Update ARM disassembler.
[qemu/mini2440.git] / vl.c
blob03859a9958ec056f12044f80f45470435b654ddd
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 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
121 #ifdef __sun__
122 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
123 #else
124 #define SMBD_COMMAND "/usr/sbin/smbd"
125 #endif
127 //#define DEBUG_UNUSED_IOPORT
128 //#define DEBUG_IOPORT
130 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
132 #ifdef TARGET_PPC
133 #define DEFAULT_RAM_SIZE 144
134 #else
135 #define DEFAULT_RAM_SIZE 128
136 #endif
137 /* in ms */
138 #define GUI_REFRESH_INTERVAL 30
140 /* Max number of USB devices that can be specified on the commandline. */
141 #define MAX_USB_CMDLINE 8
143 /* XXX: use a two level table to limit memory usage */
144 #define MAX_IOPORTS 65536
146 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
147 const char *bios_name = NULL;
148 char phys_ram_file[1024];
149 void *ioport_opaque[MAX_IOPORTS];
150 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
151 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
152 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
153 to store the VM snapshots */
154 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
155 BlockDriverState *pflash_table[MAX_PFLASH];
156 BlockDriverState *sd_bdrv;
157 BlockDriverState *mtd_bdrv;
158 /* point to the block driver where the snapshots are managed */
159 BlockDriverState *bs_snapshots;
160 int vga_ram_size;
161 static DisplayState display_state;
162 int nographic;
163 const char* keyboard_layout = NULL;
164 int64_t ticks_per_sec;
165 #if defined(TARGET_I386)
166 #define MAX_BOOT_DEVICES 3
167 #else
168 #define MAX_BOOT_DEVICES 1
169 #endif
170 static char boot_device[MAX_BOOT_DEVICES + 1];
171 int ram_size;
172 int pit_min_timer_count = 0;
173 int nb_nics;
174 NICInfo nd_table[MAX_NICS];
175 int vm_running;
176 int rtc_utc = 1;
177 int rtc_start_date = -1; /* -1 means now */
178 int cirrus_vga_enabled = 1;
179 int vmsvga_enabled = 0;
180 #ifdef TARGET_SPARC
181 int graphic_width = 1024;
182 int graphic_height = 768;
183 int graphic_depth = 8;
184 #else
185 int graphic_width = 800;
186 int graphic_height = 600;
187 int graphic_depth = 15;
188 #endif
189 int full_screen = 0;
190 int no_frame = 0;
191 int no_quit = 0;
192 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
193 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
194 #ifdef TARGET_I386
195 int win2k_install_hack = 0;
196 #endif
197 int usb_enabled = 0;
198 static VLANState *first_vlan;
199 int smp_cpus = 1;
200 const char *vnc_display;
201 #if defined(TARGET_SPARC)
202 #define MAX_CPUS 16
203 #elif defined(TARGET_I386)
204 #define MAX_CPUS 255
205 #else
206 #define MAX_CPUS 1
207 #endif
208 int acpi_enabled = 1;
209 int fd_bootchk = 1;
210 int no_reboot = 0;
211 int cursor_hide = 1;
212 int graphic_rotate = 0;
213 int daemonize = 0;
214 const char *option_rom[MAX_OPTION_ROMS];
215 int nb_option_roms;
216 int semihosting_enabled = 0;
217 int autostart = 1;
218 #ifdef TARGET_ARM
219 int old_param = 0;
220 #endif
221 const char *qemu_name;
222 int alt_grab = 0;
223 #ifdef TARGET_SPARC
224 unsigned int nb_prom_envs = 0;
225 const char *prom_envs[MAX_PROM_ENVS];
226 #endif
228 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
230 /***********************************************************/
231 /* x86 ISA bus support */
233 target_phys_addr_t isa_mem_base = 0;
234 PicState2 *isa_pic;
236 uint32_t default_ioport_readb(void *opaque, uint32_t address)
238 #ifdef DEBUG_UNUSED_IOPORT
239 fprintf(stderr, "unused inb: port=0x%04x\n", address);
240 #endif
241 return 0xff;
244 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
246 #ifdef DEBUG_UNUSED_IOPORT
247 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
248 #endif
251 /* default is to make two byte accesses */
252 uint32_t default_ioport_readw(void *opaque, uint32_t address)
254 uint32_t data;
255 data = ioport_read_table[0][address](ioport_opaque[address], address);
256 address = (address + 1) & (MAX_IOPORTS - 1);
257 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
258 return data;
261 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
263 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
264 address = (address + 1) & (MAX_IOPORTS - 1);
265 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
268 uint32_t default_ioport_readl(void *opaque, uint32_t address)
270 #ifdef DEBUG_UNUSED_IOPORT
271 fprintf(stderr, "unused inl: port=0x%04x\n", address);
272 #endif
273 return 0xffffffff;
276 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
278 #ifdef DEBUG_UNUSED_IOPORT
279 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
280 #endif
283 void init_ioports(void)
285 int i;
287 for(i = 0; i < MAX_IOPORTS; i++) {
288 ioport_read_table[0][i] = default_ioport_readb;
289 ioport_write_table[0][i] = default_ioport_writeb;
290 ioport_read_table[1][i] = default_ioport_readw;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_read_table[2][i] = default_ioport_readl;
293 ioport_write_table[2][i] = default_ioport_writel;
297 /* size is the word size in byte */
298 int register_ioport_read(int start, int length, int size,
299 IOPortReadFunc *func, void *opaque)
301 int i, bsize;
303 if (size == 1) {
304 bsize = 0;
305 } else if (size == 2) {
306 bsize = 1;
307 } else if (size == 4) {
308 bsize = 2;
309 } else {
310 hw_error("register_ioport_read: invalid size");
311 return -1;
313 for(i = start; i < start + length; i += size) {
314 ioport_read_table[bsize][i] = func;
315 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
316 hw_error("register_ioport_read: invalid opaque");
317 ioport_opaque[i] = opaque;
319 return 0;
322 /* size is the word size in byte */
323 int register_ioport_write(int start, int length, int size,
324 IOPortWriteFunc *func, void *opaque)
326 int i, bsize;
328 if (size == 1) {
329 bsize = 0;
330 } else if (size == 2) {
331 bsize = 1;
332 } else if (size == 4) {
333 bsize = 2;
334 } else {
335 hw_error("register_ioport_write: invalid size");
336 return -1;
338 for(i = start; i < start + length; i += size) {
339 ioport_write_table[bsize][i] = func;
340 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
341 hw_error("register_ioport_write: invalid opaque");
342 ioport_opaque[i] = opaque;
344 return 0;
347 void isa_unassign_ioport(int start, int length)
349 int i;
351 for(i = start; i < start + length; i++) {
352 ioport_read_table[0][i] = default_ioport_readb;
353 ioport_read_table[1][i] = default_ioport_readw;
354 ioport_read_table[2][i] = default_ioport_readl;
356 ioport_write_table[0][i] = default_ioport_writeb;
357 ioport_write_table[1][i] = default_ioport_writew;
358 ioport_write_table[2][i] = default_ioport_writel;
362 /***********************************************************/
364 void cpu_outb(CPUState *env, int addr, int val)
366 #ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outb: %04x %02x\n", addr, val);
369 #endif
370 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
371 #ifdef USE_KQEMU
372 if (env)
373 env->last_io_time = cpu_get_time_fast();
374 #endif
377 void cpu_outw(CPUState *env, int addr, int val)
379 #ifdef DEBUG_IOPORT
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "outw: %04x %04x\n", addr, val);
382 #endif
383 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384 #ifdef USE_KQEMU
385 if (env)
386 env->last_io_time = cpu_get_time_fast();
387 #endif
390 void cpu_outl(CPUState *env, int addr, int val)
392 #ifdef DEBUG_IOPORT
393 if (loglevel & CPU_LOG_IOPORT)
394 fprintf(logfile, "outl: %04x %08x\n", addr, val);
395 #endif
396 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
403 int cpu_inb(CPUState *env, int addr)
405 int val;
406 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
407 #ifdef DEBUG_IOPORT
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "inb : %04x %02x\n", addr, val);
410 #endif
411 #ifdef USE_KQEMU
412 if (env)
413 env->last_io_time = cpu_get_time_fast();
414 #endif
415 return val;
418 int cpu_inw(CPUState *env, int addr)
420 int val;
421 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
422 #ifdef DEBUG_IOPORT
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "inw : %04x %04x\n", addr, val);
425 #endif
426 #ifdef USE_KQEMU
427 if (env)
428 env->last_io_time = cpu_get_time_fast();
429 #endif
430 return val;
433 int cpu_inl(CPUState *env, int addr)
435 int val;
436 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "inl : %04x %08x\n", addr, val);
440 #endif
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
445 return val;
448 /***********************************************************/
449 void hw_error(const char *fmt, ...)
451 va_list ap;
452 CPUState *env;
454 va_start(ap, fmt);
455 fprintf(stderr, "qemu: hardware error: ");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
458 for(env = first_cpu; env != NULL; env = env->next_cpu) {
459 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
460 #ifdef TARGET_I386
461 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
462 #else
463 cpu_dump_state(env, stderr, fprintf, 0);
464 #endif
466 va_end(ap);
467 abort();
470 /***********************************************************/
471 /* keyboard/mouse */
473 static QEMUPutKBDEvent *qemu_put_kbd_event;
474 static void *qemu_put_kbd_event_opaque;
475 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
476 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
478 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
480 qemu_put_kbd_event_opaque = opaque;
481 qemu_put_kbd_event = func;
484 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
485 void *opaque, int absolute,
486 const char *name)
488 QEMUPutMouseEntry *s, *cursor;
490 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
491 if (!s)
492 return NULL;
494 s->qemu_put_mouse_event = func;
495 s->qemu_put_mouse_event_opaque = opaque;
496 s->qemu_put_mouse_event_absolute = absolute;
497 s->qemu_put_mouse_event_name = qemu_strdup(name);
498 s->next = NULL;
500 if (!qemu_put_mouse_event_head) {
501 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
502 return s;
505 cursor = qemu_put_mouse_event_head;
506 while (cursor->next != NULL)
507 cursor = cursor->next;
509 cursor->next = s;
510 qemu_put_mouse_event_current = s;
512 return s;
515 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
517 QEMUPutMouseEntry *prev = NULL, *cursor;
519 if (!qemu_put_mouse_event_head || entry == NULL)
520 return;
522 cursor = qemu_put_mouse_event_head;
523 while (cursor != NULL && cursor != entry) {
524 prev = cursor;
525 cursor = cursor->next;
528 if (cursor == NULL) // does not exist or list empty
529 return;
530 else if (prev == NULL) { // entry is head
531 qemu_put_mouse_event_head = cursor->next;
532 if (qemu_put_mouse_event_current == entry)
533 qemu_put_mouse_event_current = cursor->next;
534 qemu_free(entry->qemu_put_mouse_event_name);
535 qemu_free(entry);
536 return;
539 prev->next = entry->next;
541 if (qemu_put_mouse_event_current == entry)
542 qemu_put_mouse_event_current = prev;
544 qemu_free(entry->qemu_put_mouse_event_name);
545 qemu_free(entry);
548 void kbd_put_keycode(int keycode)
550 if (qemu_put_kbd_event) {
551 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
555 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
557 QEMUPutMouseEvent *mouse_event;
558 void *mouse_event_opaque;
559 int width;
561 if (!qemu_put_mouse_event_current) {
562 return;
565 mouse_event =
566 qemu_put_mouse_event_current->qemu_put_mouse_event;
567 mouse_event_opaque =
568 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
570 if (mouse_event) {
571 if (graphic_rotate) {
572 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
573 width = 0x7fff;
574 else
575 width = graphic_width;
576 mouse_event(mouse_event_opaque,
577 width - dy, dx, dz, buttons_state);
578 } else
579 mouse_event(mouse_event_opaque,
580 dx, dy, dz, buttons_state);
584 int kbd_mouse_is_absolute(void)
586 if (!qemu_put_mouse_event_current)
587 return 0;
589 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
592 void do_info_mice(void)
594 QEMUPutMouseEntry *cursor;
595 int index = 0;
597 if (!qemu_put_mouse_event_head) {
598 term_printf("No mouse devices connected\n");
599 return;
602 term_printf("Mouse devices available:\n");
603 cursor = qemu_put_mouse_event_head;
604 while (cursor != NULL) {
605 term_printf("%c Mouse #%d: %s\n",
606 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
607 index, cursor->qemu_put_mouse_event_name);
608 index++;
609 cursor = cursor->next;
613 void do_mouse_set(int index)
615 QEMUPutMouseEntry *cursor;
616 int i = 0;
618 if (!qemu_put_mouse_event_head) {
619 term_printf("No mouse devices connected\n");
620 return;
623 cursor = qemu_put_mouse_event_head;
624 while (cursor != NULL && index != i) {
625 i++;
626 cursor = cursor->next;
629 if (cursor != NULL)
630 qemu_put_mouse_event_current = cursor;
631 else
632 term_printf("Mouse at given index not found\n");
635 /* compute with 96 bit intermediate result: (a*b)/c */
636 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
638 union {
639 uint64_t ll;
640 struct {
641 #ifdef WORDS_BIGENDIAN
642 uint32_t high, low;
643 #else
644 uint32_t low, high;
645 #endif
646 } l;
647 } u, res;
648 uint64_t rl, rh;
650 u.ll = a;
651 rl = (uint64_t)u.l.low * (uint64_t)b;
652 rh = (uint64_t)u.l.high * (uint64_t)b;
653 rh += (rl >> 32);
654 res.l.high = rh / c;
655 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
656 return res.ll;
659 /***********************************************************/
660 /* real time host monotonic timer */
662 #define QEMU_TIMER_BASE 1000000000LL
664 #ifdef WIN32
666 static int64_t clock_freq;
668 static void init_get_clock(void)
670 LARGE_INTEGER freq;
671 int ret;
672 ret = QueryPerformanceFrequency(&freq);
673 if (ret == 0) {
674 fprintf(stderr, "Could not calibrate ticks\n");
675 exit(1);
677 clock_freq = freq.QuadPart;
680 static int64_t get_clock(void)
682 LARGE_INTEGER ti;
683 QueryPerformanceCounter(&ti);
684 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
687 #else
689 static int use_rt_clock;
691 static void init_get_clock(void)
693 use_rt_clock = 0;
694 #if defined(__linux__)
696 struct timespec ts;
697 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
698 use_rt_clock = 1;
701 #endif
704 static int64_t get_clock(void)
706 #if defined(__linux__)
707 if (use_rt_clock) {
708 struct timespec ts;
709 clock_gettime(CLOCK_MONOTONIC, &ts);
710 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
711 } else
712 #endif
714 /* XXX: using gettimeofday leads to problems if the date
715 changes, so it should be avoided. */
716 struct timeval tv;
717 gettimeofday(&tv, NULL);
718 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
722 #endif
724 /***********************************************************/
725 /* guest cycle counter */
727 static int64_t cpu_ticks_prev;
728 static int64_t cpu_ticks_offset;
729 static int64_t cpu_clock_offset;
730 static int cpu_ticks_enabled;
732 /* return the host CPU cycle counter and handle stop/restart */
733 int64_t cpu_get_ticks(void)
735 if (!cpu_ticks_enabled) {
736 return cpu_ticks_offset;
737 } else {
738 int64_t ticks;
739 ticks = cpu_get_real_ticks();
740 if (cpu_ticks_prev > ticks) {
741 /* Note: non increasing ticks may happen if the host uses
742 software suspend */
743 cpu_ticks_offset += cpu_ticks_prev - ticks;
745 cpu_ticks_prev = ticks;
746 return ticks + cpu_ticks_offset;
750 /* return the host CPU monotonic timer and handle stop/restart */
751 static int64_t cpu_get_clock(void)
753 int64_t ti;
754 if (!cpu_ticks_enabled) {
755 return cpu_clock_offset;
756 } else {
757 ti = get_clock();
758 return ti + cpu_clock_offset;
762 /* enable cpu_get_ticks() */
763 void cpu_enable_ticks(void)
765 if (!cpu_ticks_enabled) {
766 cpu_ticks_offset -= cpu_get_real_ticks();
767 cpu_clock_offset -= get_clock();
768 cpu_ticks_enabled = 1;
772 /* disable cpu_get_ticks() : the clock is stopped. You must not call
773 cpu_get_ticks() after that. */
774 void cpu_disable_ticks(void)
776 if (cpu_ticks_enabled) {
777 cpu_ticks_offset = cpu_get_ticks();
778 cpu_clock_offset = cpu_get_clock();
779 cpu_ticks_enabled = 0;
783 /***********************************************************/
784 /* timers */
786 #define QEMU_TIMER_REALTIME 0
787 #define QEMU_TIMER_VIRTUAL 1
789 struct QEMUClock {
790 int type;
791 /* XXX: add frequency */
794 struct QEMUTimer {
795 QEMUClock *clock;
796 int64_t expire_time;
797 QEMUTimerCB *cb;
798 void *opaque;
799 struct QEMUTimer *next;
802 struct qemu_alarm_timer {
803 char const *name;
804 unsigned int flags;
806 int (*start)(struct qemu_alarm_timer *t);
807 void (*stop)(struct qemu_alarm_timer *t);
808 void (*rearm)(struct qemu_alarm_timer *t);
809 void *priv;
812 #define ALARM_FLAG_DYNTICKS 0x1
814 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
816 return t->flags & ALARM_FLAG_DYNTICKS;
819 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
821 if (!alarm_has_dynticks(t))
822 return;
824 t->rearm(t);
827 /* TODO: MIN_TIMER_REARM_US should be optimized */
828 #define MIN_TIMER_REARM_US 250
830 static struct qemu_alarm_timer *alarm_timer;
832 #ifdef _WIN32
834 struct qemu_alarm_win32 {
835 MMRESULT timerId;
836 HANDLE host_alarm;
837 unsigned int period;
838 } alarm_win32_data = {0, NULL, -1};
840 static int win32_start_timer(struct qemu_alarm_timer *t);
841 static void win32_stop_timer(struct qemu_alarm_timer *t);
842 static void win32_rearm_timer(struct qemu_alarm_timer *t);
844 #else
846 static int unix_start_timer(struct qemu_alarm_timer *t);
847 static void unix_stop_timer(struct qemu_alarm_timer *t);
849 #ifdef __linux__
851 static int dynticks_start_timer(struct qemu_alarm_timer *t);
852 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
853 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
855 static int hpet_start_timer(struct qemu_alarm_timer *t);
856 static void hpet_stop_timer(struct qemu_alarm_timer *t);
858 static int rtc_start_timer(struct qemu_alarm_timer *t);
859 static void rtc_stop_timer(struct qemu_alarm_timer *t);
861 #endif /* __linux__ */
863 #endif /* _WIN32 */
865 static struct qemu_alarm_timer alarm_timers[] = {
866 #ifndef _WIN32
867 #ifdef __linux__
868 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
869 dynticks_stop_timer, dynticks_rearm_timer, NULL},
870 /* HPET - if available - is preferred */
871 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
872 /* ...otherwise try RTC */
873 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
874 #endif
875 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
876 #else
877 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
878 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
879 {"win32", 0, win32_start_timer,
880 win32_stop_timer, NULL, &alarm_win32_data},
881 #endif
882 {NULL, }
885 static void show_available_alarms()
887 int i;
889 printf("Available alarm timers, in order of precedence:\n");
890 for (i = 0; alarm_timers[i].name; i++)
891 printf("%s\n", alarm_timers[i].name);
894 static void configure_alarms(char const *opt)
896 int i;
897 int cur = 0;
898 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
899 char *arg;
900 char *name;
902 if (!strcmp(opt, "help")) {
903 show_available_alarms();
904 exit(0);
907 arg = strdup(opt);
909 /* Reorder the array */
910 name = strtok(arg, ",");
911 while (name) {
912 struct qemu_alarm_timer tmp;
914 for (i = 0; i < count && alarm_timers[i].name; i++) {
915 if (!strcmp(alarm_timers[i].name, name))
916 break;
919 if (i == count) {
920 fprintf(stderr, "Unknown clock %s\n", name);
921 goto next;
924 if (i < cur)
925 /* Ignore */
926 goto next;
928 /* Swap */
929 tmp = alarm_timers[i];
930 alarm_timers[i] = alarm_timers[cur];
931 alarm_timers[cur] = tmp;
933 cur++;
934 next:
935 name = strtok(NULL, ",");
938 free(arg);
940 if (cur) {
941 /* Disable remaining timers */
942 for (i = cur; i < count; i++)
943 alarm_timers[i].name = NULL;
946 /* debug */
947 show_available_alarms();
950 QEMUClock *rt_clock;
951 QEMUClock *vm_clock;
953 static QEMUTimer *active_timers[2];
955 QEMUClock *qemu_new_clock(int type)
957 QEMUClock *clock;
958 clock = qemu_mallocz(sizeof(QEMUClock));
959 if (!clock)
960 return NULL;
961 clock->type = type;
962 return clock;
965 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
967 QEMUTimer *ts;
969 ts = qemu_mallocz(sizeof(QEMUTimer));
970 ts->clock = clock;
971 ts->cb = cb;
972 ts->opaque = opaque;
973 return ts;
976 void qemu_free_timer(QEMUTimer *ts)
978 qemu_free(ts);
981 /* stop a timer, but do not dealloc it */
982 void qemu_del_timer(QEMUTimer *ts)
984 QEMUTimer **pt, *t;
986 /* NOTE: this code must be signal safe because
987 qemu_timer_expired() can be called from a signal. */
988 pt = &active_timers[ts->clock->type];
989 for(;;) {
990 t = *pt;
991 if (!t)
992 break;
993 if (t == ts) {
994 *pt = t->next;
995 break;
997 pt = &t->next;
1001 /* modify the current timer so that it will be fired when current_time
1002 >= expire_time. The corresponding callback will be called. */
1003 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1005 QEMUTimer **pt, *t;
1007 qemu_del_timer(ts);
1009 /* add the timer in the sorted list */
1010 /* NOTE: this code must be signal safe because
1011 qemu_timer_expired() can be called from a signal. */
1012 pt = &active_timers[ts->clock->type];
1013 for(;;) {
1014 t = *pt;
1015 if (!t)
1016 break;
1017 if (t->expire_time > expire_time)
1018 break;
1019 pt = &t->next;
1021 ts->expire_time = expire_time;
1022 ts->next = *pt;
1023 *pt = ts;
1026 int qemu_timer_pending(QEMUTimer *ts)
1028 QEMUTimer *t;
1029 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1030 if (t == ts)
1031 return 1;
1033 return 0;
1036 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1038 if (!timer_head)
1039 return 0;
1040 return (timer_head->expire_time <= current_time);
1043 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1045 QEMUTimer *ts;
1047 for(;;) {
1048 ts = *ptimer_head;
1049 if (!ts || ts->expire_time > current_time)
1050 break;
1051 /* remove timer from the list before calling the callback */
1052 *ptimer_head = ts->next;
1053 ts->next = NULL;
1055 /* run the callback (the timer list can be modified) */
1056 ts->cb(ts->opaque);
1058 qemu_rearm_alarm_timer(alarm_timer);
1061 int64_t qemu_get_clock(QEMUClock *clock)
1063 switch(clock->type) {
1064 case QEMU_TIMER_REALTIME:
1065 return get_clock() / 1000000;
1066 default:
1067 case QEMU_TIMER_VIRTUAL:
1068 return cpu_get_clock();
1072 static void init_timers(void)
1074 init_get_clock();
1075 ticks_per_sec = QEMU_TIMER_BASE;
1076 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1077 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1080 /* save a timer */
1081 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1083 uint64_t expire_time;
1085 if (qemu_timer_pending(ts)) {
1086 expire_time = ts->expire_time;
1087 } else {
1088 expire_time = -1;
1090 qemu_put_be64(f, expire_time);
1093 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1095 uint64_t expire_time;
1097 expire_time = qemu_get_be64(f);
1098 if (expire_time != -1) {
1099 qemu_mod_timer(ts, expire_time);
1100 } else {
1101 qemu_del_timer(ts);
1105 static void timer_save(QEMUFile *f, void *opaque)
1107 if (cpu_ticks_enabled) {
1108 hw_error("cannot save state if virtual timers are running");
1110 qemu_put_be64s(f, &cpu_ticks_offset);
1111 qemu_put_be64s(f, &ticks_per_sec);
1112 qemu_put_be64s(f, &cpu_clock_offset);
1115 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1117 if (version_id != 1 && version_id != 2)
1118 return -EINVAL;
1119 if (cpu_ticks_enabled) {
1120 return -EINVAL;
1122 qemu_get_be64s(f, &cpu_ticks_offset);
1123 qemu_get_be64s(f, &ticks_per_sec);
1124 if (version_id == 2) {
1125 qemu_get_be64s(f, &cpu_clock_offset);
1127 return 0;
1130 #ifdef _WIN32
1131 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1132 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1133 #else
1134 static void host_alarm_handler(int host_signum)
1135 #endif
1137 #if 0
1138 #define DISP_FREQ 1000
1140 static int64_t delta_min = INT64_MAX;
1141 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1142 static int count;
1143 ti = qemu_get_clock(vm_clock);
1144 if (last_clock != 0) {
1145 delta = ti - last_clock;
1146 if (delta < delta_min)
1147 delta_min = delta;
1148 if (delta > delta_max)
1149 delta_max = delta;
1150 delta_cum += delta;
1151 if (++count == DISP_FREQ) {
1152 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1153 muldiv64(delta_min, 1000000, ticks_per_sec),
1154 muldiv64(delta_max, 1000000, ticks_per_sec),
1155 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1156 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1157 count = 0;
1158 delta_min = INT64_MAX;
1159 delta_max = 0;
1160 delta_cum = 0;
1163 last_clock = ti;
1165 #endif
1166 if (alarm_has_dynticks(alarm_timer) ||
1167 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1168 qemu_get_clock(vm_clock)) ||
1169 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1170 qemu_get_clock(rt_clock))) {
1171 #ifdef _WIN32
1172 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1173 SetEvent(data->host_alarm);
1174 #endif
1175 CPUState *env = cpu_single_env;
1176 if (env) {
1177 /* stop the currently executing cpu because a timer occured */
1178 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1179 #ifdef USE_KQEMU
1180 if (env->kqemu_enabled) {
1181 kqemu_cpu_interrupt(env);
1183 #endif
1188 static uint64_t qemu_next_deadline(void)
1190 int64_t nearest_delta_us = INT64_MAX;
1191 int64_t vmdelta_us;
1193 if (active_timers[QEMU_TIMER_REALTIME])
1194 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1195 qemu_get_clock(rt_clock))*1000;
1197 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1198 /* round up */
1199 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1200 qemu_get_clock(vm_clock)+999)/1000;
1201 if (vmdelta_us < nearest_delta_us)
1202 nearest_delta_us = vmdelta_us;
1205 /* Avoid arming the timer to negative, zero, or too low values */
1206 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1207 nearest_delta_us = MIN_TIMER_REARM_US;
1209 return nearest_delta_us;
1212 #ifndef _WIN32
1214 #if defined(__linux__)
1216 #define RTC_FREQ 1024
1218 static void enable_sigio_timer(int fd)
1220 struct sigaction act;
1222 /* timer signal */
1223 sigfillset(&act.sa_mask);
1224 act.sa_flags = 0;
1225 act.sa_handler = host_alarm_handler;
1227 sigaction(SIGIO, &act, NULL);
1228 fcntl(fd, F_SETFL, O_ASYNC);
1229 fcntl(fd, F_SETOWN, getpid());
1232 static int hpet_start_timer(struct qemu_alarm_timer *t)
1234 struct hpet_info info;
1235 int r, fd;
1237 fd = open("/dev/hpet", O_RDONLY);
1238 if (fd < 0)
1239 return -1;
1241 /* Set frequency */
1242 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1243 if (r < 0) {
1244 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1245 "error, but for better emulation accuracy type:\n"
1246 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1247 goto fail;
1250 /* Check capabilities */
1251 r = ioctl(fd, HPET_INFO, &info);
1252 if (r < 0)
1253 goto fail;
1255 /* Enable periodic mode */
1256 r = ioctl(fd, HPET_EPI, 0);
1257 if (info.hi_flags && (r < 0))
1258 goto fail;
1260 /* Enable interrupt */
1261 r = ioctl(fd, HPET_IE_ON, 0);
1262 if (r < 0)
1263 goto fail;
1265 enable_sigio_timer(fd);
1266 t->priv = (void *)(long)fd;
1268 return 0;
1269 fail:
1270 close(fd);
1271 return -1;
1274 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1276 int fd = (long)t->priv;
1278 close(fd);
1281 static int rtc_start_timer(struct qemu_alarm_timer *t)
1283 int rtc_fd;
1285 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1286 if (rtc_fd < 0)
1287 return -1;
1288 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1289 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1290 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1291 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1292 goto fail;
1294 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1295 fail:
1296 close(rtc_fd);
1297 return -1;
1300 enable_sigio_timer(rtc_fd);
1302 t->priv = (void *)(long)rtc_fd;
1304 return 0;
1307 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd = (long)t->priv;
1311 close(rtc_fd);
1314 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1316 struct sigevent ev;
1317 timer_t host_timer;
1318 struct sigaction act;
1320 sigfillset(&act.sa_mask);
1321 act.sa_flags = 0;
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 act.sa_handler = host_alarm_handler;
1398 sigaction(SIGALRM, &act, NULL);
1400 itv.it_interval.tv_sec = 0;
1401 /* for i386 kernel 2.6 to get 1 ms */
1402 itv.it_interval.tv_usec = 999;
1403 itv.it_value.tv_sec = 0;
1404 itv.it_value.tv_usec = 10 * 1000;
1406 err = setitimer(ITIMER_REAL, &itv, NULL);
1407 if (err)
1408 return -1;
1410 return 0;
1413 static void unix_stop_timer(struct qemu_alarm_timer *t)
1415 struct itimerval itv;
1417 memset(&itv, 0, sizeof(itv));
1418 setitimer(ITIMER_REAL, &itv, NULL);
1421 #endif /* !defined(_WIN32) */
1423 #ifdef _WIN32
1425 static int win32_start_timer(struct qemu_alarm_timer *t)
1427 TIMECAPS tc;
1428 struct qemu_alarm_win32 *data = t->priv;
1429 UINT flags;
1431 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1432 if (!data->host_alarm) {
1433 perror("Failed CreateEvent");
1434 return -1;
1437 memset(&tc, 0, sizeof(tc));
1438 timeGetDevCaps(&tc, sizeof(tc));
1440 if (data->period < tc.wPeriodMin)
1441 data->period = tc.wPeriodMin;
1443 timeBeginPeriod(data->period);
1445 flags = TIME_CALLBACK_FUNCTION;
1446 if (alarm_has_dynticks(t))
1447 flags |= TIME_ONESHOT;
1448 else
1449 flags |= TIME_PERIODIC;
1451 data->timerId = timeSetEvent(1, // interval (ms)
1452 data->period, // resolution
1453 host_alarm_handler, // function
1454 (DWORD)t, // parameter
1455 flags);
1457 if (!data->timerId) {
1458 perror("Failed to initialize win32 alarm timer");
1460 timeEndPeriod(data->period);
1461 CloseHandle(data->host_alarm);
1462 return -1;
1465 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1467 return 0;
1470 static void win32_stop_timer(struct qemu_alarm_timer *t)
1472 struct qemu_alarm_win32 *data = t->priv;
1474 timeKillEvent(data->timerId);
1475 timeEndPeriod(data->period);
1477 CloseHandle(data->host_alarm);
1480 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1482 struct qemu_alarm_win32 *data = t->priv;
1483 uint64_t nearest_delta_us;
1485 if (!active_timers[QEMU_TIMER_REALTIME] &&
1486 !active_timers[QEMU_TIMER_VIRTUAL])
1487 return;
1489 nearest_delta_us = qemu_next_deadline();
1490 nearest_delta_us /= 1000;
1492 timeKillEvent(data->timerId);
1494 data->timerId = timeSetEvent(1,
1495 data->period,
1496 host_alarm_handler,
1497 (DWORD)t,
1498 TIME_ONESHOT | TIME_PERIODIC);
1500 if (!data->timerId) {
1501 perror("Failed to re-arm win32 alarm timer");
1503 timeEndPeriod(data->period);
1504 CloseHandle(data->host_alarm);
1505 exit(1);
1509 #endif /* _WIN32 */
1511 static void init_timer_alarm(void)
1513 struct qemu_alarm_timer *t;
1514 int i, err = -1;
1516 for (i = 0; alarm_timers[i].name; i++) {
1517 t = &alarm_timers[i];
1519 err = t->start(t);
1520 if (!err)
1521 break;
1524 if (err) {
1525 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1526 fprintf(stderr, "Terminating\n");
1527 exit(1);
1530 alarm_timer = t;
1533 void quit_timers(void)
1535 alarm_timer->stop(alarm_timer);
1536 alarm_timer = NULL;
1539 /***********************************************************/
1540 /* character device */
1542 static void qemu_chr_event(CharDriverState *s, int event)
1544 if (!s->chr_event)
1545 return;
1546 s->chr_event(s->handler_opaque, event);
1549 static void qemu_chr_reset_bh(void *opaque)
1551 CharDriverState *s = opaque;
1552 qemu_chr_event(s, CHR_EVENT_RESET);
1553 qemu_bh_delete(s->bh);
1554 s->bh = NULL;
1557 void qemu_chr_reset(CharDriverState *s)
1559 if (s->bh == NULL) {
1560 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1561 qemu_bh_schedule(s->bh);
1565 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1567 return s->chr_write(s, buf, len);
1570 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1572 if (!s->chr_ioctl)
1573 return -ENOTSUP;
1574 return s->chr_ioctl(s, cmd, arg);
1577 int qemu_chr_can_read(CharDriverState *s)
1579 if (!s->chr_can_read)
1580 return 0;
1581 return s->chr_can_read(s->handler_opaque);
1584 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1586 s->chr_read(s->handler_opaque, buf, len);
1590 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1592 char buf[4096];
1593 va_list ap;
1594 va_start(ap, fmt);
1595 vsnprintf(buf, sizeof(buf), fmt, ap);
1596 qemu_chr_write(s, buf, strlen(buf));
1597 va_end(ap);
1600 void qemu_chr_send_event(CharDriverState *s, int event)
1602 if (s->chr_send_event)
1603 s->chr_send_event(s, event);
1606 void qemu_chr_add_handlers(CharDriverState *s,
1607 IOCanRWHandler *fd_can_read,
1608 IOReadHandler *fd_read,
1609 IOEventHandler *fd_event,
1610 void *opaque)
1612 s->chr_can_read = fd_can_read;
1613 s->chr_read = fd_read;
1614 s->chr_event = fd_event;
1615 s->handler_opaque = opaque;
1616 if (s->chr_update_read_handler)
1617 s->chr_update_read_handler(s);
1620 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1622 return len;
1625 static CharDriverState *qemu_chr_open_null(void)
1627 CharDriverState *chr;
1629 chr = qemu_mallocz(sizeof(CharDriverState));
1630 if (!chr)
1631 return NULL;
1632 chr->chr_write = null_chr_write;
1633 return chr;
1636 /* MUX driver for serial I/O splitting */
1637 static int term_timestamps;
1638 static int64_t term_timestamps_start;
1639 #define MAX_MUX 4
1640 typedef struct {
1641 IOCanRWHandler *chr_can_read[MAX_MUX];
1642 IOReadHandler *chr_read[MAX_MUX];
1643 IOEventHandler *chr_event[MAX_MUX];
1644 void *ext_opaque[MAX_MUX];
1645 CharDriverState *drv;
1646 int mux_cnt;
1647 int term_got_escape;
1648 int max_size;
1649 } MuxDriver;
1652 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1654 MuxDriver *d = chr->opaque;
1655 int ret;
1656 if (!term_timestamps) {
1657 ret = d->drv->chr_write(d->drv, buf, len);
1658 } else {
1659 int i;
1661 ret = 0;
1662 for(i = 0; i < len; i++) {
1663 ret += d->drv->chr_write(d->drv, buf+i, 1);
1664 if (buf[i] == '\n') {
1665 char buf1[64];
1666 int64_t ti;
1667 int secs;
1669 ti = get_clock();
1670 if (term_timestamps_start == -1)
1671 term_timestamps_start = ti;
1672 ti -= term_timestamps_start;
1673 secs = ti / 1000000000;
1674 snprintf(buf1, sizeof(buf1),
1675 "[%02d:%02d:%02d.%03d] ",
1676 secs / 3600,
1677 (secs / 60) % 60,
1678 secs % 60,
1679 (int)((ti / 1000000) % 1000));
1680 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1684 return ret;
1687 static char *mux_help[] = {
1688 "% h print this help\n\r",
1689 "% x exit emulator\n\r",
1690 "% s save disk data back to file (if -snapshot)\n\r",
1691 "% t toggle console timestamps\n\r"
1692 "% b send break (magic sysrq)\n\r",
1693 "% c switch between console and monitor\n\r",
1694 "% % sends %\n\r",
1695 NULL
1698 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1699 static void mux_print_help(CharDriverState *chr)
1701 int i, j;
1702 char ebuf[15] = "Escape-Char";
1703 char cbuf[50] = "\n\r";
1705 if (term_escape_char > 0 && term_escape_char < 26) {
1706 sprintf(cbuf,"\n\r");
1707 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1708 } else {
1709 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1711 chr->chr_write(chr, cbuf, strlen(cbuf));
1712 for (i = 0; mux_help[i] != NULL; i++) {
1713 for (j=0; mux_help[i][j] != '\0'; j++) {
1714 if (mux_help[i][j] == '%')
1715 chr->chr_write(chr, ebuf, strlen(ebuf));
1716 else
1717 chr->chr_write(chr, &mux_help[i][j], 1);
1722 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1724 if (d->term_got_escape) {
1725 d->term_got_escape = 0;
1726 if (ch == term_escape_char)
1727 goto send_char;
1728 switch(ch) {
1729 case '?':
1730 case 'h':
1731 mux_print_help(chr);
1732 break;
1733 case 'x':
1735 char *term = "QEMU: Terminated\n\r";
1736 chr->chr_write(chr,term,strlen(term));
1737 exit(0);
1738 break;
1740 case 's':
1742 int i;
1743 for (i = 0; i < MAX_DISKS; i++) {
1744 if (bs_table[i])
1745 bdrv_commit(bs_table[i]);
1747 if (mtd_bdrv)
1748 bdrv_commit(mtd_bdrv);
1750 break;
1751 case 'b':
1752 qemu_chr_event(chr, CHR_EVENT_BREAK);
1753 break;
1754 case 'c':
1755 /* Switch to the next registered device */
1756 chr->focus++;
1757 if (chr->focus >= d->mux_cnt)
1758 chr->focus = 0;
1759 break;
1760 case 't':
1761 term_timestamps = !term_timestamps;
1762 term_timestamps_start = -1;
1763 break;
1765 } else if (ch == term_escape_char) {
1766 d->term_got_escape = 1;
1767 } else {
1768 send_char:
1769 return 1;
1771 return 0;
1774 static int mux_chr_can_read(void *opaque)
1776 CharDriverState *chr = opaque;
1777 MuxDriver *d = chr->opaque;
1778 if (d->chr_can_read[chr->focus])
1779 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1780 return 0;
1783 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1785 CharDriverState *chr = opaque;
1786 MuxDriver *d = chr->opaque;
1787 int i;
1788 for(i = 0; i < size; i++)
1789 if (mux_proc_byte(chr, d, buf[i]))
1790 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1793 static void mux_chr_event(void *opaque, int event)
1795 CharDriverState *chr = opaque;
1796 MuxDriver *d = chr->opaque;
1797 int i;
1799 /* Send the event to all registered listeners */
1800 for (i = 0; i < d->mux_cnt; i++)
1801 if (d->chr_event[i])
1802 d->chr_event[i](d->ext_opaque[i], event);
1805 static void mux_chr_update_read_handler(CharDriverState *chr)
1807 MuxDriver *d = chr->opaque;
1809 if (d->mux_cnt >= MAX_MUX) {
1810 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1811 return;
1813 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1814 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1815 d->chr_read[d->mux_cnt] = chr->chr_read;
1816 d->chr_event[d->mux_cnt] = chr->chr_event;
1817 /* Fix up the real driver with mux routines */
1818 if (d->mux_cnt == 0) {
1819 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1820 mux_chr_event, chr);
1822 chr->focus = d->mux_cnt;
1823 d->mux_cnt++;
1826 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1828 CharDriverState *chr;
1829 MuxDriver *d;
1831 chr = qemu_mallocz(sizeof(CharDriverState));
1832 if (!chr)
1833 return NULL;
1834 d = qemu_mallocz(sizeof(MuxDriver));
1835 if (!d) {
1836 free(chr);
1837 return NULL;
1840 chr->opaque = d;
1841 d->drv = drv;
1842 chr->focus = -1;
1843 chr->chr_write = mux_chr_write;
1844 chr->chr_update_read_handler = mux_chr_update_read_handler;
1845 return chr;
1849 #ifdef _WIN32
1851 static void socket_cleanup(void)
1853 WSACleanup();
1856 static int socket_init(void)
1858 WSADATA Data;
1859 int ret, err;
1861 ret = WSAStartup(MAKEWORD(2,2), &Data);
1862 if (ret != 0) {
1863 err = WSAGetLastError();
1864 fprintf(stderr, "WSAStartup: %d\n", err);
1865 return -1;
1867 atexit(socket_cleanup);
1868 return 0;
1871 static int send_all(int fd, const uint8_t *buf, int len1)
1873 int ret, len;
1875 len = len1;
1876 while (len > 0) {
1877 ret = send(fd, buf, len, 0);
1878 if (ret < 0) {
1879 int errno;
1880 errno = WSAGetLastError();
1881 if (errno != WSAEWOULDBLOCK) {
1882 return -1;
1884 } else if (ret == 0) {
1885 break;
1886 } else {
1887 buf += ret;
1888 len -= ret;
1891 return len1 - len;
1894 void socket_set_nonblock(int fd)
1896 unsigned long opt = 1;
1897 ioctlsocket(fd, FIONBIO, &opt);
1900 #else
1902 static int unix_write(int fd, const uint8_t *buf, int len1)
1904 int ret, len;
1906 len = len1;
1907 while (len > 0) {
1908 ret = write(fd, buf, len);
1909 if (ret < 0) {
1910 if (errno != EINTR && errno != EAGAIN)
1911 return -1;
1912 } else if (ret == 0) {
1913 break;
1914 } else {
1915 buf += ret;
1916 len -= ret;
1919 return len1 - len;
1922 static inline int send_all(int fd, const uint8_t *buf, int len1)
1924 return unix_write(fd, buf, len1);
1927 void socket_set_nonblock(int fd)
1929 fcntl(fd, F_SETFL, O_NONBLOCK);
1931 #endif /* !_WIN32 */
1933 #ifndef _WIN32
1935 typedef struct {
1936 int fd_in, fd_out;
1937 int max_size;
1938 } FDCharDriver;
1940 #define STDIO_MAX_CLIENTS 1
1941 static int stdio_nb_clients = 0;
1943 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1945 FDCharDriver *s = chr->opaque;
1946 return unix_write(s->fd_out, buf, len);
1949 static int fd_chr_read_poll(void *opaque)
1951 CharDriverState *chr = opaque;
1952 FDCharDriver *s = chr->opaque;
1954 s->max_size = qemu_chr_can_read(chr);
1955 return s->max_size;
1958 static void fd_chr_read(void *opaque)
1960 CharDriverState *chr = opaque;
1961 FDCharDriver *s = chr->opaque;
1962 int size, len;
1963 uint8_t buf[1024];
1965 len = sizeof(buf);
1966 if (len > s->max_size)
1967 len = s->max_size;
1968 if (len == 0)
1969 return;
1970 size = read(s->fd_in, buf, len);
1971 if (size == 0) {
1972 /* FD has been closed. Remove it from the active list. */
1973 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1974 return;
1976 if (size > 0) {
1977 qemu_chr_read(chr, buf, size);
1981 static void fd_chr_update_read_handler(CharDriverState *chr)
1983 FDCharDriver *s = chr->opaque;
1985 if (s->fd_in >= 0) {
1986 if (nographic && s->fd_in == 0) {
1987 } else {
1988 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1989 fd_chr_read, NULL, chr);
1994 /* open a character device to a unix fd */
1995 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1997 CharDriverState *chr;
1998 FDCharDriver *s;
2000 chr = qemu_mallocz(sizeof(CharDriverState));
2001 if (!chr)
2002 return NULL;
2003 s = qemu_mallocz(sizeof(FDCharDriver));
2004 if (!s) {
2005 free(chr);
2006 return NULL;
2008 s->fd_in = fd_in;
2009 s->fd_out = fd_out;
2010 chr->opaque = s;
2011 chr->chr_write = fd_chr_write;
2012 chr->chr_update_read_handler = fd_chr_update_read_handler;
2014 qemu_chr_reset(chr);
2016 return chr;
2019 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2021 int fd_out;
2023 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2024 if (fd_out < 0)
2025 return NULL;
2026 return qemu_chr_open_fd(-1, fd_out);
2029 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2031 int fd_in, fd_out;
2032 char filename_in[256], filename_out[256];
2034 snprintf(filename_in, 256, "%s.in", filename);
2035 snprintf(filename_out, 256, "%s.out", filename);
2036 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2037 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2038 if (fd_in < 0 || fd_out < 0) {
2039 if (fd_in >= 0)
2040 close(fd_in);
2041 if (fd_out >= 0)
2042 close(fd_out);
2043 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2044 if (fd_in < 0)
2045 return NULL;
2047 return qemu_chr_open_fd(fd_in, fd_out);
2051 /* for STDIO, we handle the case where several clients use it
2052 (nographic mode) */
2054 #define TERM_FIFO_MAX_SIZE 1
2056 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2057 static int term_fifo_size;
2059 static int stdio_read_poll(void *opaque)
2061 CharDriverState *chr = opaque;
2063 /* try to flush the queue if needed */
2064 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2065 qemu_chr_read(chr, term_fifo, 1);
2066 term_fifo_size = 0;
2068 /* see if we can absorb more chars */
2069 if (term_fifo_size == 0)
2070 return 1;
2071 else
2072 return 0;
2075 static void stdio_read(void *opaque)
2077 int size;
2078 uint8_t buf[1];
2079 CharDriverState *chr = opaque;
2081 size = read(0, buf, 1);
2082 if (size == 0) {
2083 /* stdin has been closed. Remove it from the active list. */
2084 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2085 return;
2087 if (size > 0) {
2088 if (qemu_chr_can_read(chr) > 0) {
2089 qemu_chr_read(chr, buf, 1);
2090 } else if (term_fifo_size == 0) {
2091 term_fifo[term_fifo_size++] = buf[0];
2096 /* init terminal so that we can grab keys */
2097 static struct termios oldtty;
2098 static int old_fd0_flags;
2100 static void term_exit(void)
2102 tcsetattr (0, TCSANOW, &oldtty);
2103 fcntl(0, F_SETFL, old_fd0_flags);
2106 static void term_init(void)
2108 struct termios tty;
2110 tcgetattr (0, &tty);
2111 oldtty = tty;
2112 old_fd0_flags = fcntl(0, F_GETFL);
2114 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2115 |INLCR|IGNCR|ICRNL|IXON);
2116 tty.c_oflag |= OPOST;
2117 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2118 /* if graphical mode, we allow Ctrl-C handling */
2119 if (nographic)
2120 tty.c_lflag &= ~ISIG;
2121 tty.c_cflag &= ~(CSIZE|PARENB);
2122 tty.c_cflag |= CS8;
2123 tty.c_cc[VMIN] = 1;
2124 tty.c_cc[VTIME] = 0;
2126 tcsetattr (0, TCSANOW, &tty);
2128 atexit(term_exit);
2130 fcntl(0, F_SETFL, O_NONBLOCK);
2133 static CharDriverState *qemu_chr_open_stdio(void)
2135 CharDriverState *chr;
2137 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2138 return NULL;
2139 chr = qemu_chr_open_fd(0, 1);
2140 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2141 stdio_nb_clients++;
2142 term_init();
2144 return chr;
2147 #if defined(__linux__) || defined(__sun__)
2148 static CharDriverState *qemu_chr_open_pty(void)
2150 struct termios tty;
2151 char slave_name[1024];
2152 int master_fd, slave_fd;
2154 #if defined(__linux__)
2155 /* Not satisfying */
2156 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2157 return NULL;
2159 #endif
2161 /* Disabling local echo and line-buffered output */
2162 tcgetattr (master_fd, &tty);
2163 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2164 tty.c_cc[VMIN] = 1;
2165 tty.c_cc[VTIME] = 0;
2166 tcsetattr (master_fd, TCSAFLUSH, &tty);
2168 fprintf(stderr, "char device redirected to %s\n", slave_name);
2169 return qemu_chr_open_fd(master_fd, master_fd);
2172 static void tty_serial_init(int fd, int speed,
2173 int parity, int data_bits, int stop_bits)
2175 struct termios tty;
2176 speed_t spd;
2178 #if 0
2179 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2180 speed, parity, data_bits, stop_bits);
2181 #endif
2182 tcgetattr (fd, &tty);
2184 switch(speed) {
2185 case 50:
2186 spd = B50;
2187 break;
2188 case 75:
2189 spd = B75;
2190 break;
2191 case 300:
2192 spd = B300;
2193 break;
2194 case 600:
2195 spd = B600;
2196 break;
2197 case 1200:
2198 spd = B1200;
2199 break;
2200 case 2400:
2201 spd = B2400;
2202 break;
2203 case 4800:
2204 spd = B4800;
2205 break;
2206 case 9600:
2207 spd = B9600;
2208 break;
2209 case 19200:
2210 spd = B19200;
2211 break;
2212 case 38400:
2213 spd = B38400;
2214 break;
2215 case 57600:
2216 spd = B57600;
2217 break;
2218 default:
2219 case 115200:
2220 spd = B115200;
2221 break;
2224 cfsetispeed(&tty, spd);
2225 cfsetospeed(&tty, spd);
2227 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2228 |INLCR|IGNCR|ICRNL|IXON);
2229 tty.c_oflag |= OPOST;
2230 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2231 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2232 switch(data_bits) {
2233 default:
2234 case 8:
2235 tty.c_cflag |= CS8;
2236 break;
2237 case 7:
2238 tty.c_cflag |= CS7;
2239 break;
2240 case 6:
2241 tty.c_cflag |= CS6;
2242 break;
2243 case 5:
2244 tty.c_cflag |= CS5;
2245 break;
2247 switch(parity) {
2248 default:
2249 case 'N':
2250 break;
2251 case 'E':
2252 tty.c_cflag |= PARENB;
2253 break;
2254 case 'O':
2255 tty.c_cflag |= PARENB | PARODD;
2256 break;
2258 if (stop_bits == 2)
2259 tty.c_cflag |= CSTOPB;
2261 tcsetattr (fd, TCSANOW, &tty);
2264 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2266 FDCharDriver *s = chr->opaque;
2268 switch(cmd) {
2269 case CHR_IOCTL_SERIAL_SET_PARAMS:
2271 QEMUSerialSetParams *ssp = arg;
2272 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2273 ssp->data_bits, ssp->stop_bits);
2275 break;
2276 case CHR_IOCTL_SERIAL_SET_BREAK:
2278 int enable = *(int *)arg;
2279 if (enable)
2280 tcsendbreak(s->fd_in, 1);
2282 break;
2283 default:
2284 return -ENOTSUP;
2286 return 0;
2289 static CharDriverState *qemu_chr_open_tty(const char *filename)
2291 CharDriverState *chr;
2292 int fd;
2294 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2295 fcntl(fd, F_SETFL, O_NONBLOCK);
2296 tty_serial_init(fd, 115200, 'N', 8, 1);
2297 chr = qemu_chr_open_fd(fd, fd);
2298 if (!chr) {
2299 close(fd);
2300 return NULL;
2302 chr->chr_ioctl = tty_serial_ioctl;
2303 qemu_chr_reset(chr);
2304 return chr;
2306 #else /* ! __linux__ && ! __sun__ */
2307 static CharDriverState *qemu_chr_open_pty(void)
2309 return NULL;
2311 #endif /* __linux__ || __sun__ */
2313 #if defined(__linux__)
2314 typedef struct {
2315 int fd;
2316 int mode;
2317 } ParallelCharDriver;
2319 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2321 if (s->mode != mode) {
2322 int m = mode;
2323 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2324 return 0;
2325 s->mode = mode;
2327 return 1;
2330 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2332 ParallelCharDriver *drv = chr->opaque;
2333 int fd = drv->fd;
2334 uint8_t b;
2336 switch(cmd) {
2337 case CHR_IOCTL_PP_READ_DATA:
2338 if (ioctl(fd, PPRDATA, &b) < 0)
2339 return -ENOTSUP;
2340 *(uint8_t *)arg = b;
2341 break;
2342 case CHR_IOCTL_PP_WRITE_DATA:
2343 b = *(uint8_t *)arg;
2344 if (ioctl(fd, PPWDATA, &b) < 0)
2345 return -ENOTSUP;
2346 break;
2347 case CHR_IOCTL_PP_READ_CONTROL:
2348 if (ioctl(fd, PPRCONTROL, &b) < 0)
2349 return -ENOTSUP;
2350 /* Linux gives only the lowest bits, and no way to know data
2351 direction! For better compatibility set the fixed upper
2352 bits. */
2353 *(uint8_t *)arg = b | 0xc0;
2354 break;
2355 case CHR_IOCTL_PP_WRITE_CONTROL:
2356 b = *(uint8_t *)arg;
2357 if (ioctl(fd, PPWCONTROL, &b) < 0)
2358 return -ENOTSUP;
2359 break;
2360 case CHR_IOCTL_PP_READ_STATUS:
2361 if (ioctl(fd, PPRSTATUS, &b) < 0)
2362 return -ENOTSUP;
2363 *(uint8_t *)arg = b;
2364 break;
2365 case CHR_IOCTL_PP_EPP_READ_ADDR:
2366 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2367 struct ParallelIOArg *parg = arg;
2368 int n = read(fd, parg->buffer, parg->count);
2369 if (n != parg->count) {
2370 return -EIO;
2373 break;
2374 case CHR_IOCTL_PP_EPP_READ:
2375 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2376 struct ParallelIOArg *parg = arg;
2377 int n = read(fd, parg->buffer, parg->count);
2378 if (n != parg->count) {
2379 return -EIO;
2382 break;
2383 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2384 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2385 struct ParallelIOArg *parg = arg;
2386 int n = write(fd, parg->buffer, parg->count);
2387 if (n != parg->count) {
2388 return -EIO;
2391 break;
2392 case CHR_IOCTL_PP_EPP_WRITE:
2393 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2394 struct ParallelIOArg *parg = arg;
2395 int n = write(fd, parg->buffer, parg->count);
2396 if (n != parg->count) {
2397 return -EIO;
2400 break;
2401 default:
2402 return -ENOTSUP;
2404 return 0;
2407 static void pp_close(CharDriverState *chr)
2409 ParallelCharDriver *drv = chr->opaque;
2410 int fd = drv->fd;
2412 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2413 ioctl(fd, PPRELEASE);
2414 close(fd);
2415 qemu_free(drv);
2418 static CharDriverState *qemu_chr_open_pp(const char *filename)
2420 CharDriverState *chr;
2421 ParallelCharDriver *drv;
2422 int fd;
2424 TFR(fd = open(filename, O_RDWR));
2425 if (fd < 0)
2426 return NULL;
2428 if (ioctl(fd, PPCLAIM) < 0) {
2429 close(fd);
2430 return NULL;
2433 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2434 if (!drv) {
2435 close(fd);
2436 return NULL;
2438 drv->fd = fd;
2439 drv->mode = IEEE1284_MODE_COMPAT;
2441 chr = qemu_mallocz(sizeof(CharDriverState));
2442 if (!chr) {
2443 qemu_free(drv);
2444 close(fd);
2445 return NULL;
2447 chr->chr_write = null_chr_write;
2448 chr->chr_ioctl = pp_ioctl;
2449 chr->chr_close = pp_close;
2450 chr->opaque = drv;
2452 qemu_chr_reset(chr);
2454 return chr;
2456 #endif /* __linux__ */
2458 #else /* _WIN32 */
2460 typedef struct {
2461 int max_size;
2462 HANDLE hcom, hrecv, hsend;
2463 OVERLAPPED orecv, osend;
2464 BOOL fpipe;
2465 DWORD len;
2466 } WinCharState;
2468 #define NSENDBUF 2048
2469 #define NRECVBUF 2048
2470 #define MAXCONNECT 1
2471 #define NTIMEOUT 5000
2473 static int win_chr_poll(void *opaque);
2474 static int win_chr_pipe_poll(void *opaque);
2476 static void win_chr_close(CharDriverState *chr)
2478 WinCharState *s = chr->opaque;
2480 if (s->hsend) {
2481 CloseHandle(s->hsend);
2482 s->hsend = NULL;
2484 if (s->hrecv) {
2485 CloseHandle(s->hrecv);
2486 s->hrecv = NULL;
2488 if (s->hcom) {
2489 CloseHandle(s->hcom);
2490 s->hcom = NULL;
2492 if (s->fpipe)
2493 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2494 else
2495 qemu_del_polling_cb(win_chr_poll, chr);
2498 static int win_chr_init(CharDriverState *chr, const char *filename)
2500 WinCharState *s = chr->opaque;
2501 COMMCONFIG comcfg;
2502 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2503 COMSTAT comstat;
2504 DWORD size;
2505 DWORD err;
2507 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2508 if (!s->hsend) {
2509 fprintf(stderr, "Failed CreateEvent\n");
2510 goto fail;
2512 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2513 if (!s->hrecv) {
2514 fprintf(stderr, "Failed CreateEvent\n");
2515 goto fail;
2518 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2519 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2520 if (s->hcom == INVALID_HANDLE_VALUE) {
2521 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2522 s->hcom = NULL;
2523 goto fail;
2526 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2527 fprintf(stderr, "Failed SetupComm\n");
2528 goto fail;
2531 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2532 size = sizeof(COMMCONFIG);
2533 GetDefaultCommConfig(filename, &comcfg, &size);
2534 comcfg.dcb.DCBlength = sizeof(DCB);
2535 CommConfigDialog(filename, NULL, &comcfg);
2537 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2538 fprintf(stderr, "Failed SetCommState\n");
2539 goto fail;
2542 if (!SetCommMask(s->hcom, EV_ERR)) {
2543 fprintf(stderr, "Failed SetCommMask\n");
2544 goto fail;
2547 cto.ReadIntervalTimeout = MAXDWORD;
2548 if (!SetCommTimeouts(s->hcom, &cto)) {
2549 fprintf(stderr, "Failed SetCommTimeouts\n");
2550 goto fail;
2553 if (!ClearCommError(s->hcom, &err, &comstat)) {
2554 fprintf(stderr, "Failed ClearCommError\n");
2555 goto fail;
2557 qemu_add_polling_cb(win_chr_poll, chr);
2558 return 0;
2560 fail:
2561 win_chr_close(chr);
2562 return -1;
2565 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2567 WinCharState *s = chr->opaque;
2568 DWORD len, ret, size, err;
2570 len = len1;
2571 ZeroMemory(&s->osend, sizeof(s->osend));
2572 s->osend.hEvent = s->hsend;
2573 while (len > 0) {
2574 if (s->hsend)
2575 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2576 else
2577 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2578 if (!ret) {
2579 err = GetLastError();
2580 if (err == ERROR_IO_PENDING) {
2581 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2582 if (ret) {
2583 buf += size;
2584 len -= size;
2585 } else {
2586 break;
2588 } else {
2589 break;
2591 } else {
2592 buf += size;
2593 len -= size;
2596 return len1 - len;
2599 static int win_chr_read_poll(CharDriverState *chr)
2601 WinCharState *s = chr->opaque;
2603 s->max_size = qemu_chr_can_read(chr);
2604 return s->max_size;
2607 static void win_chr_readfile(CharDriverState *chr)
2609 WinCharState *s = chr->opaque;
2610 int ret, err;
2611 uint8_t buf[1024];
2612 DWORD size;
2614 ZeroMemory(&s->orecv, sizeof(s->orecv));
2615 s->orecv.hEvent = s->hrecv;
2616 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2617 if (!ret) {
2618 err = GetLastError();
2619 if (err == ERROR_IO_PENDING) {
2620 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2624 if (size > 0) {
2625 qemu_chr_read(chr, buf, size);
2629 static void win_chr_read(CharDriverState *chr)
2631 WinCharState *s = chr->opaque;
2633 if (s->len > s->max_size)
2634 s->len = s->max_size;
2635 if (s->len == 0)
2636 return;
2638 win_chr_readfile(chr);
2641 static int win_chr_poll(void *opaque)
2643 CharDriverState *chr = opaque;
2644 WinCharState *s = chr->opaque;
2645 COMSTAT status;
2646 DWORD comerr;
2648 ClearCommError(s->hcom, &comerr, &status);
2649 if (status.cbInQue > 0) {
2650 s->len = status.cbInQue;
2651 win_chr_read_poll(chr);
2652 win_chr_read(chr);
2653 return 1;
2655 return 0;
2658 static CharDriverState *qemu_chr_open_win(const char *filename)
2660 CharDriverState *chr;
2661 WinCharState *s;
2663 chr = qemu_mallocz(sizeof(CharDriverState));
2664 if (!chr)
2665 return NULL;
2666 s = qemu_mallocz(sizeof(WinCharState));
2667 if (!s) {
2668 free(chr);
2669 return NULL;
2671 chr->opaque = s;
2672 chr->chr_write = win_chr_write;
2673 chr->chr_close = win_chr_close;
2675 if (win_chr_init(chr, filename) < 0) {
2676 free(s);
2677 free(chr);
2678 return NULL;
2680 qemu_chr_reset(chr);
2681 return chr;
2684 static int win_chr_pipe_poll(void *opaque)
2686 CharDriverState *chr = opaque;
2687 WinCharState *s = chr->opaque;
2688 DWORD size;
2690 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2691 if (size > 0) {
2692 s->len = size;
2693 win_chr_read_poll(chr);
2694 win_chr_read(chr);
2695 return 1;
2697 return 0;
2700 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2702 WinCharState *s = chr->opaque;
2703 OVERLAPPED ov;
2704 int ret;
2705 DWORD size;
2706 char openname[256];
2708 s->fpipe = TRUE;
2710 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2711 if (!s->hsend) {
2712 fprintf(stderr, "Failed CreateEvent\n");
2713 goto fail;
2715 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2716 if (!s->hrecv) {
2717 fprintf(stderr, "Failed CreateEvent\n");
2718 goto fail;
2721 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2722 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2723 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2724 PIPE_WAIT,
2725 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2726 if (s->hcom == INVALID_HANDLE_VALUE) {
2727 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2728 s->hcom = NULL;
2729 goto fail;
2732 ZeroMemory(&ov, sizeof(ov));
2733 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2734 ret = ConnectNamedPipe(s->hcom, &ov);
2735 if (ret) {
2736 fprintf(stderr, "Failed ConnectNamedPipe\n");
2737 goto fail;
2740 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2741 if (!ret) {
2742 fprintf(stderr, "Failed GetOverlappedResult\n");
2743 if (ov.hEvent) {
2744 CloseHandle(ov.hEvent);
2745 ov.hEvent = NULL;
2747 goto fail;
2750 if (ov.hEvent) {
2751 CloseHandle(ov.hEvent);
2752 ov.hEvent = NULL;
2754 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2755 return 0;
2757 fail:
2758 win_chr_close(chr);
2759 return -1;
2763 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2765 CharDriverState *chr;
2766 WinCharState *s;
2768 chr = qemu_mallocz(sizeof(CharDriverState));
2769 if (!chr)
2770 return NULL;
2771 s = qemu_mallocz(sizeof(WinCharState));
2772 if (!s) {
2773 free(chr);
2774 return NULL;
2776 chr->opaque = s;
2777 chr->chr_write = win_chr_write;
2778 chr->chr_close = win_chr_close;
2780 if (win_chr_pipe_init(chr, filename) < 0) {
2781 free(s);
2782 free(chr);
2783 return NULL;
2785 qemu_chr_reset(chr);
2786 return chr;
2789 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2791 CharDriverState *chr;
2792 WinCharState *s;
2794 chr = qemu_mallocz(sizeof(CharDriverState));
2795 if (!chr)
2796 return NULL;
2797 s = qemu_mallocz(sizeof(WinCharState));
2798 if (!s) {
2799 free(chr);
2800 return NULL;
2802 s->hcom = fd_out;
2803 chr->opaque = s;
2804 chr->chr_write = win_chr_write;
2805 qemu_chr_reset(chr);
2806 return chr;
2809 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2811 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2814 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2816 HANDLE fd_out;
2818 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2819 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2820 if (fd_out == INVALID_HANDLE_VALUE)
2821 return NULL;
2823 return qemu_chr_open_win_file(fd_out);
2825 #endif /* !_WIN32 */
2827 /***********************************************************/
2828 /* UDP Net console */
2830 typedef struct {
2831 int fd;
2832 struct sockaddr_in daddr;
2833 char buf[1024];
2834 int bufcnt;
2835 int bufptr;
2836 int max_size;
2837 } NetCharDriver;
2839 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2841 NetCharDriver *s = chr->opaque;
2843 return sendto(s->fd, buf, len, 0,
2844 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2847 static int udp_chr_read_poll(void *opaque)
2849 CharDriverState *chr = opaque;
2850 NetCharDriver *s = chr->opaque;
2852 s->max_size = qemu_chr_can_read(chr);
2854 /* If there were any stray characters in the queue process them
2855 * first
2857 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2858 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2859 s->bufptr++;
2860 s->max_size = qemu_chr_can_read(chr);
2862 return s->max_size;
2865 static void udp_chr_read(void *opaque)
2867 CharDriverState *chr = opaque;
2868 NetCharDriver *s = chr->opaque;
2870 if (s->max_size == 0)
2871 return;
2872 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2873 s->bufptr = s->bufcnt;
2874 if (s->bufcnt <= 0)
2875 return;
2877 s->bufptr = 0;
2878 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2879 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2880 s->bufptr++;
2881 s->max_size = qemu_chr_can_read(chr);
2885 static void udp_chr_update_read_handler(CharDriverState *chr)
2887 NetCharDriver *s = chr->opaque;
2889 if (s->fd >= 0) {
2890 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2891 udp_chr_read, NULL, chr);
2895 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2896 #ifndef _WIN32
2897 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2898 #endif
2899 int parse_host_src_port(struct sockaddr_in *haddr,
2900 struct sockaddr_in *saddr,
2901 const char *str);
2903 static CharDriverState *qemu_chr_open_udp(const char *def)
2905 CharDriverState *chr = NULL;
2906 NetCharDriver *s = NULL;
2907 int fd = -1;
2908 struct sockaddr_in saddr;
2910 chr = qemu_mallocz(sizeof(CharDriverState));
2911 if (!chr)
2912 goto return_err;
2913 s = qemu_mallocz(sizeof(NetCharDriver));
2914 if (!s)
2915 goto return_err;
2917 fd = socket(PF_INET, SOCK_DGRAM, 0);
2918 if (fd < 0) {
2919 perror("socket(PF_INET, SOCK_DGRAM)");
2920 goto return_err;
2923 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2924 printf("Could not parse: %s\n", def);
2925 goto return_err;
2928 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2930 perror("bind");
2931 goto return_err;
2934 s->fd = fd;
2935 s->bufcnt = 0;
2936 s->bufptr = 0;
2937 chr->opaque = s;
2938 chr->chr_write = udp_chr_write;
2939 chr->chr_update_read_handler = udp_chr_update_read_handler;
2940 return chr;
2942 return_err:
2943 if (chr)
2944 free(chr);
2945 if (s)
2946 free(s);
2947 if (fd >= 0)
2948 closesocket(fd);
2949 return NULL;
2952 /***********************************************************/
2953 /* TCP Net console */
2955 typedef struct {
2956 int fd, listen_fd;
2957 int connected;
2958 int max_size;
2959 int do_telnetopt;
2960 int do_nodelay;
2961 int is_unix;
2962 } TCPCharDriver;
2964 static void tcp_chr_accept(void *opaque);
2966 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2968 TCPCharDriver *s = chr->opaque;
2969 if (s->connected) {
2970 return send_all(s->fd, buf, len);
2971 } else {
2972 /* XXX: indicate an error ? */
2973 return len;
2977 static int tcp_chr_read_poll(void *opaque)
2979 CharDriverState *chr = opaque;
2980 TCPCharDriver *s = chr->opaque;
2981 if (!s->connected)
2982 return 0;
2983 s->max_size = qemu_chr_can_read(chr);
2984 return s->max_size;
2987 #define IAC 255
2988 #define IAC_BREAK 243
2989 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2990 TCPCharDriver *s,
2991 char *buf, int *size)
2993 /* Handle any telnet client's basic IAC options to satisfy char by
2994 * char mode with no echo. All IAC options will be removed from
2995 * the buf and the do_telnetopt variable will be used to track the
2996 * state of the width of the IAC information.
2998 * IAC commands come in sets of 3 bytes with the exception of the
2999 * "IAC BREAK" command and the double IAC.
3002 int i;
3003 int j = 0;
3005 for (i = 0; i < *size; i++) {
3006 if (s->do_telnetopt > 1) {
3007 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3008 /* Double IAC means send an IAC */
3009 if (j != i)
3010 buf[j] = buf[i];
3011 j++;
3012 s->do_telnetopt = 1;
3013 } else {
3014 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3015 /* Handle IAC break commands by sending a serial break */
3016 qemu_chr_event(chr, CHR_EVENT_BREAK);
3017 s->do_telnetopt++;
3019 s->do_telnetopt++;
3021 if (s->do_telnetopt >= 4) {
3022 s->do_telnetopt = 1;
3024 } else {
3025 if ((unsigned char)buf[i] == IAC) {
3026 s->do_telnetopt = 2;
3027 } else {
3028 if (j != i)
3029 buf[j] = buf[i];
3030 j++;
3034 *size = j;
3037 static void tcp_chr_read(void *opaque)
3039 CharDriverState *chr = opaque;
3040 TCPCharDriver *s = chr->opaque;
3041 uint8_t buf[1024];
3042 int len, size;
3044 if (!s->connected || s->max_size <= 0)
3045 return;
3046 len = sizeof(buf);
3047 if (len > s->max_size)
3048 len = s->max_size;
3049 size = recv(s->fd, buf, len, 0);
3050 if (size == 0) {
3051 /* connection closed */
3052 s->connected = 0;
3053 if (s->listen_fd >= 0) {
3054 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3056 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3057 closesocket(s->fd);
3058 s->fd = -1;
3059 } else if (size > 0) {
3060 if (s->do_telnetopt)
3061 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3062 if (size > 0)
3063 qemu_chr_read(chr, buf, size);
3067 static void tcp_chr_connect(void *opaque)
3069 CharDriverState *chr = opaque;
3070 TCPCharDriver *s = chr->opaque;
3072 s->connected = 1;
3073 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3074 tcp_chr_read, NULL, chr);
3075 qemu_chr_reset(chr);
3078 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3079 static void tcp_chr_telnet_init(int fd)
3081 char buf[3];
3082 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3083 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3084 send(fd, (char *)buf, 3, 0);
3085 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3086 send(fd, (char *)buf, 3, 0);
3087 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3088 send(fd, (char *)buf, 3, 0);
3089 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3090 send(fd, (char *)buf, 3, 0);
3093 static void socket_set_nodelay(int fd)
3095 int val = 1;
3096 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3099 static void tcp_chr_accept(void *opaque)
3101 CharDriverState *chr = opaque;
3102 TCPCharDriver *s = chr->opaque;
3103 struct sockaddr_in saddr;
3104 #ifndef _WIN32
3105 struct sockaddr_un uaddr;
3106 #endif
3107 struct sockaddr *addr;
3108 socklen_t len;
3109 int fd;
3111 for(;;) {
3112 #ifndef _WIN32
3113 if (s->is_unix) {
3114 len = sizeof(uaddr);
3115 addr = (struct sockaddr *)&uaddr;
3116 } else
3117 #endif
3119 len = sizeof(saddr);
3120 addr = (struct sockaddr *)&saddr;
3122 fd = accept(s->listen_fd, addr, &len);
3123 if (fd < 0 && errno != EINTR) {
3124 return;
3125 } else if (fd >= 0) {
3126 if (s->do_telnetopt)
3127 tcp_chr_telnet_init(fd);
3128 break;
3131 socket_set_nonblock(fd);
3132 if (s->do_nodelay)
3133 socket_set_nodelay(fd);
3134 s->fd = fd;
3135 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3136 tcp_chr_connect(chr);
3139 static void tcp_chr_close(CharDriverState *chr)
3141 TCPCharDriver *s = chr->opaque;
3142 if (s->fd >= 0)
3143 closesocket(s->fd);
3144 if (s->listen_fd >= 0)
3145 closesocket(s->listen_fd);
3146 qemu_free(s);
3149 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3150 int is_telnet,
3151 int is_unix)
3153 CharDriverState *chr = NULL;
3154 TCPCharDriver *s = NULL;
3155 int fd = -1, ret, err, val;
3156 int is_listen = 0;
3157 int is_waitconnect = 1;
3158 int do_nodelay = 0;
3159 const char *ptr;
3160 struct sockaddr_in saddr;
3161 #ifndef _WIN32
3162 struct sockaddr_un uaddr;
3163 #endif
3164 struct sockaddr *addr;
3165 socklen_t addrlen;
3167 #ifndef _WIN32
3168 if (is_unix) {
3169 addr = (struct sockaddr *)&uaddr;
3170 addrlen = sizeof(uaddr);
3171 if (parse_unix_path(&uaddr, host_str) < 0)
3172 goto fail;
3173 } else
3174 #endif
3176 addr = (struct sockaddr *)&saddr;
3177 addrlen = sizeof(saddr);
3178 if (parse_host_port(&saddr, host_str) < 0)
3179 goto fail;
3182 ptr = host_str;
3183 while((ptr = strchr(ptr,','))) {
3184 ptr++;
3185 if (!strncmp(ptr,"server",6)) {
3186 is_listen = 1;
3187 } else if (!strncmp(ptr,"nowait",6)) {
3188 is_waitconnect = 0;
3189 } else if (!strncmp(ptr,"nodelay",6)) {
3190 do_nodelay = 1;
3191 } else {
3192 printf("Unknown option: %s\n", ptr);
3193 goto fail;
3196 if (!is_listen)
3197 is_waitconnect = 0;
3199 chr = qemu_mallocz(sizeof(CharDriverState));
3200 if (!chr)
3201 goto fail;
3202 s = qemu_mallocz(sizeof(TCPCharDriver));
3203 if (!s)
3204 goto fail;
3206 #ifndef _WIN32
3207 if (is_unix)
3208 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3209 else
3210 #endif
3211 fd = socket(PF_INET, SOCK_STREAM, 0);
3213 if (fd < 0)
3214 goto fail;
3216 if (!is_waitconnect)
3217 socket_set_nonblock(fd);
3219 s->connected = 0;
3220 s->fd = -1;
3221 s->listen_fd = -1;
3222 s->is_unix = is_unix;
3223 s->do_nodelay = do_nodelay && !is_unix;
3225 chr->opaque = s;
3226 chr->chr_write = tcp_chr_write;
3227 chr->chr_close = tcp_chr_close;
3229 if (is_listen) {
3230 /* allow fast reuse */
3231 #ifndef _WIN32
3232 if (is_unix) {
3233 char path[109];
3234 strncpy(path, uaddr.sun_path, 108);
3235 path[108] = 0;
3236 unlink(path);
3237 } else
3238 #endif
3240 val = 1;
3241 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3244 ret = bind(fd, addr, addrlen);
3245 if (ret < 0)
3246 goto fail;
3248 ret = listen(fd, 0);
3249 if (ret < 0)
3250 goto fail;
3252 s->listen_fd = fd;
3253 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3254 if (is_telnet)
3255 s->do_telnetopt = 1;
3256 } else {
3257 for(;;) {
3258 ret = connect(fd, addr, addrlen);
3259 if (ret < 0) {
3260 err = socket_error();
3261 if (err == EINTR || err == EWOULDBLOCK) {
3262 } else if (err == EINPROGRESS) {
3263 break;
3264 #ifdef _WIN32
3265 } else if (err == WSAEALREADY) {
3266 break;
3267 #endif
3268 } else {
3269 goto fail;
3271 } else {
3272 s->connected = 1;
3273 break;
3276 s->fd = fd;
3277 socket_set_nodelay(fd);
3278 if (s->connected)
3279 tcp_chr_connect(chr);
3280 else
3281 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3284 if (is_listen && is_waitconnect) {
3285 printf("QEMU waiting for connection on: %s\n", host_str);
3286 tcp_chr_accept(chr);
3287 socket_set_nonblock(s->listen_fd);
3290 return chr;
3291 fail:
3292 if (fd >= 0)
3293 closesocket(fd);
3294 qemu_free(s);
3295 qemu_free(chr);
3296 return NULL;
3299 CharDriverState *qemu_chr_open(const char *filename)
3301 const char *p;
3303 if (!strcmp(filename, "vc")) {
3304 return text_console_init(&display_state, 0);
3305 } else if (strstart(filename, "vc:", &p)) {
3306 return text_console_init(&display_state, p);
3307 } else if (!strcmp(filename, "null")) {
3308 return qemu_chr_open_null();
3309 } else
3310 if (strstart(filename, "tcp:", &p)) {
3311 return qemu_chr_open_tcp(p, 0, 0);
3312 } else
3313 if (strstart(filename, "telnet:", &p)) {
3314 return qemu_chr_open_tcp(p, 1, 0);
3315 } else
3316 if (strstart(filename, "udp:", &p)) {
3317 return qemu_chr_open_udp(p);
3318 } else
3319 if (strstart(filename, "mon:", &p)) {
3320 CharDriverState *drv = qemu_chr_open(p);
3321 if (drv) {
3322 drv = qemu_chr_open_mux(drv);
3323 monitor_init(drv, !nographic);
3324 return drv;
3326 printf("Unable to open driver: %s\n", p);
3327 return 0;
3328 } else
3329 #ifndef _WIN32
3330 if (strstart(filename, "unix:", &p)) {
3331 return qemu_chr_open_tcp(p, 0, 1);
3332 } else if (strstart(filename, "file:", &p)) {
3333 return qemu_chr_open_file_out(p);
3334 } else if (strstart(filename, "pipe:", &p)) {
3335 return qemu_chr_open_pipe(p);
3336 } else if (!strcmp(filename, "pty")) {
3337 return qemu_chr_open_pty();
3338 } else if (!strcmp(filename, "stdio")) {
3339 return qemu_chr_open_stdio();
3340 } else
3341 #if defined(__linux__)
3342 if (strstart(filename, "/dev/parport", NULL)) {
3343 return qemu_chr_open_pp(filename);
3344 } else
3345 #endif
3346 #if defined(__linux__) || defined(__sun__)
3347 if (strstart(filename, "/dev/", NULL)) {
3348 return qemu_chr_open_tty(filename);
3349 } else
3350 #endif
3351 #else /* !_WIN32 */
3352 if (strstart(filename, "COM", NULL)) {
3353 return qemu_chr_open_win(filename);
3354 } else
3355 if (strstart(filename, "pipe:", &p)) {
3356 return qemu_chr_open_win_pipe(p);
3357 } else
3358 if (strstart(filename, "con:", NULL)) {
3359 return qemu_chr_open_win_con(filename);
3360 } else
3361 if (strstart(filename, "file:", &p)) {
3362 return qemu_chr_open_win_file_out(p);
3364 #endif
3366 return NULL;
3370 void qemu_chr_close(CharDriverState *chr)
3372 if (chr->chr_close)
3373 chr->chr_close(chr);
3376 /***********************************************************/
3377 /* network device redirectors */
3379 void hex_dump(FILE *f, const uint8_t *buf, int size)
3381 int len, i, j, c;
3383 for(i=0;i<size;i+=16) {
3384 len = size - i;
3385 if (len > 16)
3386 len = 16;
3387 fprintf(f, "%08x ", i);
3388 for(j=0;j<16;j++) {
3389 if (j < len)
3390 fprintf(f, " %02x", buf[i+j]);
3391 else
3392 fprintf(f, " ");
3394 fprintf(f, " ");
3395 for(j=0;j<len;j++) {
3396 c = buf[i+j];
3397 if (c < ' ' || c > '~')
3398 c = '.';
3399 fprintf(f, "%c", c);
3401 fprintf(f, "\n");
3405 static int parse_macaddr(uint8_t *macaddr, const char *p)
3407 int i;
3408 for(i = 0; i < 6; i++) {
3409 macaddr[i] = strtol(p, (char **)&p, 16);
3410 if (i == 5) {
3411 if (*p != '\0')
3412 return -1;
3413 } else {
3414 if (*p != ':')
3415 return -1;
3416 p++;
3419 return 0;
3422 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3424 const char *p, *p1;
3425 int len;
3426 p = *pp;
3427 p1 = strchr(p, sep);
3428 if (!p1)
3429 return -1;
3430 len = p1 - p;
3431 p1++;
3432 if (buf_size > 0) {
3433 if (len > buf_size - 1)
3434 len = buf_size - 1;
3435 memcpy(buf, p, len);
3436 buf[len] = '\0';
3438 *pp = p1;
3439 return 0;
3442 int parse_host_src_port(struct sockaddr_in *haddr,
3443 struct sockaddr_in *saddr,
3444 const char *input_str)
3446 char *str = strdup(input_str);
3447 char *host_str = str;
3448 char *src_str;
3449 char *ptr;
3452 * Chop off any extra arguments at the end of the string which
3453 * would start with a comma, then fill in the src port information
3454 * if it was provided else use the "any address" and "any port".
3456 if ((ptr = strchr(str,',')))
3457 *ptr = '\0';
3459 if ((src_str = strchr(input_str,'@'))) {
3460 *src_str = '\0';
3461 src_str++;
3464 if (parse_host_port(haddr, host_str) < 0)
3465 goto fail;
3467 if (!src_str || *src_str == '\0')
3468 src_str = ":0";
3470 if (parse_host_port(saddr, src_str) < 0)
3471 goto fail;
3473 free(str);
3474 return(0);
3476 fail:
3477 free(str);
3478 return -1;
3481 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3483 char buf[512];
3484 struct hostent *he;
3485 const char *p, *r;
3486 int port;
3488 p = str;
3489 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3490 return -1;
3491 saddr->sin_family = AF_INET;
3492 if (buf[0] == '\0') {
3493 saddr->sin_addr.s_addr = 0;
3494 } else {
3495 if (isdigit(buf[0])) {
3496 if (!inet_aton(buf, &saddr->sin_addr))
3497 return -1;
3498 } else {
3499 if ((he = gethostbyname(buf)) == NULL)
3500 return - 1;
3501 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3504 port = strtol(p, (char **)&r, 0);
3505 if (r == p)
3506 return -1;
3507 saddr->sin_port = htons(port);
3508 return 0;
3511 #ifndef _WIN32
3512 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3514 const char *p;
3515 int len;
3517 len = MIN(108, strlen(str));
3518 p = strchr(str, ',');
3519 if (p)
3520 len = MIN(len, p - str);
3522 memset(uaddr, 0, sizeof(*uaddr));
3524 uaddr->sun_family = AF_UNIX;
3525 memcpy(uaddr->sun_path, str, len);
3527 return 0;
3529 #endif
3531 /* find or alloc a new VLAN */
3532 VLANState *qemu_find_vlan(int id)
3534 VLANState **pvlan, *vlan;
3535 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3536 if (vlan->id == id)
3537 return vlan;
3539 vlan = qemu_mallocz(sizeof(VLANState));
3540 if (!vlan)
3541 return NULL;
3542 vlan->id = id;
3543 vlan->next = NULL;
3544 pvlan = &first_vlan;
3545 while (*pvlan != NULL)
3546 pvlan = &(*pvlan)->next;
3547 *pvlan = vlan;
3548 return vlan;
3551 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3552 IOReadHandler *fd_read,
3553 IOCanRWHandler *fd_can_read,
3554 void *opaque)
3556 VLANClientState *vc, **pvc;
3557 vc = qemu_mallocz(sizeof(VLANClientState));
3558 if (!vc)
3559 return NULL;
3560 vc->fd_read = fd_read;
3561 vc->fd_can_read = fd_can_read;
3562 vc->opaque = opaque;
3563 vc->vlan = vlan;
3565 vc->next = NULL;
3566 pvc = &vlan->first_client;
3567 while (*pvc != NULL)
3568 pvc = &(*pvc)->next;
3569 *pvc = vc;
3570 return vc;
3573 int qemu_can_send_packet(VLANClientState *vc1)
3575 VLANState *vlan = vc1->vlan;
3576 VLANClientState *vc;
3578 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3579 if (vc != vc1) {
3580 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3581 return 1;
3584 return 0;
3587 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3589 VLANState *vlan = vc1->vlan;
3590 VLANClientState *vc;
3592 #if 0
3593 printf("vlan %d send:\n", vlan->id);
3594 hex_dump(stdout, buf, size);
3595 #endif
3596 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3597 if (vc != vc1) {
3598 vc->fd_read(vc->opaque, buf, size);
3603 #if defined(CONFIG_SLIRP)
3605 /* slirp network adapter */
3607 static int slirp_inited;
3608 static VLANClientState *slirp_vc;
3610 int slirp_can_output(void)
3612 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3615 void slirp_output(const uint8_t *pkt, int pkt_len)
3617 #if 0
3618 printf("slirp output:\n");
3619 hex_dump(stdout, pkt, pkt_len);
3620 #endif
3621 if (!slirp_vc)
3622 return;
3623 qemu_send_packet(slirp_vc, pkt, pkt_len);
3626 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3628 #if 0
3629 printf("slirp input:\n");
3630 hex_dump(stdout, buf, size);
3631 #endif
3632 slirp_input(buf, size);
3635 static int net_slirp_init(VLANState *vlan)
3637 if (!slirp_inited) {
3638 slirp_inited = 1;
3639 slirp_init();
3641 slirp_vc = qemu_new_vlan_client(vlan,
3642 slirp_receive, NULL, NULL);
3643 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3644 return 0;
3647 static void net_slirp_redir(const char *redir_str)
3649 int is_udp;
3650 char buf[256], *r;
3651 const char *p;
3652 struct in_addr guest_addr;
3653 int host_port, guest_port;
3655 if (!slirp_inited) {
3656 slirp_inited = 1;
3657 slirp_init();
3660 p = redir_str;
3661 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3662 goto fail;
3663 if (!strcmp(buf, "tcp")) {
3664 is_udp = 0;
3665 } else if (!strcmp(buf, "udp")) {
3666 is_udp = 1;
3667 } else {
3668 goto fail;
3671 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3672 goto fail;
3673 host_port = strtol(buf, &r, 0);
3674 if (r == buf)
3675 goto fail;
3677 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3678 goto fail;
3679 if (buf[0] == '\0') {
3680 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3682 if (!inet_aton(buf, &guest_addr))
3683 goto fail;
3685 guest_port = strtol(p, &r, 0);
3686 if (r == p)
3687 goto fail;
3689 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3690 fprintf(stderr, "qemu: could not set up redirection\n");
3691 exit(1);
3693 return;
3694 fail:
3695 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3696 exit(1);
3699 #ifndef _WIN32
3701 char smb_dir[1024];
3703 static void smb_exit(void)
3705 DIR *d;
3706 struct dirent *de;
3707 char filename[1024];
3709 /* erase all the files in the directory */
3710 d = opendir(smb_dir);
3711 for(;;) {
3712 de = readdir(d);
3713 if (!de)
3714 break;
3715 if (strcmp(de->d_name, ".") != 0 &&
3716 strcmp(de->d_name, "..") != 0) {
3717 snprintf(filename, sizeof(filename), "%s/%s",
3718 smb_dir, de->d_name);
3719 unlink(filename);
3722 closedir(d);
3723 rmdir(smb_dir);
3726 /* automatic user mode samba server configuration */
3727 void net_slirp_smb(const char *exported_dir)
3729 char smb_conf[1024];
3730 char smb_cmdline[1024];
3731 FILE *f;
3733 if (!slirp_inited) {
3734 slirp_inited = 1;
3735 slirp_init();
3738 /* XXX: better tmp dir construction */
3739 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3740 if (mkdir(smb_dir, 0700) < 0) {
3741 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3742 exit(1);
3744 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3746 f = fopen(smb_conf, "w");
3747 if (!f) {
3748 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3749 exit(1);
3751 fprintf(f,
3752 "[global]\n"
3753 "private dir=%s\n"
3754 "smb ports=0\n"
3755 "socket address=127.0.0.1\n"
3756 "pid directory=%s\n"
3757 "lock directory=%s\n"
3758 "log file=%s/log.smbd\n"
3759 "smb passwd file=%s/smbpasswd\n"
3760 "security = share\n"
3761 "[qemu]\n"
3762 "path=%s\n"
3763 "read only=no\n"
3764 "guest ok=yes\n",
3765 smb_dir,
3766 smb_dir,
3767 smb_dir,
3768 smb_dir,
3769 smb_dir,
3770 exported_dir
3772 fclose(f);
3773 atexit(smb_exit);
3775 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3776 SMBD_COMMAND, smb_conf);
3778 slirp_add_exec(0, smb_cmdline, 4, 139);
3781 #endif /* !defined(_WIN32) */
3782 void do_info_slirp(void)
3784 slirp_stats();
3787 #endif /* CONFIG_SLIRP */
3789 #if !defined(_WIN32)
3791 typedef struct TAPState {
3792 VLANClientState *vc;
3793 int fd;
3794 char down_script[1024];
3795 } TAPState;
3797 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3799 TAPState *s = opaque;
3800 int ret;
3801 for(;;) {
3802 ret = write(s->fd, buf, size);
3803 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3804 } else {
3805 break;
3810 static void tap_send(void *opaque)
3812 TAPState *s = opaque;
3813 uint8_t buf[4096];
3814 int size;
3816 #ifdef __sun__
3817 struct strbuf sbuf;
3818 int f = 0;
3819 sbuf.maxlen = sizeof(buf);
3820 sbuf.buf = buf;
3821 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3822 #else
3823 size = read(s->fd, buf, sizeof(buf));
3824 #endif
3825 if (size > 0) {
3826 qemu_send_packet(s->vc, buf, size);
3830 /* fd support */
3832 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3834 TAPState *s;
3836 s = qemu_mallocz(sizeof(TAPState));
3837 if (!s)
3838 return NULL;
3839 s->fd = fd;
3840 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3841 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3842 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3843 return s;
3846 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3847 static int tap_open(char *ifname, int ifname_size)
3849 int fd;
3850 char *dev;
3851 struct stat s;
3853 TFR(fd = open("/dev/tap", O_RDWR));
3854 if (fd < 0) {
3855 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3856 return -1;
3859 fstat(fd, &s);
3860 dev = devname(s.st_rdev, S_IFCHR);
3861 pstrcpy(ifname, ifname_size, dev);
3863 fcntl(fd, F_SETFL, O_NONBLOCK);
3864 return fd;
3866 #elif defined(__sun__)
3867 #define TUNNEWPPA (('T'<<16) | 0x0001)
3869 * Allocate TAP device, returns opened fd.
3870 * Stores dev name in the first arg(must be large enough).
3872 int tap_alloc(char *dev)
3874 int tap_fd, if_fd, ppa = -1;
3875 static int ip_fd = 0;
3876 char *ptr;
3878 static int arp_fd = 0;
3879 int ip_muxid, arp_muxid;
3880 struct strioctl strioc_if, strioc_ppa;
3881 int link_type = I_PLINK;;
3882 struct lifreq ifr;
3883 char actual_name[32] = "";
3885 memset(&ifr, 0x0, sizeof(ifr));
3887 if( *dev ){
3888 ptr = dev;
3889 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3890 ppa = atoi(ptr);
3893 /* Check if IP device was opened */
3894 if( ip_fd )
3895 close(ip_fd);
3897 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3898 if (ip_fd < 0) {
3899 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3900 return -1;
3903 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3904 if (tap_fd < 0) {
3905 syslog(LOG_ERR, "Can't open /dev/tap");
3906 return -1;
3909 /* Assign a new PPA and get its unit number. */
3910 strioc_ppa.ic_cmd = TUNNEWPPA;
3911 strioc_ppa.ic_timout = 0;
3912 strioc_ppa.ic_len = sizeof(ppa);
3913 strioc_ppa.ic_dp = (char *)&ppa;
3914 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3915 syslog (LOG_ERR, "Can't assign new interface");
3917 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3918 if (if_fd < 0) {
3919 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3920 return -1;
3922 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3923 syslog(LOG_ERR, "Can't push IP module");
3924 return -1;
3927 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3928 syslog(LOG_ERR, "Can't get flags\n");
3930 snprintf (actual_name, 32, "tap%d", ppa);
3931 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3933 ifr.lifr_ppa = ppa;
3934 /* Assign ppa according to the unit number returned by tun device */
3936 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3937 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3938 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3939 syslog (LOG_ERR, "Can't get flags\n");
3940 /* Push arp module to if_fd */
3941 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3942 syslog (LOG_ERR, "Can't push ARP module (2)");
3944 /* Push arp module to ip_fd */
3945 if (ioctl (ip_fd, I_POP, NULL) < 0)
3946 syslog (LOG_ERR, "I_POP failed\n");
3947 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3948 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3949 /* Open arp_fd */
3950 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3951 if (arp_fd < 0)
3952 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3954 /* Set ifname to arp */
3955 strioc_if.ic_cmd = SIOCSLIFNAME;
3956 strioc_if.ic_timout = 0;
3957 strioc_if.ic_len = sizeof(ifr);
3958 strioc_if.ic_dp = (char *)&ifr;
3959 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3960 syslog (LOG_ERR, "Can't set ifname to arp\n");
3963 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3964 syslog(LOG_ERR, "Can't link TAP device to IP");
3965 return -1;
3968 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3969 syslog (LOG_ERR, "Can't link TAP device to ARP");
3971 close (if_fd);
3973 memset(&ifr, 0x0, sizeof(ifr));
3974 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3975 ifr.lifr_ip_muxid = ip_muxid;
3976 ifr.lifr_arp_muxid = arp_muxid;
3978 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3980 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3981 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3982 syslog (LOG_ERR, "Can't set multiplexor id");
3985 sprintf(dev, "tap%d", ppa);
3986 return tap_fd;
3989 static int tap_open(char *ifname, int ifname_size)
3991 char dev[10]="";
3992 int fd;
3993 if( (fd = tap_alloc(dev)) < 0 ){
3994 fprintf(stderr, "Cannot allocate TAP device\n");
3995 return -1;
3997 pstrcpy(ifname, ifname_size, dev);
3998 fcntl(fd, F_SETFL, O_NONBLOCK);
3999 return fd;
4001 #else
4002 static int tap_open(char *ifname, int ifname_size)
4004 struct ifreq ifr;
4005 int fd, ret;
4007 TFR(fd = open("/dev/net/tun", O_RDWR));
4008 if (fd < 0) {
4009 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4010 return -1;
4012 memset(&ifr, 0, sizeof(ifr));
4013 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4014 if (ifname[0] != '\0')
4015 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4016 else
4017 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4018 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4019 if (ret != 0) {
4020 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4021 close(fd);
4022 return -1;
4024 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4025 fcntl(fd, F_SETFL, O_NONBLOCK);
4026 return fd;
4028 #endif
4030 static int launch_script(const char *setup_script, const char *ifname, int fd)
4032 int pid, status;
4033 char *args[3];
4034 char **parg;
4036 /* try to launch network script */
4037 pid = fork();
4038 if (pid >= 0) {
4039 if (pid == 0) {
4040 int open_max = sysconf (_SC_OPEN_MAX), i;
4041 for (i = 0; i < open_max; i++)
4042 if (i != STDIN_FILENO &&
4043 i != STDOUT_FILENO &&
4044 i != STDERR_FILENO &&
4045 i != fd)
4046 close(i);
4048 parg = args;
4049 *parg++ = (char *)setup_script;
4050 *parg++ = (char *)ifname;
4051 *parg++ = NULL;
4052 execv(setup_script, args);
4053 _exit(1);
4055 while (waitpid(pid, &status, 0) != pid);
4056 if (!WIFEXITED(status) ||
4057 WEXITSTATUS(status) != 0) {
4058 fprintf(stderr, "%s: could not launch network script\n",
4059 setup_script);
4060 return -1;
4063 return 0;
4066 static int net_tap_init(VLANState *vlan, const char *ifname1,
4067 const char *setup_script, const char *down_script)
4069 TAPState *s;
4070 int fd;
4071 char ifname[128];
4073 if (ifname1 != NULL)
4074 pstrcpy(ifname, sizeof(ifname), ifname1);
4075 else
4076 ifname[0] = '\0';
4077 TFR(fd = tap_open(ifname, sizeof(ifname)));
4078 if (fd < 0)
4079 return -1;
4081 if (!setup_script || !strcmp(setup_script, "no"))
4082 setup_script = "";
4083 if (setup_script[0] != '\0') {
4084 if (launch_script(setup_script, ifname, fd))
4085 return -1;
4087 s = net_tap_fd_init(vlan, fd);
4088 if (!s)
4089 return -1;
4090 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4091 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4092 if (down_script && strcmp(down_script, "no"))
4093 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4094 return 0;
4097 #endif /* !_WIN32 */
4099 /* network connection */
4100 typedef struct NetSocketState {
4101 VLANClientState *vc;
4102 int fd;
4103 int state; /* 0 = getting length, 1 = getting data */
4104 int index;
4105 int packet_len;
4106 uint8_t buf[4096];
4107 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4108 } NetSocketState;
4110 typedef struct NetSocketListenState {
4111 VLANState *vlan;
4112 int fd;
4113 } NetSocketListenState;
4115 /* XXX: we consider we can send the whole packet without blocking */
4116 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4118 NetSocketState *s = opaque;
4119 uint32_t len;
4120 len = htonl(size);
4122 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4123 send_all(s->fd, buf, size);
4126 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4128 NetSocketState *s = opaque;
4129 sendto(s->fd, buf, size, 0,
4130 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4133 static void net_socket_send(void *opaque)
4135 NetSocketState *s = opaque;
4136 int l, size, err;
4137 uint8_t buf1[4096];
4138 const uint8_t *buf;
4140 size = recv(s->fd, buf1, sizeof(buf1), 0);
4141 if (size < 0) {
4142 err = socket_error();
4143 if (err != EWOULDBLOCK)
4144 goto eoc;
4145 } else if (size == 0) {
4146 /* end of connection */
4147 eoc:
4148 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4149 closesocket(s->fd);
4150 return;
4152 buf = buf1;
4153 while (size > 0) {
4154 /* reassemble a packet from the network */
4155 switch(s->state) {
4156 case 0:
4157 l = 4 - s->index;
4158 if (l > size)
4159 l = size;
4160 memcpy(s->buf + s->index, buf, l);
4161 buf += l;
4162 size -= l;
4163 s->index += l;
4164 if (s->index == 4) {
4165 /* got length */
4166 s->packet_len = ntohl(*(uint32_t *)s->buf);
4167 s->index = 0;
4168 s->state = 1;
4170 break;
4171 case 1:
4172 l = s->packet_len - s->index;
4173 if (l > size)
4174 l = size;
4175 memcpy(s->buf + s->index, buf, l);
4176 s->index += l;
4177 buf += l;
4178 size -= l;
4179 if (s->index >= s->packet_len) {
4180 qemu_send_packet(s->vc, s->buf, s->packet_len);
4181 s->index = 0;
4182 s->state = 0;
4184 break;
4189 static void net_socket_send_dgram(void *opaque)
4191 NetSocketState *s = opaque;
4192 int size;
4194 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4195 if (size < 0)
4196 return;
4197 if (size == 0) {
4198 /* end of connection */
4199 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4200 return;
4202 qemu_send_packet(s->vc, s->buf, size);
4205 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4207 struct ip_mreq imr;
4208 int fd;
4209 int val, ret;
4210 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4211 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4212 inet_ntoa(mcastaddr->sin_addr),
4213 (int)ntohl(mcastaddr->sin_addr.s_addr));
4214 return -1;
4217 fd = socket(PF_INET, SOCK_DGRAM, 0);
4218 if (fd < 0) {
4219 perror("socket(PF_INET, SOCK_DGRAM)");
4220 return -1;
4223 val = 1;
4224 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4225 (const char *)&val, sizeof(val));
4226 if (ret < 0) {
4227 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4228 goto fail;
4231 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4232 if (ret < 0) {
4233 perror("bind");
4234 goto fail;
4237 /* Add host to multicast group */
4238 imr.imr_multiaddr = mcastaddr->sin_addr;
4239 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4241 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4242 (const char *)&imr, sizeof(struct ip_mreq));
4243 if (ret < 0) {
4244 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4245 goto fail;
4248 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4249 val = 1;
4250 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4251 (const char *)&val, sizeof(val));
4252 if (ret < 0) {
4253 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4254 goto fail;
4257 socket_set_nonblock(fd);
4258 return fd;
4259 fail:
4260 if (fd >= 0)
4261 closesocket(fd);
4262 return -1;
4265 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4266 int is_connected)
4268 struct sockaddr_in saddr;
4269 int newfd;
4270 socklen_t saddr_len;
4271 NetSocketState *s;
4273 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4274 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4275 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4278 if (is_connected) {
4279 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4280 /* must be bound */
4281 if (saddr.sin_addr.s_addr==0) {
4282 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4283 fd);
4284 return NULL;
4286 /* clone dgram socket */
4287 newfd = net_socket_mcast_create(&saddr);
4288 if (newfd < 0) {
4289 /* error already reported by net_socket_mcast_create() */
4290 close(fd);
4291 return NULL;
4293 /* clone newfd to fd, close newfd */
4294 dup2(newfd, fd);
4295 close(newfd);
4297 } else {
4298 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4299 fd, strerror(errno));
4300 return NULL;
4304 s = qemu_mallocz(sizeof(NetSocketState));
4305 if (!s)
4306 return NULL;
4307 s->fd = fd;
4309 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4310 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4312 /* mcast: save bound address as dst */
4313 if (is_connected) s->dgram_dst=saddr;
4315 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4316 "socket: fd=%d (%s mcast=%s:%d)",
4317 fd, is_connected? "cloned" : "",
4318 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4319 return s;
4322 static void net_socket_connect(void *opaque)
4324 NetSocketState *s = opaque;
4325 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4328 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4329 int is_connected)
4331 NetSocketState *s;
4332 s = qemu_mallocz(sizeof(NetSocketState));
4333 if (!s)
4334 return NULL;
4335 s->fd = fd;
4336 s->vc = qemu_new_vlan_client(vlan,
4337 net_socket_receive, NULL, s);
4338 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4339 "socket: fd=%d", fd);
4340 if (is_connected) {
4341 net_socket_connect(s);
4342 } else {
4343 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4345 return s;
4348 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4349 int is_connected)
4351 int so_type=-1, optlen=sizeof(so_type);
4353 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4354 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4355 return NULL;
4357 switch(so_type) {
4358 case SOCK_DGRAM:
4359 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4360 case SOCK_STREAM:
4361 return net_socket_fd_init_stream(vlan, fd, is_connected);
4362 default:
4363 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4364 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4365 return net_socket_fd_init_stream(vlan, fd, is_connected);
4367 return NULL;
4370 static void net_socket_accept(void *opaque)
4372 NetSocketListenState *s = opaque;
4373 NetSocketState *s1;
4374 struct sockaddr_in saddr;
4375 socklen_t len;
4376 int fd;
4378 for(;;) {
4379 len = sizeof(saddr);
4380 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4381 if (fd < 0 && errno != EINTR) {
4382 return;
4383 } else if (fd >= 0) {
4384 break;
4387 s1 = net_socket_fd_init(s->vlan, fd, 1);
4388 if (!s1) {
4389 closesocket(fd);
4390 } else {
4391 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4392 "socket: connection from %s:%d",
4393 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4397 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4399 NetSocketListenState *s;
4400 int fd, val, ret;
4401 struct sockaddr_in saddr;
4403 if (parse_host_port(&saddr, host_str) < 0)
4404 return -1;
4406 s = qemu_mallocz(sizeof(NetSocketListenState));
4407 if (!s)
4408 return -1;
4410 fd = socket(PF_INET, SOCK_STREAM, 0);
4411 if (fd < 0) {
4412 perror("socket");
4413 return -1;
4415 socket_set_nonblock(fd);
4417 /* allow fast reuse */
4418 val = 1;
4419 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4421 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4422 if (ret < 0) {
4423 perror("bind");
4424 return -1;
4426 ret = listen(fd, 0);
4427 if (ret < 0) {
4428 perror("listen");
4429 return -1;
4431 s->vlan = vlan;
4432 s->fd = fd;
4433 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4434 return 0;
4437 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4439 NetSocketState *s;
4440 int fd, connected, ret, err;
4441 struct sockaddr_in saddr;
4443 if (parse_host_port(&saddr, host_str) < 0)
4444 return -1;
4446 fd = socket(PF_INET, SOCK_STREAM, 0);
4447 if (fd < 0) {
4448 perror("socket");
4449 return -1;
4451 socket_set_nonblock(fd);
4453 connected = 0;
4454 for(;;) {
4455 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4456 if (ret < 0) {
4457 err = socket_error();
4458 if (err == EINTR || err == EWOULDBLOCK) {
4459 } else if (err == EINPROGRESS) {
4460 break;
4461 #ifdef _WIN32
4462 } else if (err == WSAEALREADY) {
4463 break;
4464 #endif
4465 } else {
4466 perror("connect");
4467 closesocket(fd);
4468 return -1;
4470 } else {
4471 connected = 1;
4472 break;
4475 s = net_socket_fd_init(vlan, fd, connected);
4476 if (!s)
4477 return -1;
4478 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4479 "socket: connect to %s:%d",
4480 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4481 return 0;
4484 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4486 NetSocketState *s;
4487 int fd;
4488 struct sockaddr_in saddr;
4490 if (parse_host_port(&saddr, host_str) < 0)
4491 return -1;
4494 fd = net_socket_mcast_create(&saddr);
4495 if (fd < 0)
4496 return -1;
4498 s = net_socket_fd_init(vlan, fd, 0);
4499 if (!s)
4500 return -1;
4502 s->dgram_dst = saddr;
4504 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4505 "socket: mcast=%s:%d",
4506 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4507 return 0;
4511 static int get_param_value(char *buf, int buf_size,
4512 const char *tag, const char *str)
4514 const char *p;
4515 char *q;
4516 char option[128];
4518 p = str;
4519 for(;;) {
4520 q = option;
4521 while (*p != '\0' && *p != '=') {
4522 if ((q - option) < sizeof(option) - 1)
4523 *q++ = *p;
4524 p++;
4526 *q = '\0';
4527 if (*p != '=')
4528 break;
4529 p++;
4530 if (!strcmp(tag, option)) {
4531 q = buf;
4532 while (*p != '\0' && *p != ',') {
4533 if ((q - buf) < buf_size - 1)
4534 *q++ = *p;
4535 p++;
4537 *q = '\0';
4538 return q - buf;
4539 } else {
4540 while (*p != '\0' && *p != ',') {
4541 p++;
4544 if (*p != ',')
4545 break;
4546 p++;
4548 return 0;
4551 static int net_client_init(const char *str)
4553 const char *p;
4554 char *q;
4555 char device[64];
4556 char buf[1024];
4557 int vlan_id, ret;
4558 VLANState *vlan;
4560 p = str;
4561 q = device;
4562 while (*p != '\0' && *p != ',') {
4563 if ((q - device) < sizeof(device) - 1)
4564 *q++ = *p;
4565 p++;
4567 *q = '\0';
4568 if (*p == ',')
4569 p++;
4570 vlan_id = 0;
4571 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4572 vlan_id = strtol(buf, NULL, 0);
4574 vlan = qemu_find_vlan(vlan_id);
4575 if (!vlan) {
4576 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4577 return -1;
4579 if (!strcmp(device, "nic")) {
4580 NICInfo *nd;
4581 uint8_t *macaddr;
4583 if (nb_nics >= MAX_NICS) {
4584 fprintf(stderr, "Too Many NICs\n");
4585 return -1;
4587 nd = &nd_table[nb_nics];
4588 macaddr = nd->macaddr;
4589 macaddr[0] = 0x52;
4590 macaddr[1] = 0x54;
4591 macaddr[2] = 0x00;
4592 macaddr[3] = 0x12;
4593 macaddr[4] = 0x34;
4594 macaddr[5] = 0x56 + nb_nics;
4596 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4597 if (parse_macaddr(macaddr, buf) < 0) {
4598 fprintf(stderr, "invalid syntax for ethernet address\n");
4599 return -1;
4602 if (get_param_value(buf, sizeof(buf), "model", p)) {
4603 nd->model = strdup(buf);
4605 nd->vlan = vlan;
4606 nb_nics++;
4607 vlan->nb_guest_devs++;
4608 ret = 0;
4609 } else
4610 if (!strcmp(device, "none")) {
4611 /* does nothing. It is needed to signal that no network cards
4612 are wanted */
4613 ret = 0;
4614 } else
4615 #ifdef CONFIG_SLIRP
4616 if (!strcmp(device, "user")) {
4617 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4618 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4620 vlan->nb_host_devs++;
4621 ret = net_slirp_init(vlan);
4622 } else
4623 #endif
4624 #ifdef _WIN32
4625 if (!strcmp(device, "tap")) {
4626 char ifname[64];
4627 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4628 fprintf(stderr, "tap: no interface name\n");
4629 return -1;
4631 vlan->nb_host_devs++;
4632 ret = tap_win32_init(vlan, ifname);
4633 } else
4634 #else
4635 if (!strcmp(device, "tap")) {
4636 char ifname[64];
4637 char setup_script[1024], down_script[1024];
4638 int fd;
4639 vlan->nb_host_devs++;
4640 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4641 fd = strtol(buf, NULL, 0);
4642 ret = -1;
4643 if (net_tap_fd_init(vlan, fd))
4644 ret = 0;
4645 } else {
4646 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4647 ifname[0] = '\0';
4649 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4650 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4652 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4653 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4655 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4657 } else
4658 #endif
4659 if (!strcmp(device, "socket")) {
4660 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4661 int fd;
4662 fd = strtol(buf, NULL, 0);
4663 ret = -1;
4664 if (net_socket_fd_init(vlan, fd, 1))
4665 ret = 0;
4666 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4667 ret = net_socket_listen_init(vlan, buf);
4668 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4669 ret = net_socket_connect_init(vlan, buf);
4670 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4671 ret = net_socket_mcast_init(vlan, buf);
4672 } else {
4673 fprintf(stderr, "Unknown socket options: %s\n", p);
4674 return -1;
4676 vlan->nb_host_devs++;
4677 } else
4679 fprintf(stderr, "Unknown network device: %s\n", device);
4680 return -1;
4682 if (ret < 0) {
4683 fprintf(stderr, "Could not initialize device '%s'\n", device);
4686 return ret;
4689 void do_info_network(void)
4691 VLANState *vlan;
4692 VLANClientState *vc;
4694 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4695 term_printf("VLAN %d devices:\n", vlan->id);
4696 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4697 term_printf(" %s\n", vc->info_str);
4701 /***********************************************************/
4702 /* USB devices */
4704 static USBPort *used_usb_ports;
4705 static USBPort *free_usb_ports;
4707 /* ??? Maybe change this to register a hub to keep track of the topology. */
4708 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4709 usb_attachfn attach)
4711 port->opaque = opaque;
4712 port->index = index;
4713 port->attach = attach;
4714 port->next = free_usb_ports;
4715 free_usb_ports = port;
4718 static int usb_device_add(const char *devname)
4720 const char *p;
4721 USBDevice *dev;
4722 USBPort *port;
4724 if (!free_usb_ports)
4725 return -1;
4727 if (strstart(devname, "host:", &p)) {
4728 dev = usb_host_device_open(p);
4729 } else if (!strcmp(devname, "mouse")) {
4730 dev = usb_mouse_init();
4731 } else if (!strcmp(devname, "tablet")) {
4732 dev = usb_tablet_init();
4733 } else if (!strcmp(devname, "keyboard")) {
4734 dev = usb_keyboard_init();
4735 } else if (strstart(devname, "disk:", &p)) {
4736 dev = usb_msd_init(p);
4737 } else if (!strcmp(devname, "wacom-tablet")) {
4738 dev = usb_wacom_init();
4739 } else {
4740 return -1;
4742 if (!dev)
4743 return -1;
4745 /* Find a USB port to add the device to. */
4746 port = free_usb_ports;
4747 if (!port->next) {
4748 USBDevice *hub;
4750 /* Create a new hub and chain it on. */
4751 free_usb_ports = NULL;
4752 port->next = used_usb_ports;
4753 used_usb_ports = port;
4755 hub = usb_hub_init(VM_USB_HUB_SIZE);
4756 usb_attach(port, hub);
4757 port = free_usb_ports;
4760 free_usb_ports = port->next;
4761 port->next = used_usb_ports;
4762 used_usb_ports = port;
4763 usb_attach(port, dev);
4764 return 0;
4767 static int usb_device_del(const char *devname)
4769 USBPort *port;
4770 USBPort **lastp;
4771 USBDevice *dev;
4772 int bus_num, addr;
4773 const char *p;
4775 if (!used_usb_ports)
4776 return -1;
4778 p = strchr(devname, '.');
4779 if (!p)
4780 return -1;
4781 bus_num = strtoul(devname, NULL, 0);
4782 addr = strtoul(p + 1, NULL, 0);
4783 if (bus_num != 0)
4784 return -1;
4786 lastp = &used_usb_ports;
4787 port = used_usb_ports;
4788 while (port && port->dev->addr != addr) {
4789 lastp = &port->next;
4790 port = port->next;
4793 if (!port)
4794 return -1;
4796 dev = port->dev;
4797 *lastp = port->next;
4798 usb_attach(port, NULL);
4799 dev->handle_destroy(dev);
4800 port->next = free_usb_ports;
4801 free_usb_ports = port;
4802 return 0;
4805 void do_usb_add(const char *devname)
4807 int ret;
4808 ret = usb_device_add(devname);
4809 if (ret < 0)
4810 term_printf("Could not add USB device '%s'\n", devname);
4813 void do_usb_del(const char *devname)
4815 int ret;
4816 ret = usb_device_del(devname);
4817 if (ret < 0)
4818 term_printf("Could not remove USB device '%s'\n", devname);
4821 void usb_info(void)
4823 USBDevice *dev;
4824 USBPort *port;
4825 const char *speed_str;
4827 if (!usb_enabled) {
4828 term_printf("USB support not enabled\n");
4829 return;
4832 for (port = used_usb_ports; port; port = port->next) {
4833 dev = port->dev;
4834 if (!dev)
4835 continue;
4836 switch(dev->speed) {
4837 case USB_SPEED_LOW:
4838 speed_str = "1.5";
4839 break;
4840 case USB_SPEED_FULL:
4841 speed_str = "12";
4842 break;
4843 case USB_SPEED_HIGH:
4844 speed_str = "480";
4845 break;
4846 default:
4847 speed_str = "?";
4848 break;
4850 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4851 0, dev->addr, speed_str, dev->devname);
4855 /***********************************************************/
4856 /* PCMCIA/Cardbus */
4858 static struct pcmcia_socket_entry_s {
4859 struct pcmcia_socket_s *socket;
4860 struct pcmcia_socket_entry_s *next;
4861 } *pcmcia_sockets = 0;
4863 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4865 struct pcmcia_socket_entry_s *entry;
4867 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4868 entry->socket = socket;
4869 entry->next = pcmcia_sockets;
4870 pcmcia_sockets = entry;
4873 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4875 struct pcmcia_socket_entry_s *entry, **ptr;
4877 ptr = &pcmcia_sockets;
4878 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4879 if (entry->socket == socket) {
4880 *ptr = entry->next;
4881 qemu_free(entry);
4885 void pcmcia_info(void)
4887 struct pcmcia_socket_entry_s *iter;
4888 if (!pcmcia_sockets)
4889 term_printf("No PCMCIA sockets\n");
4891 for (iter = pcmcia_sockets; iter; iter = iter->next)
4892 term_printf("%s: %s\n", iter->socket->slot_string,
4893 iter->socket->attached ? iter->socket->card_string :
4894 "Empty");
4897 /***********************************************************/
4898 /* dumb display */
4900 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4904 static void dumb_resize(DisplayState *ds, int w, int h)
4908 static void dumb_refresh(DisplayState *ds)
4910 #if defined(CONFIG_SDL)
4911 vga_hw_update();
4912 #endif
4915 static void dumb_display_init(DisplayState *ds)
4917 ds->data = NULL;
4918 ds->linesize = 0;
4919 ds->depth = 0;
4920 ds->dpy_update = dumb_update;
4921 ds->dpy_resize = dumb_resize;
4922 ds->dpy_refresh = dumb_refresh;
4925 /***********************************************************/
4926 /* I/O handling */
4928 #define MAX_IO_HANDLERS 64
4930 typedef struct IOHandlerRecord {
4931 int fd;
4932 IOCanRWHandler *fd_read_poll;
4933 IOHandler *fd_read;
4934 IOHandler *fd_write;
4935 int deleted;
4936 void *opaque;
4937 /* temporary data */
4938 struct pollfd *ufd;
4939 struct IOHandlerRecord *next;
4940 } IOHandlerRecord;
4942 static IOHandlerRecord *first_io_handler;
4944 /* XXX: fd_read_poll should be suppressed, but an API change is
4945 necessary in the character devices to suppress fd_can_read(). */
4946 int qemu_set_fd_handler2(int fd,
4947 IOCanRWHandler *fd_read_poll,
4948 IOHandler *fd_read,
4949 IOHandler *fd_write,
4950 void *opaque)
4952 IOHandlerRecord **pioh, *ioh;
4954 if (!fd_read && !fd_write) {
4955 pioh = &first_io_handler;
4956 for(;;) {
4957 ioh = *pioh;
4958 if (ioh == NULL)
4959 break;
4960 if (ioh->fd == fd) {
4961 ioh->deleted = 1;
4962 break;
4964 pioh = &ioh->next;
4966 } else {
4967 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4968 if (ioh->fd == fd)
4969 goto found;
4971 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4972 if (!ioh)
4973 return -1;
4974 ioh->next = first_io_handler;
4975 first_io_handler = ioh;
4976 found:
4977 ioh->fd = fd;
4978 ioh->fd_read_poll = fd_read_poll;
4979 ioh->fd_read = fd_read;
4980 ioh->fd_write = fd_write;
4981 ioh->opaque = opaque;
4982 ioh->deleted = 0;
4984 return 0;
4987 int qemu_set_fd_handler(int fd,
4988 IOHandler *fd_read,
4989 IOHandler *fd_write,
4990 void *opaque)
4992 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4995 /***********************************************************/
4996 /* Polling handling */
4998 typedef struct PollingEntry {
4999 PollingFunc *func;
5000 void *opaque;
5001 struct PollingEntry *next;
5002 } PollingEntry;
5004 static PollingEntry *first_polling_entry;
5006 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5008 PollingEntry **ppe, *pe;
5009 pe = qemu_mallocz(sizeof(PollingEntry));
5010 if (!pe)
5011 return -1;
5012 pe->func = func;
5013 pe->opaque = opaque;
5014 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5015 *ppe = pe;
5016 return 0;
5019 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5021 PollingEntry **ppe, *pe;
5022 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5023 pe = *ppe;
5024 if (pe->func == func && pe->opaque == opaque) {
5025 *ppe = pe->next;
5026 qemu_free(pe);
5027 break;
5032 #ifdef _WIN32
5033 /***********************************************************/
5034 /* Wait objects support */
5035 typedef struct WaitObjects {
5036 int num;
5037 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5038 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5039 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5040 } WaitObjects;
5042 static WaitObjects wait_objects = {0};
5044 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5046 WaitObjects *w = &wait_objects;
5048 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5049 return -1;
5050 w->events[w->num] = handle;
5051 w->func[w->num] = func;
5052 w->opaque[w->num] = opaque;
5053 w->num++;
5054 return 0;
5057 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5059 int i, found;
5060 WaitObjects *w = &wait_objects;
5062 found = 0;
5063 for (i = 0; i < w->num; i++) {
5064 if (w->events[i] == handle)
5065 found = 1;
5066 if (found) {
5067 w->events[i] = w->events[i + 1];
5068 w->func[i] = w->func[i + 1];
5069 w->opaque[i] = w->opaque[i + 1];
5072 if (found)
5073 w->num--;
5075 #endif
5077 /***********************************************************/
5078 /* savevm/loadvm support */
5080 #define IO_BUF_SIZE 32768
5082 struct QEMUFile {
5083 FILE *outfile;
5084 BlockDriverState *bs;
5085 int is_file;
5086 int is_writable;
5087 int64_t base_offset;
5088 int64_t buf_offset; /* start of buffer when writing, end of buffer
5089 when reading */
5090 int buf_index;
5091 int buf_size; /* 0 when writing */
5092 uint8_t buf[IO_BUF_SIZE];
5095 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5097 QEMUFile *f;
5099 f = qemu_mallocz(sizeof(QEMUFile));
5100 if (!f)
5101 return NULL;
5102 if (!strcmp(mode, "wb")) {
5103 f->is_writable = 1;
5104 } else if (!strcmp(mode, "rb")) {
5105 f->is_writable = 0;
5106 } else {
5107 goto fail;
5109 f->outfile = fopen(filename, mode);
5110 if (!f->outfile)
5111 goto fail;
5112 f->is_file = 1;
5113 return f;
5114 fail:
5115 if (f->outfile)
5116 fclose(f->outfile);
5117 qemu_free(f);
5118 return NULL;
5121 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5123 QEMUFile *f;
5125 f = qemu_mallocz(sizeof(QEMUFile));
5126 if (!f)
5127 return NULL;
5128 f->is_file = 0;
5129 f->bs = bs;
5130 f->is_writable = is_writable;
5131 f->base_offset = offset;
5132 return f;
5135 void qemu_fflush(QEMUFile *f)
5137 if (!f->is_writable)
5138 return;
5139 if (f->buf_index > 0) {
5140 if (f->is_file) {
5141 fseek(f->outfile, f->buf_offset, SEEK_SET);
5142 fwrite(f->buf, 1, f->buf_index, f->outfile);
5143 } else {
5144 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5145 f->buf, f->buf_index);
5147 f->buf_offset += f->buf_index;
5148 f->buf_index = 0;
5152 static void qemu_fill_buffer(QEMUFile *f)
5154 int len;
5156 if (f->is_writable)
5157 return;
5158 if (f->is_file) {
5159 fseek(f->outfile, f->buf_offset, SEEK_SET);
5160 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5161 if (len < 0)
5162 len = 0;
5163 } else {
5164 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5165 f->buf, IO_BUF_SIZE);
5166 if (len < 0)
5167 len = 0;
5169 f->buf_index = 0;
5170 f->buf_size = len;
5171 f->buf_offset += len;
5174 void qemu_fclose(QEMUFile *f)
5176 if (f->is_writable)
5177 qemu_fflush(f);
5178 if (f->is_file) {
5179 fclose(f->outfile);
5181 qemu_free(f);
5184 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5186 int l;
5187 while (size > 0) {
5188 l = IO_BUF_SIZE - f->buf_index;
5189 if (l > size)
5190 l = size;
5191 memcpy(f->buf + f->buf_index, buf, l);
5192 f->buf_index += l;
5193 buf += l;
5194 size -= l;
5195 if (f->buf_index >= IO_BUF_SIZE)
5196 qemu_fflush(f);
5200 void qemu_put_byte(QEMUFile *f, int v)
5202 f->buf[f->buf_index++] = v;
5203 if (f->buf_index >= IO_BUF_SIZE)
5204 qemu_fflush(f);
5207 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5209 int size, l;
5211 size = size1;
5212 while (size > 0) {
5213 l = f->buf_size - f->buf_index;
5214 if (l == 0) {
5215 qemu_fill_buffer(f);
5216 l = f->buf_size - f->buf_index;
5217 if (l == 0)
5218 break;
5220 if (l > size)
5221 l = size;
5222 memcpy(buf, f->buf + f->buf_index, l);
5223 f->buf_index += l;
5224 buf += l;
5225 size -= l;
5227 return size1 - size;
5230 int qemu_get_byte(QEMUFile *f)
5232 if (f->buf_index >= f->buf_size) {
5233 qemu_fill_buffer(f);
5234 if (f->buf_index >= f->buf_size)
5235 return 0;
5237 return f->buf[f->buf_index++];
5240 int64_t qemu_ftell(QEMUFile *f)
5242 return f->buf_offset - f->buf_size + f->buf_index;
5245 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5247 if (whence == SEEK_SET) {
5248 /* nothing to do */
5249 } else if (whence == SEEK_CUR) {
5250 pos += qemu_ftell(f);
5251 } else {
5252 /* SEEK_END not supported */
5253 return -1;
5255 if (f->is_writable) {
5256 qemu_fflush(f);
5257 f->buf_offset = pos;
5258 } else {
5259 f->buf_offset = pos;
5260 f->buf_index = 0;
5261 f->buf_size = 0;
5263 return pos;
5266 void qemu_put_be16(QEMUFile *f, unsigned int v)
5268 qemu_put_byte(f, v >> 8);
5269 qemu_put_byte(f, v);
5272 void qemu_put_be32(QEMUFile *f, unsigned int v)
5274 qemu_put_byte(f, v >> 24);
5275 qemu_put_byte(f, v >> 16);
5276 qemu_put_byte(f, v >> 8);
5277 qemu_put_byte(f, v);
5280 void qemu_put_be64(QEMUFile *f, uint64_t v)
5282 qemu_put_be32(f, v >> 32);
5283 qemu_put_be32(f, v);
5286 unsigned int qemu_get_be16(QEMUFile *f)
5288 unsigned int v;
5289 v = qemu_get_byte(f) << 8;
5290 v |= qemu_get_byte(f);
5291 return v;
5294 unsigned int qemu_get_be32(QEMUFile *f)
5296 unsigned int v;
5297 v = qemu_get_byte(f) << 24;
5298 v |= qemu_get_byte(f) << 16;
5299 v |= qemu_get_byte(f) << 8;
5300 v |= qemu_get_byte(f);
5301 return v;
5304 uint64_t qemu_get_be64(QEMUFile *f)
5306 uint64_t v;
5307 v = (uint64_t)qemu_get_be32(f) << 32;
5308 v |= qemu_get_be32(f);
5309 return v;
5312 typedef struct SaveStateEntry {
5313 char idstr[256];
5314 int instance_id;
5315 int version_id;
5316 SaveStateHandler *save_state;
5317 LoadStateHandler *load_state;
5318 void *opaque;
5319 struct SaveStateEntry *next;
5320 } SaveStateEntry;
5322 static SaveStateEntry *first_se;
5324 int register_savevm(const char *idstr,
5325 int instance_id,
5326 int version_id,
5327 SaveStateHandler *save_state,
5328 LoadStateHandler *load_state,
5329 void *opaque)
5331 SaveStateEntry *se, **pse;
5333 se = qemu_malloc(sizeof(SaveStateEntry));
5334 if (!se)
5335 return -1;
5336 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5337 se->instance_id = instance_id;
5338 se->version_id = version_id;
5339 se->save_state = save_state;
5340 se->load_state = load_state;
5341 se->opaque = opaque;
5342 se->next = NULL;
5344 /* add at the end of list */
5345 pse = &first_se;
5346 while (*pse != NULL)
5347 pse = &(*pse)->next;
5348 *pse = se;
5349 return 0;
5352 #define QEMU_VM_FILE_MAGIC 0x5145564d
5353 #define QEMU_VM_FILE_VERSION 0x00000002
5355 int qemu_savevm_state(QEMUFile *f)
5357 SaveStateEntry *se;
5358 int len, ret;
5359 int64_t cur_pos, len_pos, total_len_pos;
5361 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5362 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5363 total_len_pos = qemu_ftell(f);
5364 qemu_put_be64(f, 0); /* total size */
5366 for(se = first_se; se != NULL; se = se->next) {
5367 /* ID string */
5368 len = strlen(se->idstr);
5369 qemu_put_byte(f, len);
5370 qemu_put_buffer(f, se->idstr, len);
5372 qemu_put_be32(f, se->instance_id);
5373 qemu_put_be32(f, se->version_id);
5375 /* record size: filled later */
5376 len_pos = qemu_ftell(f);
5377 qemu_put_be32(f, 0);
5379 se->save_state(f, se->opaque);
5381 /* fill record size */
5382 cur_pos = qemu_ftell(f);
5383 len = cur_pos - len_pos - 4;
5384 qemu_fseek(f, len_pos, SEEK_SET);
5385 qemu_put_be32(f, len);
5386 qemu_fseek(f, cur_pos, SEEK_SET);
5388 cur_pos = qemu_ftell(f);
5389 qemu_fseek(f, total_len_pos, SEEK_SET);
5390 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5391 qemu_fseek(f, cur_pos, SEEK_SET);
5393 ret = 0;
5394 return ret;
5397 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5399 SaveStateEntry *se;
5401 for(se = first_se; se != NULL; se = se->next) {
5402 if (!strcmp(se->idstr, idstr) &&
5403 instance_id == se->instance_id)
5404 return se;
5406 return NULL;
5409 int qemu_loadvm_state(QEMUFile *f)
5411 SaveStateEntry *se;
5412 int len, ret, instance_id, record_len, version_id;
5413 int64_t total_len, end_pos, cur_pos;
5414 unsigned int v;
5415 char idstr[256];
5417 v = qemu_get_be32(f);
5418 if (v != QEMU_VM_FILE_MAGIC)
5419 goto fail;
5420 v = qemu_get_be32(f);
5421 if (v != QEMU_VM_FILE_VERSION) {
5422 fail:
5423 ret = -1;
5424 goto the_end;
5426 total_len = qemu_get_be64(f);
5427 end_pos = total_len + qemu_ftell(f);
5428 for(;;) {
5429 if (qemu_ftell(f) >= end_pos)
5430 break;
5431 len = qemu_get_byte(f);
5432 qemu_get_buffer(f, idstr, len);
5433 idstr[len] = '\0';
5434 instance_id = qemu_get_be32(f);
5435 version_id = qemu_get_be32(f);
5436 record_len = qemu_get_be32(f);
5437 #if 0
5438 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5439 idstr, instance_id, version_id, record_len);
5440 #endif
5441 cur_pos = qemu_ftell(f);
5442 se = find_se(idstr, instance_id);
5443 if (!se) {
5444 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5445 instance_id, idstr);
5446 } else {
5447 ret = se->load_state(f, se->opaque, version_id);
5448 if (ret < 0) {
5449 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5450 instance_id, idstr);
5453 /* always seek to exact end of record */
5454 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5456 ret = 0;
5457 the_end:
5458 return ret;
5461 /* device can contain snapshots */
5462 static int bdrv_can_snapshot(BlockDriverState *bs)
5464 return (bs &&
5465 !bdrv_is_removable(bs) &&
5466 !bdrv_is_read_only(bs));
5469 /* device must be snapshots in order to have a reliable snapshot */
5470 static int bdrv_has_snapshot(BlockDriverState *bs)
5472 return (bs &&
5473 !bdrv_is_removable(bs) &&
5474 !bdrv_is_read_only(bs));
5477 static BlockDriverState *get_bs_snapshots(void)
5479 BlockDriverState *bs;
5480 int i;
5482 if (bs_snapshots)
5483 return bs_snapshots;
5484 for(i = 0; i <= MAX_DISKS; i++) {
5485 bs = bs_table[i];
5486 if (bdrv_can_snapshot(bs))
5487 goto ok;
5489 return NULL;
5491 bs_snapshots = bs;
5492 return bs;
5495 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5496 const char *name)
5498 QEMUSnapshotInfo *sn_tab, *sn;
5499 int nb_sns, i, ret;
5501 ret = -ENOENT;
5502 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5503 if (nb_sns < 0)
5504 return ret;
5505 for(i = 0; i < nb_sns; i++) {
5506 sn = &sn_tab[i];
5507 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5508 *sn_info = *sn;
5509 ret = 0;
5510 break;
5513 qemu_free(sn_tab);
5514 return ret;
5517 void do_savevm(const char *name)
5519 BlockDriverState *bs, *bs1;
5520 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5521 int must_delete, ret, i;
5522 BlockDriverInfo bdi1, *bdi = &bdi1;
5523 QEMUFile *f;
5524 int saved_vm_running;
5525 #ifdef _WIN32
5526 struct _timeb tb;
5527 #else
5528 struct timeval tv;
5529 #endif
5531 bs = get_bs_snapshots();
5532 if (!bs) {
5533 term_printf("No block device can accept snapshots\n");
5534 return;
5537 /* ??? Should this occur after vm_stop? */
5538 qemu_aio_flush();
5540 saved_vm_running = vm_running;
5541 vm_stop(0);
5543 must_delete = 0;
5544 if (name) {
5545 ret = bdrv_snapshot_find(bs, old_sn, name);
5546 if (ret >= 0) {
5547 must_delete = 1;
5550 memset(sn, 0, sizeof(*sn));
5551 if (must_delete) {
5552 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5553 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5554 } else {
5555 if (name)
5556 pstrcpy(sn->name, sizeof(sn->name), name);
5559 /* fill auxiliary fields */
5560 #ifdef _WIN32
5561 _ftime(&tb);
5562 sn->date_sec = tb.time;
5563 sn->date_nsec = tb.millitm * 1000000;
5564 #else
5565 gettimeofday(&tv, NULL);
5566 sn->date_sec = tv.tv_sec;
5567 sn->date_nsec = tv.tv_usec * 1000;
5568 #endif
5569 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5571 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5572 term_printf("Device %s does not support VM state snapshots\n",
5573 bdrv_get_device_name(bs));
5574 goto the_end;
5577 /* save the VM state */
5578 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5579 if (!f) {
5580 term_printf("Could not open VM state file\n");
5581 goto the_end;
5583 ret = qemu_savevm_state(f);
5584 sn->vm_state_size = qemu_ftell(f);
5585 qemu_fclose(f);
5586 if (ret < 0) {
5587 term_printf("Error %d while writing VM\n", ret);
5588 goto the_end;
5591 /* create the snapshots */
5593 for(i = 0; i < MAX_DISKS; i++) {
5594 bs1 = bs_table[i];
5595 if (bdrv_has_snapshot(bs1)) {
5596 if (must_delete) {
5597 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5598 if (ret < 0) {
5599 term_printf("Error while deleting snapshot on '%s'\n",
5600 bdrv_get_device_name(bs1));
5603 ret = bdrv_snapshot_create(bs1, sn);
5604 if (ret < 0) {
5605 term_printf("Error while creating snapshot on '%s'\n",
5606 bdrv_get_device_name(bs1));
5611 the_end:
5612 if (saved_vm_running)
5613 vm_start();
5616 void do_loadvm(const char *name)
5618 BlockDriverState *bs, *bs1;
5619 BlockDriverInfo bdi1, *bdi = &bdi1;
5620 QEMUFile *f;
5621 int i, ret;
5622 int saved_vm_running;
5624 bs = get_bs_snapshots();
5625 if (!bs) {
5626 term_printf("No block device supports snapshots\n");
5627 return;
5630 /* Flush all IO requests so they don't interfere with the new state. */
5631 qemu_aio_flush();
5633 saved_vm_running = vm_running;
5634 vm_stop(0);
5636 for(i = 0; i <= MAX_DISKS; i++) {
5637 bs1 = bs_table[i];
5638 if (bdrv_has_snapshot(bs1)) {
5639 ret = bdrv_snapshot_goto(bs1, name);
5640 if (ret < 0) {
5641 if (bs != bs1)
5642 term_printf("Warning: ");
5643 switch(ret) {
5644 case -ENOTSUP:
5645 term_printf("Snapshots not supported on device '%s'\n",
5646 bdrv_get_device_name(bs1));
5647 break;
5648 case -ENOENT:
5649 term_printf("Could not find snapshot '%s' on device '%s'\n",
5650 name, bdrv_get_device_name(bs1));
5651 break;
5652 default:
5653 term_printf("Error %d while activating snapshot on '%s'\n",
5654 ret, bdrv_get_device_name(bs1));
5655 break;
5657 /* fatal on snapshot block device */
5658 if (bs == bs1)
5659 goto the_end;
5664 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5665 term_printf("Device %s does not support VM state snapshots\n",
5666 bdrv_get_device_name(bs));
5667 return;
5670 /* restore the VM state */
5671 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5672 if (!f) {
5673 term_printf("Could not open VM state file\n");
5674 goto the_end;
5676 ret = qemu_loadvm_state(f);
5677 qemu_fclose(f);
5678 if (ret < 0) {
5679 term_printf("Error %d while loading VM state\n", ret);
5681 the_end:
5682 if (saved_vm_running)
5683 vm_start();
5686 void do_delvm(const char *name)
5688 BlockDriverState *bs, *bs1;
5689 int i, ret;
5691 bs = get_bs_snapshots();
5692 if (!bs) {
5693 term_printf("No block device supports snapshots\n");
5694 return;
5697 for(i = 0; i <= MAX_DISKS; i++) {
5698 bs1 = bs_table[i];
5699 if (bdrv_has_snapshot(bs1)) {
5700 ret = bdrv_snapshot_delete(bs1, name);
5701 if (ret < 0) {
5702 if (ret == -ENOTSUP)
5703 term_printf("Snapshots not supported on device '%s'\n",
5704 bdrv_get_device_name(bs1));
5705 else
5706 term_printf("Error %d while deleting snapshot on '%s'\n",
5707 ret, bdrv_get_device_name(bs1));
5713 void do_info_snapshots(void)
5715 BlockDriverState *bs, *bs1;
5716 QEMUSnapshotInfo *sn_tab, *sn;
5717 int nb_sns, i;
5718 char buf[256];
5720 bs = get_bs_snapshots();
5721 if (!bs) {
5722 term_printf("No available block device supports snapshots\n");
5723 return;
5725 term_printf("Snapshot devices:");
5726 for(i = 0; i <= MAX_DISKS; i++) {
5727 bs1 = bs_table[i];
5728 if (bdrv_has_snapshot(bs1)) {
5729 if (bs == bs1)
5730 term_printf(" %s", bdrv_get_device_name(bs1));
5733 term_printf("\n");
5735 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5736 if (nb_sns < 0) {
5737 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5738 return;
5740 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5741 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5742 for(i = 0; i < nb_sns; i++) {
5743 sn = &sn_tab[i];
5744 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5746 qemu_free(sn_tab);
5749 /***********************************************************/
5750 /* cpu save/restore */
5752 #if defined(TARGET_I386)
5754 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5756 qemu_put_be32(f, dt->selector);
5757 qemu_put_betl(f, dt->base);
5758 qemu_put_be32(f, dt->limit);
5759 qemu_put_be32(f, dt->flags);
5762 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5764 dt->selector = qemu_get_be32(f);
5765 dt->base = qemu_get_betl(f);
5766 dt->limit = qemu_get_be32(f);
5767 dt->flags = qemu_get_be32(f);
5770 void cpu_save(QEMUFile *f, void *opaque)
5772 CPUState *env = opaque;
5773 uint16_t fptag, fpus, fpuc, fpregs_format;
5774 uint32_t hflags;
5775 int i;
5777 for(i = 0; i < CPU_NB_REGS; i++)
5778 qemu_put_betls(f, &env->regs[i]);
5779 qemu_put_betls(f, &env->eip);
5780 qemu_put_betls(f, &env->eflags);
5781 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5782 qemu_put_be32s(f, &hflags);
5784 /* FPU */
5785 fpuc = env->fpuc;
5786 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5787 fptag = 0;
5788 for(i = 0; i < 8; i++) {
5789 fptag |= ((!env->fptags[i]) << i);
5792 qemu_put_be16s(f, &fpuc);
5793 qemu_put_be16s(f, &fpus);
5794 qemu_put_be16s(f, &fptag);
5796 #ifdef USE_X86LDOUBLE
5797 fpregs_format = 0;
5798 #else
5799 fpregs_format = 1;
5800 #endif
5801 qemu_put_be16s(f, &fpregs_format);
5803 for(i = 0; i < 8; i++) {
5804 #ifdef USE_X86LDOUBLE
5806 uint64_t mant;
5807 uint16_t exp;
5808 /* we save the real CPU data (in case of MMX usage only 'mant'
5809 contains the MMX register */
5810 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5811 qemu_put_be64(f, mant);
5812 qemu_put_be16(f, exp);
5814 #else
5815 /* if we use doubles for float emulation, we save the doubles to
5816 avoid losing information in case of MMX usage. It can give
5817 problems if the image is restored on a CPU where long
5818 doubles are used instead. */
5819 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5820 #endif
5823 for(i = 0; i < 6; i++)
5824 cpu_put_seg(f, &env->segs[i]);
5825 cpu_put_seg(f, &env->ldt);
5826 cpu_put_seg(f, &env->tr);
5827 cpu_put_seg(f, &env->gdt);
5828 cpu_put_seg(f, &env->idt);
5830 qemu_put_be32s(f, &env->sysenter_cs);
5831 qemu_put_be32s(f, &env->sysenter_esp);
5832 qemu_put_be32s(f, &env->sysenter_eip);
5834 qemu_put_betls(f, &env->cr[0]);
5835 qemu_put_betls(f, &env->cr[2]);
5836 qemu_put_betls(f, &env->cr[3]);
5837 qemu_put_betls(f, &env->cr[4]);
5839 for(i = 0; i < 8; i++)
5840 qemu_put_betls(f, &env->dr[i]);
5842 /* MMU */
5843 qemu_put_be32s(f, &env->a20_mask);
5845 /* XMM */
5846 qemu_put_be32s(f, &env->mxcsr);
5847 for(i = 0; i < CPU_NB_REGS; i++) {
5848 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5849 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5852 #ifdef TARGET_X86_64
5853 qemu_put_be64s(f, &env->efer);
5854 qemu_put_be64s(f, &env->star);
5855 qemu_put_be64s(f, &env->lstar);
5856 qemu_put_be64s(f, &env->cstar);
5857 qemu_put_be64s(f, &env->fmask);
5858 qemu_put_be64s(f, &env->kernelgsbase);
5859 #endif
5860 qemu_put_be32s(f, &env->smbase);
5863 #ifdef USE_X86LDOUBLE
5864 /* XXX: add that in a FPU generic layer */
5865 union x86_longdouble {
5866 uint64_t mant;
5867 uint16_t exp;
5870 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5871 #define EXPBIAS1 1023
5872 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5873 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5875 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5877 int e;
5878 /* mantissa */
5879 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5880 /* exponent + sign */
5881 e = EXPD1(temp) - EXPBIAS1 + 16383;
5882 e |= SIGND1(temp) >> 16;
5883 p->exp = e;
5885 #endif
5887 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5889 CPUState *env = opaque;
5890 int i, guess_mmx;
5891 uint32_t hflags;
5892 uint16_t fpus, fpuc, fptag, fpregs_format;
5894 if (version_id != 3 && version_id != 4)
5895 return -EINVAL;
5896 for(i = 0; i < CPU_NB_REGS; i++)
5897 qemu_get_betls(f, &env->regs[i]);
5898 qemu_get_betls(f, &env->eip);
5899 qemu_get_betls(f, &env->eflags);
5900 qemu_get_be32s(f, &hflags);
5902 qemu_get_be16s(f, &fpuc);
5903 qemu_get_be16s(f, &fpus);
5904 qemu_get_be16s(f, &fptag);
5905 qemu_get_be16s(f, &fpregs_format);
5907 /* NOTE: we cannot always restore the FPU state if the image come
5908 from a host with a different 'USE_X86LDOUBLE' define. We guess
5909 if we are in an MMX state to restore correctly in that case. */
5910 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5911 for(i = 0; i < 8; i++) {
5912 uint64_t mant;
5913 uint16_t exp;
5915 switch(fpregs_format) {
5916 case 0:
5917 mant = qemu_get_be64(f);
5918 exp = qemu_get_be16(f);
5919 #ifdef USE_X86LDOUBLE
5920 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5921 #else
5922 /* difficult case */
5923 if (guess_mmx)
5924 env->fpregs[i].mmx.MMX_Q(0) = mant;
5925 else
5926 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5927 #endif
5928 break;
5929 case 1:
5930 mant = qemu_get_be64(f);
5931 #ifdef USE_X86LDOUBLE
5933 union x86_longdouble *p;
5934 /* difficult case */
5935 p = (void *)&env->fpregs[i];
5936 if (guess_mmx) {
5937 p->mant = mant;
5938 p->exp = 0xffff;
5939 } else {
5940 fp64_to_fp80(p, mant);
5943 #else
5944 env->fpregs[i].mmx.MMX_Q(0) = mant;
5945 #endif
5946 break;
5947 default:
5948 return -EINVAL;
5952 env->fpuc = fpuc;
5953 /* XXX: restore FPU round state */
5954 env->fpstt = (fpus >> 11) & 7;
5955 env->fpus = fpus & ~0x3800;
5956 fptag ^= 0xff;
5957 for(i = 0; i < 8; i++) {
5958 env->fptags[i] = (fptag >> i) & 1;
5961 for(i = 0; i < 6; i++)
5962 cpu_get_seg(f, &env->segs[i]);
5963 cpu_get_seg(f, &env->ldt);
5964 cpu_get_seg(f, &env->tr);
5965 cpu_get_seg(f, &env->gdt);
5966 cpu_get_seg(f, &env->idt);
5968 qemu_get_be32s(f, &env->sysenter_cs);
5969 qemu_get_be32s(f, &env->sysenter_esp);
5970 qemu_get_be32s(f, &env->sysenter_eip);
5972 qemu_get_betls(f, &env->cr[0]);
5973 qemu_get_betls(f, &env->cr[2]);
5974 qemu_get_betls(f, &env->cr[3]);
5975 qemu_get_betls(f, &env->cr[4]);
5977 for(i = 0; i < 8; i++)
5978 qemu_get_betls(f, &env->dr[i]);
5980 /* MMU */
5981 qemu_get_be32s(f, &env->a20_mask);
5983 qemu_get_be32s(f, &env->mxcsr);
5984 for(i = 0; i < CPU_NB_REGS; i++) {
5985 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5986 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5989 #ifdef TARGET_X86_64
5990 qemu_get_be64s(f, &env->efer);
5991 qemu_get_be64s(f, &env->star);
5992 qemu_get_be64s(f, &env->lstar);
5993 qemu_get_be64s(f, &env->cstar);
5994 qemu_get_be64s(f, &env->fmask);
5995 qemu_get_be64s(f, &env->kernelgsbase);
5996 #endif
5997 if (version_id >= 4)
5998 qemu_get_be32s(f, &env->smbase);
6000 /* XXX: compute hflags from scratch, except for CPL and IIF */
6001 env->hflags = hflags;
6002 tlb_flush(env, 1);
6003 return 0;
6006 #elif defined(TARGET_PPC)
6007 void cpu_save(QEMUFile *f, void *opaque)
6011 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6013 return 0;
6016 #elif defined(TARGET_MIPS)
6017 void cpu_save(QEMUFile *f, void *opaque)
6021 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6023 return 0;
6026 #elif defined(TARGET_SPARC)
6027 void cpu_save(QEMUFile *f, void *opaque)
6029 CPUState *env = opaque;
6030 int i;
6031 uint32_t tmp;
6033 for(i = 0; i < 8; i++)
6034 qemu_put_betls(f, &env->gregs[i]);
6035 for(i = 0; i < NWINDOWS * 16; i++)
6036 qemu_put_betls(f, &env->regbase[i]);
6038 /* FPU */
6039 for(i = 0; i < TARGET_FPREGS; i++) {
6040 union {
6041 float32 f;
6042 uint32_t i;
6043 } u;
6044 u.f = env->fpr[i];
6045 qemu_put_be32(f, u.i);
6048 qemu_put_betls(f, &env->pc);
6049 qemu_put_betls(f, &env->npc);
6050 qemu_put_betls(f, &env->y);
6051 tmp = GET_PSR(env);
6052 qemu_put_be32(f, tmp);
6053 qemu_put_betls(f, &env->fsr);
6054 qemu_put_betls(f, &env->tbr);
6055 #ifndef TARGET_SPARC64
6056 qemu_put_be32s(f, &env->wim);
6057 /* MMU */
6058 for(i = 0; i < 16; i++)
6059 qemu_put_be32s(f, &env->mmuregs[i]);
6060 #endif
6063 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6065 CPUState *env = opaque;
6066 int i;
6067 uint32_t tmp;
6069 for(i = 0; i < 8; i++)
6070 qemu_get_betls(f, &env->gregs[i]);
6071 for(i = 0; i < NWINDOWS * 16; i++)
6072 qemu_get_betls(f, &env->regbase[i]);
6074 /* FPU */
6075 for(i = 0; i < TARGET_FPREGS; i++) {
6076 union {
6077 float32 f;
6078 uint32_t i;
6079 } u;
6080 u.i = qemu_get_be32(f);
6081 env->fpr[i] = u.f;
6084 qemu_get_betls(f, &env->pc);
6085 qemu_get_betls(f, &env->npc);
6086 qemu_get_betls(f, &env->y);
6087 tmp = qemu_get_be32(f);
6088 env->cwp = 0; /* needed to ensure that the wrapping registers are
6089 correctly updated */
6090 PUT_PSR(env, tmp);
6091 qemu_get_betls(f, &env->fsr);
6092 qemu_get_betls(f, &env->tbr);
6093 #ifndef TARGET_SPARC64
6094 qemu_get_be32s(f, &env->wim);
6095 /* MMU */
6096 for(i = 0; i < 16; i++)
6097 qemu_get_be32s(f, &env->mmuregs[i]);
6098 #endif
6099 tlb_flush(env, 1);
6100 return 0;
6103 #elif defined(TARGET_ARM)
6105 void cpu_save(QEMUFile *f, void *opaque)
6107 int i;
6108 CPUARMState *env = (CPUARMState *)opaque;
6110 for (i = 0; i < 16; i++) {
6111 qemu_put_be32(f, env->regs[i]);
6113 qemu_put_be32(f, cpsr_read(env));
6114 qemu_put_be32(f, env->spsr);
6115 for (i = 0; i < 6; i++) {
6116 qemu_put_be32(f, env->banked_spsr[i]);
6117 qemu_put_be32(f, env->banked_r13[i]);
6118 qemu_put_be32(f, env->banked_r14[i]);
6120 for (i = 0; i < 5; i++) {
6121 qemu_put_be32(f, env->usr_regs[i]);
6122 qemu_put_be32(f, env->fiq_regs[i]);
6124 qemu_put_be32(f, env->cp15.c0_cpuid);
6125 qemu_put_be32(f, env->cp15.c0_cachetype);
6126 qemu_put_be32(f, env->cp15.c1_sys);
6127 qemu_put_be32(f, env->cp15.c1_coproc);
6128 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6129 qemu_put_be32(f, env->cp15.c2_base);
6130 qemu_put_be32(f, env->cp15.c2_data);
6131 qemu_put_be32(f, env->cp15.c2_insn);
6132 qemu_put_be32(f, env->cp15.c3);
6133 qemu_put_be32(f, env->cp15.c5_insn);
6134 qemu_put_be32(f, env->cp15.c5_data);
6135 for (i = 0; i < 8; i++) {
6136 qemu_put_be32(f, env->cp15.c6_region[i]);
6138 qemu_put_be32(f, env->cp15.c6_insn);
6139 qemu_put_be32(f, env->cp15.c6_data);
6140 qemu_put_be32(f, env->cp15.c9_insn);
6141 qemu_put_be32(f, env->cp15.c9_data);
6142 qemu_put_be32(f, env->cp15.c13_fcse);
6143 qemu_put_be32(f, env->cp15.c13_context);
6144 qemu_put_be32(f, env->cp15.c15_cpar);
6146 qemu_put_be32(f, env->features);
6148 if (arm_feature(env, ARM_FEATURE_VFP)) {
6149 for (i = 0; i < 16; i++) {
6150 CPU_DoubleU u;
6151 u.d = env->vfp.regs[i];
6152 qemu_put_be32(f, u.l.upper);
6153 qemu_put_be32(f, u.l.lower);
6155 for (i = 0; i < 16; i++) {
6156 qemu_put_be32(f, env->vfp.xregs[i]);
6159 /* TODO: Should use proper FPSCR access functions. */
6160 qemu_put_be32(f, env->vfp.vec_len);
6161 qemu_put_be32(f, env->vfp.vec_stride);
6164 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6165 for (i = 0; i < 16; i++) {
6166 qemu_put_be64(f, env->iwmmxt.regs[i]);
6168 for (i = 0; i < 16; i++) {
6169 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6174 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6176 CPUARMState *env = (CPUARMState *)opaque;
6177 int i;
6179 if (version_id != 0)
6180 return -EINVAL;
6182 for (i = 0; i < 16; i++) {
6183 env->regs[i] = qemu_get_be32(f);
6185 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6186 env->spsr = qemu_get_be32(f);
6187 for (i = 0; i < 6; i++) {
6188 env->banked_spsr[i] = qemu_get_be32(f);
6189 env->banked_r13[i] = qemu_get_be32(f);
6190 env->banked_r14[i] = qemu_get_be32(f);
6192 for (i = 0; i < 5; i++) {
6193 env->usr_regs[i] = qemu_get_be32(f);
6194 env->fiq_regs[i] = qemu_get_be32(f);
6196 env->cp15.c0_cpuid = qemu_get_be32(f);
6197 env->cp15.c0_cachetype = qemu_get_be32(f);
6198 env->cp15.c1_sys = qemu_get_be32(f);
6199 env->cp15.c1_coproc = qemu_get_be32(f);
6200 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6201 env->cp15.c2_base = qemu_get_be32(f);
6202 env->cp15.c2_data = qemu_get_be32(f);
6203 env->cp15.c2_insn = qemu_get_be32(f);
6204 env->cp15.c3 = qemu_get_be32(f);
6205 env->cp15.c5_insn = qemu_get_be32(f);
6206 env->cp15.c5_data = qemu_get_be32(f);
6207 for (i = 0; i < 8; i++) {
6208 env->cp15.c6_region[i] = qemu_get_be32(f);
6210 env->cp15.c6_insn = qemu_get_be32(f);
6211 env->cp15.c6_data = qemu_get_be32(f);
6212 env->cp15.c9_insn = qemu_get_be32(f);
6213 env->cp15.c9_data = qemu_get_be32(f);
6214 env->cp15.c13_fcse = qemu_get_be32(f);
6215 env->cp15.c13_context = qemu_get_be32(f);
6216 env->cp15.c15_cpar = qemu_get_be32(f);
6218 env->features = qemu_get_be32(f);
6220 if (arm_feature(env, ARM_FEATURE_VFP)) {
6221 for (i = 0; i < 16; i++) {
6222 CPU_DoubleU u;
6223 u.l.upper = qemu_get_be32(f);
6224 u.l.lower = qemu_get_be32(f);
6225 env->vfp.regs[i] = u.d;
6227 for (i = 0; i < 16; i++) {
6228 env->vfp.xregs[i] = qemu_get_be32(f);
6231 /* TODO: Should use proper FPSCR access functions. */
6232 env->vfp.vec_len = qemu_get_be32(f);
6233 env->vfp.vec_stride = qemu_get_be32(f);
6236 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6237 for (i = 0; i < 16; i++) {
6238 env->iwmmxt.regs[i] = qemu_get_be64(f);
6240 for (i = 0; i < 16; i++) {
6241 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6245 return 0;
6248 #else
6250 #warning No CPU save/restore functions
6252 #endif
6254 /***********************************************************/
6255 /* ram save/restore */
6257 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6259 int v;
6261 v = qemu_get_byte(f);
6262 switch(v) {
6263 case 0:
6264 if (qemu_get_buffer(f, buf, len) != len)
6265 return -EIO;
6266 break;
6267 case 1:
6268 v = qemu_get_byte(f);
6269 memset(buf, v, len);
6270 break;
6271 default:
6272 return -EINVAL;
6274 return 0;
6277 static int ram_load_v1(QEMUFile *f, void *opaque)
6279 int i, ret;
6281 if (qemu_get_be32(f) != phys_ram_size)
6282 return -EINVAL;
6283 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6284 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6285 if (ret)
6286 return ret;
6288 return 0;
6291 #define BDRV_HASH_BLOCK_SIZE 1024
6292 #define IOBUF_SIZE 4096
6293 #define RAM_CBLOCK_MAGIC 0xfabe
6295 typedef struct RamCompressState {
6296 z_stream zstream;
6297 QEMUFile *f;
6298 uint8_t buf[IOBUF_SIZE];
6299 } RamCompressState;
6301 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6303 int ret;
6304 memset(s, 0, sizeof(*s));
6305 s->f = f;
6306 ret = deflateInit2(&s->zstream, 1,
6307 Z_DEFLATED, 15,
6308 9, Z_DEFAULT_STRATEGY);
6309 if (ret != Z_OK)
6310 return -1;
6311 s->zstream.avail_out = IOBUF_SIZE;
6312 s->zstream.next_out = s->buf;
6313 return 0;
6316 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6318 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6319 qemu_put_be16(s->f, len);
6320 qemu_put_buffer(s->f, buf, len);
6323 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6325 int ret;
6327 s->zstream.avail_in = len;
6328 s->zstream.next_in = (uint8_t *)buf;
6329 while (s->zstream.avail_in > 0) {
6330 ret = deflate(&s->zstream, Z_NO_FLUSH);
6331 if (ret != Z_OK)
6332 return -1;
6333 if (s->zstream.avail_out == 0) {
6334 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6335 s->zstream.avail_out = IOBUF_SIZE;
6336 s->zstream.next_out = s->buf;
6339 return 0;
6342 static void ram_compress_close(RamCompressState *s)
6344 int len, ret;
6346 /* compress last bytes */
6347 for(;;) {
6348 ret = deflate(&s->zstream, Z_FINISH);
6349 if (ret == Z_OK || ret == Z_STREAM_END) {
6350 len = IOBUF_SIZE - s->zstream.avail_out;
6351 if (len > 0) {
6352 ram_put_cblock(s, s->buf, len);
6354 s->zstream.avail_out = IOBUF_SIZE;
6355 s->zstream.next_out = s->buf;
6356 if (ret == Z_STREAM_END)
6357 break;
6358 } else {
6359 goto fail;
6362 fail:
6363 deflateEnd(&s->zstream);
6366 typedef struct RamDecompressState {
6367 z_stream zstream;
6368 QEMUFile *f;
6369 uint8_t buf[IOBUF_SIZE];
6370 } RamDecompressState;
6372 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6374 int ret;
6375 memset(s, 0, sizeof(*s));
6376 s->f = f;
6377 ret = inflateInit(&s->zstream);
6378 if (ret != Z_OK)
6379 return -1;
6380 return 0;
6383 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6385 int ret, clen;
6387 s->zstream.avail_out = len;
6388 s->zstream.next_out = buf;
6389 while (s->zstream.avail_out > 0) {
6390 if (s->zstream.avail_in == 0) {
6391 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6392 return -1;
6393 clen = qemu_get_be16(s->f);
6394 if (clen > IOBUF_SIZE)
6395 return -1;
6396 qemu_get_buffer(s->f, s->buf, clen);
6397 s->zstream.avail_in = clen;
6398 s->zstream.next_in = s->buf;
6400 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6401 if (ret != Z_OK && ret != Z_STREAM_END) {
6402 return -1;
6405 return 0;
6408 static void ram_decompress_close(RamDecompressState *s)
6410 inflateEnd(&s->zstream);
6413 static void ram_save(QEMUFile *f, void *opaque)
6415 int i;
6416 RamCompressState s1, *s = &s1;
6417 uint8_t buf[10];
6419 qemu_put_be32(f, phys_ram_size);
6420 if (ram_compress_open(s, f) < 0)
6421 return;
6422 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6423 #if 0
6424 if (tight_savevm_enabled) {
6425 int64_t sector_num;
6426 int j;
6428 /* find if the memory block is available on a virtual
6429 block device */
6430 sector_num = -1;
6431 for(j = 0; j < MAX_DISKS; j++) {
6432 if (bs_table[j]) {
6433 sector_num = bdrv_hash_find(bs_table[j],
6434 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6435 if (sector_num >= 0)
6436 break;
6439 if (j == MAX_DISKS)
6440 goto normal_compress;
6441 buf[0] = 1;
6442 buf[1] = j;
6443 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6444 ram_compress_buf(s, buf, 10);
6445 } else
6446 #endif
6448 // normal_compress:
6449 buf[0] = 0;
6450 ram_compress_buf(s, buf, 1);
6451 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6454 ram_compress_close(s);
6457 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6459 RamDecompressState s1, *s = &s1;
6460 uint8_t buf[10];
6461 int i;
6463 if (version_id == 1)
6464 return ram_load_v1(f, opaque);
6465 if (version_id != 2)
6466 return -EINVAL;
6467 if (qemu_get_be32(f) != phys_ram_size)
6468 return -EINVAL;
6469 if (ram_decompress_open(s, f) < 0)
6470 return -EINVAL;
6471 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6472 if (ram_decompress_buf(s, buf, 1) < 0) {
6473 fprintf(stderr, "Error while reading ram block header\n");
6474 goto error;
6476 if (buf[0] == 0) {
6477 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6478 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6479 goto error;
6481 } else
6482 #if 0
6483 if (buf[0] == 1) {
6484 int bs_index;
6485 int64_t sector_num;
6487 ram_decompress_buf(s, buf + 1, 9);
6488 bs_index = buf[1];
6489 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6490 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6491 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6492 goto error;
6494 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6495 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6496 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6497 bs_index, sector_num);
6498 goto error;
6500 } else
6501 #endif
6503 error:
6504 printf("Error block header\n");
6505 return -EINVAL;
6508 ram_decompress_close(s);
6509 return 0;
6512 /***********************************************************/
6513 /* bottom halves (can be seen as timers which expire ASAP) */
6515 struct QEMUBH {
6516 QEMUBHFunc *cb;
6517 void *opaque;
6518 int scheduled;
6519 QEMUBH *next;
6522 static QEMUBH *first_bh = NULL;
6524 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6526 QEMUBH *bh;
6527 bh = qemu_mallocz(sizeof(QEMUBH));
6528 if (!bh)
6529 return NULL;
6530 bh->cb = cb;
6531 bh->opaque = opaque;
6532 return bh;
6535 int qemu_bh_poll(void)
6537 QEMUBH *bh, **pbh;
6538 int ret;
6540 ret = 0;
6541 for(;;) {
6542 pbh = &first_bh;
6543 bh = *pbh;
6544 if (!bh)
6545 break;
6546 ret = 1;
6547 *pbh = bh->next;
6548 bh->scheduled = 0;
6549 bh->cb(bh->opaque);
6551 return ret;
6554 void qemu_bh_schedule(QEMUBH *bh)
6556 CPUState *env = cpu_single_env;
6557 if (bh->scheduled)
6558 return;
6559 bh->scheduled = 1;
6560 bh->next = first_bh;
6561 first_bh = bh;
6563 /* stop the currently executing CPU to execute the BH ASAP */
6564 if (env) {
6565 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6569 void qemu_bh_cancel(QEMUBH *bh)
6571 QEMUBH **pbh;
6572 if (bh->scheduled) {
6573 pbh = &first_bh;
6574 while (*pbh != bh)
6575 pbh = &(*pbh)->next;
6576 *pbh = bh->next;
6577 bh->scheduled = 0;
6581 void qemu_bh_delete(QEMUBH *bh)
6583 qemu_bh_cancel(bh);
6584 qemu_free(bh);
6587 /***********************************************************/
6588 /* machine registration */
6590 QEMUMachine *first_machine = NULL;
6592 int qemu_register_machine(QEMUMachine *m)
6594 QEMUMachine **pm;
6595 pm = &first_machine;
6596 while (*pm != NULL)
6597 pm = &(*pm)->next;
6598 m->next = NULL;
6599 *pm = m;
6600 return 0;
6603 QEMUMachine *find_machine(const char *name)
6605 QEMUMachine *m;
6607 for(m = first_machine; m != NULL; m = m->next) {
6608 if (!strcmp(m->name, name))
6609 return m;
6611 return NULL;
6614 /***********************************************************/
6615 /* main execution loop */
6617 void gui_update(void *opaque)
6619 DisplayState *ds = opaque;
6620 ds->dpy_refresh(ds);
6621 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6624 struct vm_change_state_entry {
6625 VMChangeStateHandler *cb;
6626 void *opaque;
6627 LIST_ENTRY (vm_change_state_entry) entries;
6630 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6632 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6633 void *opaque)
6635 VMChangeStateEntry *e;
6637 e = qemu_mallocz(sizeof (*e));
6638 if (!e)
6639 return NULL;
6641 e->cb = cb;
6642 e->opaque = opaque;
6643 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6644 return e;
6647 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6649 LIST_REMOVE (e, entries);
6650 qemu_free (e);
6653 static void vm_state_notify(int running)
6655 VMChangeStateEntry *e;
6657 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6658 e->cb(e->opaque, running);
6662 /* XXX: support several handlers */
6663 static VMStopHandler *vm_stop_cb;
6664 static void *vm_stop_opaque;
6666 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6668 vm_stop_cb = cb;
6669 vm_stop_opaque = opaque;
6670 return 0;
6673 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6675 vm_stop_cb = NULL;
6678 void vm_start(void)
6680 if (!vm_running) {
6681 cpu_enable_ticks();
6682 vm_running = 1;
6683 vm_state_notify(1);
6684 qemu_rearm_alarm_timer(alarm_timer);
6688 void vm_stop(int reason)
6690 if (vm_running) {
6691 cpu_disable_ticks();
6692 vm_running = 0;
6693 if (reason != 0) {
6694 if (vm_stop_cb) {
6695 vm_stop_cb(vm_stop_opaque, reason);
6698 vm_state_notify(0);
6702 /* reset/shutdown handler */
6704 typedef struct QEMUResetEntry {
6705 QEMUResetHandler *func;
6706 void *opaque;
6707 struct QEMUResetEntry *next;
6708 } QEMUResetEntry;
6710 static QEMUResetEntry *first_reset_entry;
6711 static int reset_requested;
6712 static int shutdown_requested;
6713 static int powerdown_requested;
6715 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6717 QEMUResetEntry **pre, *re;
6719 pre = &first_reset_entry;
6720 while (*pre != NULL)
6721 pre = &(*pre)->next;
6722 re = qemu_mallocz(sizeof(QEMUResetEntry));
6723 re->func = func;
6724 re->opaque = opaque;
6725 re->next = NULL;
6726 *pre = re;
6729 static void qemu_system_reset(void)
6731 QEMUResetEntry *re;
6733 /* reset all devices */
6734 for(re = first_reset_entry; re != NULL; re = re->next) {
6735 re->func(re->opaque);
6739 void qemu_system_reset_request(void)
6741 if (no_reboot) {
6742 shutdown_requested = 1;
6743 } else {
6744 reset_requested = 1;
6746 if (cpu_single_env)
6747 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6750 void qemu_system_shutdown_request(void)
6752 shutdown_requested = 1;
6753 if (cpu_single_env)
6754 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6757 void qemu_system_powerdown_request(void)
6759 powerdown_requested = 1;
6760 if (cpu_single_env)
6761 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6764 void main_loop_wait(int timeout)
6766 IOHandlerRecord *ioh;
6767 fd_set rfds, wfds, xfds;
6768 int ret, nfds;
6769 #ifdef _WIN32
6770 int ret2, i;
6771 #endif
6772 struct timeval tv;
6773 PollingEntry *pe;
6776 /* XXX: need to suppress polling by better using win32 events */
6777 ret = 0;
6778 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6779 ret |= pe->func(pe->opaque);
6781 #ifdef _WIN32
6782 if (ret == 0) {
6783 int err;
6784 WaitObjects *w = &wait_objects;
6786 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6787 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6788 if (w->func[ret - WAIT_OBJECT_0])
6789 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6791 /* Check for additional signaled events */
6792 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6794 /* Check if event is signaled */
6795 ret2 = WaitForSingleObject(w->events[i], 0);
6796 if(ret2 == WAIT_OBJECT_0) {
6797 if (w->func[i])
6798 w->func[i](w->opaque[i]);
6799 } else if (ret2 == WAIT_TIMEOUT) {
6800 } else {
6801 err = GetLastError();
6802 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6805 } else if (ret == WAIT_TIMEOUT) {
6806 } else {
6807 err = GetLastError();
6808 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6811 #endif
6812 /* poll any events */
6813 /* XXX: separate device handlers from system ones */
6814 nfds = -1;
6815 FD_ZERO(&rfds);
6816 FD_ZERO(&wfds);
6817 FD_ZERO(&xfds);
6818 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6819 if (ioh->deleted)
6820 continue;
6821 if (ioh->fd_read &&
6822 (!ioh->fd_read_poll ||
6823 ioh->fd_read_poll(ioh->opaque) != 0)) {
6824 FD_SET(ioh->fd, &rfds);
6825 if (ioh->fd > nfds)
6826 nfds = ioh->fd;
6828 if (ioh->fd_write) {
6829 FD_SET(ioh->fd, &wfds);
6830 if (ioh->fd > nfds)
6831 nfds = ioh->fd;
6835 tv.tv_sec = 0;
6836 #ifdef _WIN32
6837 tv.tv_usec = 0;
6838 #else
6839 tv.tv_usec = timeout * 1000;
6840 #endif
6841 #if defined(CONFIG_SLIRP)
6842 if (slirp_inited) {
6843 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6845 #endif
6846 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6847 if (ret > 0) {
6848 IOHandlerRecord **pioh;
6850 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6851 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6852 ioh->fd_read(ioh->opaque);
6854 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6855 ioh->fd_write(ioh->opaque);
6859 /* remove deleted IO handlers */
6860 pioh = &first_io_handler;
6861 while (*pioh) {
6862 ioh = *pioh;
6863 if (ioh->deleted) {
6864 *pioh = ioh->next;
6865 qemu_free(ioh);
6866 } else
6867 pioh = &ioh->next;
6870 #if defined(CONFIG_SLIRP)
6871 if (slirp_inited) {
6872 if (ret < 0) {
6873 FD_ZERO(&rfds);
6874 FD_ZERO(&wfds);
6875 FD_ZERO(&xfds);
6877 slirp_select_poll(&rfds, &wfds, &xfds);
6879 #endif
6880 qemu_aio_poll();
6882 if (vm_running) {
6883 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6884 qemu_get_clock(vm_clock));
6885 /* run dma transfers, if any */
6886 DMA_run();
6889 /* real time timers */
6890 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6891 qemu_get_clock(rt_clock));
6893 /* Check bottom-halves last in case any of the earlier events triggered
6894 them. */
6895 qemu_bh_poll();
6899 static CPUState *cur_cpu;
6901 int main_loop(void)
6903 int ret, timeout;
6904 #ifdef CONFIG_PROFILER
6905 int64_t ti;
6906 #endif
6907 CPUState *env;
6909 cur_cpu = first_cpu;
6910 for(;;) {
6911 if (vm_running) {
6913 env = cur_cpu;
6914 for(;;) {
6915 /* get next cpu */
6916 env = env->next_cpu;
6917 if (!env)
6918 env = first_cpu;
6919 #ifdef CONFIG_PROFILER
6920 ti = profile_getclock();
6921 #endif
6922 ret = cpu_exec(env);
6923 #ifdef CONFIG_PROFILER
6924 qemu_time += profile_getclock() - ti;
6925 #endif
6926 if (ret == EXCP_HLT) {
6927 /* Give the next CPU a chance to run. */
6928 cur_cpu = env;
6929 continue;
6931 if (ret != EXCP_HALTED)
6932 break;
6933 /* all CPUs are halted ? */
6934 if (env == cur_cpu)
6935 break;
6937 cur_cpu = env;
6939 if (shutdown_requested) {
6940 ret = EXCP_INTERRUPT;
6941 break;
6943 if (reset_requested) {
6944 reset_requested = 0;
6945 qemu_system_reset();
6946 ret = EXCP_INTERRUPT;
6948 if (powerdown_requested) {
6949 powerdown_requested = 0;
6950 qemu_system_powerdown();
6951 ret = EXCP_INTERRUPT;
6953 if (ret == EXCP_DEBUG) {
6954 vm_stop(EXCP_DEBUG);
6956 /* If all cpus are halted then wait until the next IRQ */
6957 /* XXX: use timeout computed from timers */
6958 if (ret == EXCP_HALTED)
6959 timeout = 10;
6960 else
6961 timeout = 0;
6962 } else {
6963 timeout = 10;
6965 #ifdef CONFIG_PROFILER
6966 ti = profile_getclock();
6967 #endif
6968 main_loop_wait(timeout);
6969 #ifdef CONFIG_PROFILER
6970 dev_time += profile_getclock() - ti;
6971 #endif
6973 cpu_disable_ticks();
6974 return ret;
6977 static void help(int exitcode)
6979 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6980 "usage: %s [options] [disk_image]\n"
6981 "\n"
6982 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6983 "\n"
6984 "Standard options:\n"
6985 "-M machine select emulated machine (-M ? for list)\n"
6986 "-cpu cpu select CPU (-cpu ? for list)\n"
6987 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6988 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6989 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6990 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6991 "-mtdblock file use 'file' as on-board Flash memory image\n"
6992 "-sd file use 'file' as SecureDigital card image\n"
6993 "-pflash file use 'file' as a parallel flash image\n"
6994 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6995 "-snapshot write to temporary files instead of disk image files\n"
6996 #ifdef CONFIG_SDL
6997 "-no-frame open SDL window without a frame and window decorations\n"
6998 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6999 "-no-quit disable SDL window close capability\n"
7000 #endif
7001 #ifdef TARGET_I386
7002 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7003 #endif
7004 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7005 "-smp n set the number of CPUs to 'n' [default=1]\n"
7006 "-nographic disable graphical output and redirect serial I/Os to console\n"
7007 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7008 #ifndef _WIN32
7009 "-k language use keyboard layout (for example \"fr\" for French)\n"
7010 #endif
7011 #ifdef HAS_AUDIO
7012 "-audio-help print list of audio drivers and their options\n"
7013 "-soundhw c1,... enable audio support\n"
7014 " and only specified sound cards (comma separated list)\n"
7015 " use -soundhw ? to get the list of supported cards\n"
7016 " use -soundhw all to enable all of them\n"
7017 #endif
7018 "-localtime set the real time clock to local time [default=utc]\n"
7019 "-full-screen start in full screen\n"
7020 #ifdef TARGET_I386
7021 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7022 #endif
7023 "-usb enable the USB driver (will be the default soon)\n"
7024 "-usbdevice name add the host or guest USB device 'name'\n"
7025 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7026 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7027 #endif
7028 "-name string set the name of the guest\n"
7029 "\n"
7030 "Network options:\n"
7031 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7032 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7033 #ifdef CONFIG_SLIRP
7034 "-net user[,vlan=n][,hostname=host]\n"
7035 " connect the user mode network stack to VLAN 'n' and send\n"
7036 " hostname 'host' to DHCP clients\n"
7037 #endif
7038 #ifdef _WIN32
7039 "-net tap[,vlan=n],ifname=name\n"
7040 " connect the host TAP network interface to VLAN 'n'\n"
7041 #else
7042 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7043 " connect the host TAP network interface to VLAN 'n' and use the\n"
7044 " network scripts 'file' (default=%s)\n"
7045 " and 'dfile' (default=%s);\n"
7046 " use '[down]script=no' to disable script execution;\n"
7047 " use 'fd=h' to connect to an already opened TAP interface\n"
7048 #endif
7049 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7050 " connect the vlan 'n' to another VLAN using a socket connection\n"
7051 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7052 " connect the vlan 'n' to multicast maddr and port\n"
7053 "-net none use it alone to have zero network devices; if no -net option\n"
7054 " is provided, the default is '-net nic -net user'\n"
7055 "\n"
7056 #ifdef CONFIG_SLIRP
7057 "-tftp dir allow tftp access to files in dir [-net user]\n"
7058 "-bootp file advertise file in BOOTP replies\n"
7059 #ifndef _WIN32
7060 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7061 #endif
7062 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7063 " redirect TCP or UDP connections from host to guest [-net user]\n"
7064 #endif
7065 "\n"
7066 "Linux boot specific:\n"
7067 "-kernel bzImage use 'bzImage' as kernel image\n"
7068 "-append cmdline use 'cmdline' as kernel command line\n"
7069 "-initrd file use 'file' as initial ram disk\n"
7070 "\n"
7071 "Debug/Expert options:\n"
7072 "-monitor dev redirect the monitor to char device 'dev'\n"
7073 "-serial dev redirect the serial port to char device 'dev'\n"
7074 "-parallel dev redirect the parallel port to char device 'dev'\n"
7075 "-pidfile file Write PID to 'file'\n"
7076 "-S freeze CPU at startup (use 'c' to start execution)\n"
7077 "-s wait gdb connection to port\n"
7078 "-p port set gdb connection port [default=%s]\n"
7079 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7080 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7081 " translation (t=none or lba) (usually qemu can guess them)\n"
7082 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7083 #ifdef USE_KQEMU
7084 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7085 "-no-kqemu disable KQEMU kernel module usage\n"
7086 #endif
7087 #ifdef TARGET_I386
7088 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7089 " (default is CL-GD5446 PCI VGA)\n"
7090 "-no-acpi disable ACPI\n"
7091 #endif
7092 "-no-reboot exit instead of rebooting\n"
7093 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7094 "-vnc display start a VNC server on display\n"
7095 #ifndef _WIN32
7096 "-daemonize daemonize QEMU after initializing\n"
7097 #endif
7098 "-option-rom rom load a file, rom, into the option ROM space\n"
7099 #ifdef TARGET_SPARC
7100 "-prom-env variable=value set OpenBIOS nvram variables\n"
7101 #endif
7102 "-clock force the use of the given methods for timer alarm.\n"
7103 " To see what timers are available use -clock help\n"
7104 "\n"
7105 "During emulation, the following keys are useful:\n"
7106 "ctrl-alt-f toggle full screen\n"
7107 "ctrl-alt-n switch to virtual console 'n'\n"
7108 "ctrl-alt toggle mouse and keyboard grab\n"
7109 "\n"
7110 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7112 "qemu",
7113 DEFAULT_RAM_SIZE,
7114 #ifndef _WIN32
7115 DEFAULT_NETWORK_SCRIPT,
7116 DEFAULT_NETWORK_DOWN_SCRIPT,
7117 #endif
7118 DEFAULT_GDBSTUB_PORT,
7119 "/tmp/qemu.log");
7120 exit(exitcode);
7123 #define HAS_ARG 0x0001
7125 enum {
7126 QEMU_OPTION_h,
7128 QEMU_OPTION_M,
7129 QEMU_OPTION_cpu,
7130 QEMU_OPTION_fda,
7131 QEMU_OPTION_fdb,
7132 QEMU_OPTION_hda,
7133 QEMU_OPTION_hdb,
7134 QEMU_OPTION_hdc,
7135 QEMU_OPTION_hdd,
7136 QEMU_OPTION_cdrom,
7137 QEMU_OPTION_mtdblock,
7138 QEMU_OPTION_sd,
7139 QEMU_OPTION_pflash,
7140 QEMU_OPTION_boot,
7141 QEMU_OPTION_snapshot,
7142 #ifdef TARGET_I386
7143 QEMU_OPTION_no_fd_bootchk,
7144 #endif
7145 QEMU_OPTION_m,
7146 QEMU_OPTION_nographic,
7147 QEMU_OPTION_portrait,
7148 #ifdef HAS_AUDIO
7149 QEMU_OPTION_audio_help,
7150 QEMU_OPTION_soundhw,
7151 #endif
7153 QEMU_OPTION_net,
7154 QEMU_OPTION_tftp,
7155 QEMU_OPTION_bootp,
7156 QEMU_OPTION_smb,
7157 QEMU_OPTION_redir,
7159 QEMU_OPTION_kernel,
7160 QEMU_OPTION_append,
7161 QEMU_OPTION_initrd,
7163 QEMU_OPTION_S,
7164 QEMU_OPTION_s,
7165 QEMU_OPTION_p,
7166 QEMU_OPTION_d,
7167 QEMU_OPTION_hdachs,
7168 QEMU_OPTION_L,
7169 QEMU_OPTION_bios,
7170 QEMU_OPTION_no_code_copy,
7171 QEMU_OPTION_k,
7172 QEMU_OPTION_localtime,
7173 QEMU_OPTION_cirrusvga,
7174 QEMU_OPTION_vmsvga,
7175 QEMU_OPTION_g,
7176 QEMU_OPTION_std_vga,
7177 QEMU_OPTION_echr,
7178 QEMU_OPTION_monitor,
7179 QEMU_OPTION_serial,
7180 QEMU_OPTION_parallel,
7181 QEMU_OPTION_loadvm,
7182 QEMU_OPTION_full_screen,
7183 QEMU_OPTION_no_frame,
7184 QEMU_OPTION_alt_grab,
7185 QEMU_OPTION_no_quit,
7186 QEMU_OPTION_pidfile,
7187 QEMU_OPTION_no_kqemu,
7188 QEMU_OPTION_kernel_kqemu,
7189 QEMU_OPTION_win2k_hack,
7190 QEMU_OPTION_usb,
7191 QEMU_OPTION_usbdevice,
7192 QEMU_OPTION_smp,
7193 QEMU_OPTION_vnc,
7194 QEMU_OPTION_no_acpi,
7195 QEMU_OPTION_no_reboot,
7196 QEMU_OPTION_show_cursor,
7197 QEMU_OPTION_daemonize,
7198 QEMU_OPTION_option_rom,
7199 QEMU_OPTION_semihosting,
7200 QEMU_OPTION_name,
7201 QEMU_OPTION_prom_env,
7202 QEMU_OPTION_old_param,
7203 QEMU_OPTION_clock,
7204 QEMU_OPTION_startdate,
7207 typedef struct QEMUOption {
7208 const char *name;
7209 int flags;
7210 int index;
7211 } QEMUOption;
7213 const QEMUOption qemu_options[] = {
7214 { "h", 0, QEMU_OPTION_h },
7215 { "help", 0, QEMU_OPTION_h },
7217 { "M", HAS_ARG, QEMU_OPTION_M },
7218 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7219 { "fda", HAS_ARG, QEMU_OPTION_fda },
7220 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7221 { "hda", HAS_ARG, QEMU_OPTION_hda },
7222 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7223 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7224 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7225 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7226 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7227 { "sd", HAS_ARG, QEMU_OPTION_sd },
7228 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7229 { "boot", HAS_ARG, QEMU_OPTION_boot },
7230 { "snapshot", 0, QEMU_OPTION_snapshot },
7231 #ifdef TARGET_I386
7232 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7233 #endif
7234 { "m", HAS_ARG, QEMU_OPTION_m },
7235 { "nographic", 0, QEMU_OPTION_nographic },
7236 { "portrait", 0, QEMU_OPTION_portrait },
7237 { "k", HAS_ARG, QEMU_OPTION_k },
7238 #ifdef HAS_AUDIO
7239 { "audio-help", 0, QEMU_OPTION_audio_help },
7240 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7241 #endif
7243 { "net", HAS_ARG, QEMU_OPTION_net},
7244 #ifdef CONFIG_SLIRP
7245 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7246 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7247 #ifndef _WIN32
7248 { "smb", HAS_ARG, QEMU_OPTION_smb },
7249 #endif
7250 { "redir", HAS_ARG, QEMU_OPTION_redir },
7251 #endif
7253 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7254 { "append", HAS_ARG, QEMU_OPTION_append },
7255 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7257 { "S", 0, QEMU_OPTION_S },
7258 { "s", 0, QEMU_OPTION_s },
7259 { "p", HAS_ARG, QEMU_OPTION_p },
7260 { "d", HAS_ARG, QEMU_OPTION_d },
7261 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7262 { "L", HAS_ARG, QEMU_OPTION_L },
7263 { "bios", HAS_ARG, QEMU_OPTION_bios },
7264 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7265 #ifdef USE_KQEMU
7266 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7267 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7268 #endif
7269 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7270 { "g", 1, QEMU_OPTION_g },
7271 #endif
7272 { "localtime", 0, QEMU_OPTION_localtime },
7273 { "std-vga", 0, QEMU_OPTION_std_vga },
7274 { "echr", HAS_ARG, QEMU_OPTION_echr },
7275 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7276 { "serial", HAS_ARG, QEMU_OPTION_serial },
7277 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7278 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7279 { "full-screen", 0, QEMU_OPTION_full_screen },
7280 #ifdef CONFIG_SDL
7281 { "no-frame", 0, QEMU_OPTION_no_frame },
7282 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7283 { "no-quit", 0, QEMU_OPTION_no_quit },
7284 #endif
7285 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7286 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7287 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7288 { "smp", HAS_ARG, QEMU_OPTION_smp },
7289 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7291 /* temporary options */
7292 { "usb", 0, QEMU_OPTION_usb },
7293 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7294 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7295 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7296 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7297 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7298 { "daemonize", 0, QEMU_OPTION_daemonize },
7299 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7300 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7301 { "semihosting", 0, QEMU_OPTION_semihosting },
7302 #endif
7303 { "name", HAS_ARG, QEMU_OPTION_name },
7304 #if defined(TARGET_SPARC)
7305 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7306 #endif
7307 #if defined(TARGET_ARM)
7308 { "old-param", 0, QEMU_OPTION_old_param },
7309 #endif
7310 { "clock", HAS_ARG, QEMU_OPTION_clock },
7311 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7312 { NULL },
7315 /* password input */
7317 int qemu_key_check(BlockDriverState *bs, const char *name)
7319 char password[256];
7320 int i;
7322 if (!bdrv_is_encrypted(bs))
7323 return 0;
7325 term_printf("%s is encrypted.\n", name);
7326 for(i = 0; i < 3; i++) {
7327 monitor_readline("Password: ", 1, password, sizeof(password));
7328 if (bdrv_set_key(bs, password) == 0)
7329 return 0;
7330 term_printf("invalid password\n");
7332 return -EPERM;
7335 static BlockDriverState *get_bdrv(int index)
7337 BlockDriverState *bs;
7339 if (index < 4) {
7340 bs = bs_table[index];
7341 } else if (index < 6) {
7342 bs = fd_table[index - 4];
7343 } else {
7344 bs = NULL;
7346 return bs;
7349 static void read_passwords(void)
7351 BlockDriverState *bs;
7352 int i;
7354 for(i = 0; i < 6; i++) {
7355 bs = get_bdrv(i);
7356 if (bs)
7357 qemu_key_check(bs, bdrv_get_device_name(bs));
7361 /* XXX: currently we cannot use simultaneously different CPUs */
7362 void register_machines(void)
7364 #if defined(TARGET_I386)
7365 qemu_register_machine(&pc_machine);
7366 qemu_register_machine(&isapc_machine);
7367 #elif defined(TARGET_PPC)
7368 qemu_register_machine(&heathrow_machine);
7369 qemu_register_machine(&core99_machine);
7370 qemu_register_machine(&prep_machine);
7371 qemu_register_machine(&ref405ep_machine);
7372 qemu_register_machine(&taihu_machine);
7373 #elif defined(TARGET_MIPS)
7374 qemu_register_machine(&mips_machine);
7375 qemu_register_machine(&mips_malta_machine);
7376 qemu_register_machine(&mips_pica61_machine);
7377 qemu_register_machine(&mips_mipssim_machine);
7378 #elif defined(TARGET_SPARC)
7379 #ifdef TARGET_SPARC64
7380 qemu_register_machine(&sun4u_machine);
7381 #else
7382 qemu_register_machine(&ss5_machine);
7383 qemu_register_machine(&ss10_machine);
7384 #endif
7385 #elif defined(TARGET_ARM)
7386 qemu_register_machine(&integratorcp_machine);
7387 qemu_register_machine(&versatilepb_machine);
7388 qemu_register_machine(&versatileab_machine);
7389 qemu_register_machine(&realview_machine);
7390 qemu_register_machine(&akitapda_machine);
7391 qemu_register_machine(&spitzpda_machine);
7392 qemu_register_machine(&borzoipda_machine);
7393 qemu_register_machine(&terrierpda_machine);
7394 qemu_register_machine(&palmte_machine);
7395 #elif defined(TARGET_SH4)
7396 qemu_register_machine(&shix_machine);
7397 qemu_register_machine(&r2d_machine);
7398 #elif defined(TARGET_ALPHA)
7399 /* XXX: TODO */
7400 #elif defined(TARGET_M68K)
7401 qemu_register_machine(&mcf5208evb_machine);
7402 qemu_register_machine(&an5206_machine);
7403 #elif defined(TARGET_CRIS)
7404 qemu_register_machine(&bareetraxfs_machine);
7405 #else
7406 #error unsupported CPU
7407 #endif
7410 #ifdef HAS_AUDIO
7411 struct soundhw soundhw[] = {
7412 #ifdef HAS_AUDIO_CHOICE
7413 #ifdef TARGET_I386
7415 "pcspk",
7416 "PC speaker",
7419 { .init_isa = pcspk_audio_init }
7421 #endif
7423 "sb16",
7424 "Creative Sound Blaster 16",
7427 { .init_isa = SB16_init }
7430 #ifdef CONFIG_ADLIB
7432 "adlib",
7433 #ifdef HAS_YMF262
7434 "Yamaha YMF262 (OPL3)",
7435 #else
7436 "Yamaha YM3812 (OPL2)",
7437 #endif
7440 { .init_isa = Adlib_init }
7442 #endif
7444 #ifdef CONFIG_GUS
7446 "gus",
7447 "Gravis Ultrasound GF1",
7450 { .init_isa = GUS_init }
7452 #endif
7455 "es1370",
7456 "ENSONIQ AudioPCI ES1370",
7459 { .init_pci = es1370_init }
7461 #endif
7463 { NULL, NULL, 0, 0, { NULL } }
7466 static void select_soundhw (const char *optarg)
7468 struct soundhw *c;
7470 if (*optarg == '?') {
7471 show_valid_cards:
7473 printf ("Valid sound card names (comma separated):\n");
7474 for (c = soundhw; c->name; ++c) {
7475 printf ("%-11s %s\n", c->name, c->descr);
7477 printf ("\n-soundhw all will enable all of the above\n");
7478 exit (*optarg != '?');
7480 else {
7481 size_t l;
7482 const char *p;
7483 char *e;
7484 int bad_card = 0;
7486 if (!strcmp (optarg, "all")) {
7487 for (c = soundhw; c->name; ++c) {
7488 c->enabled = 1;
7490 return;
7493 p = optarg;
7494 while (*p) {
7495 e = strchr (p, ',');
7496 l = !e ? strlen (p) : (size_t) (e - p);
7498 for (c = soundhw; c->name; ++c) {
7499 if (!strncmp (c->name, p, l)) {
7500 c->enabled = 1;
7501 break;
7505 if (!c->name) {
7506 if (l > 80) {
7507 fprintf (stderr,
7508 "Unknown sound card name (too big to show)\n");
7510 else {
7511 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7512 (int) l, p);
7514 bad_card = 1;
7516 p += l + (e != NULL);
7519 if (bad_card)
7520 goto show_valid_cards;
7523 #endif
7525 #ifdef _WIN32
7526 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7528 exit(STATUS_CONTROL_C_EXIT);
7529 return TRUE;
7531 #endif
7533 #define MAX_NET_CLIENTS 32
7535 int main(int argc, char **argv)
7537 #ifdef CONFIG_GDBSTUB
7538 int use_gdbstub;
7539 const char *gdbstub_port;
7540 #endif
7541 int i, cdrom_index, pflash_index;
7542 int snapshot, linux_boot;
7543 const char *initrd_filename;
7544 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7545 const char *pflash_filename[MAX_PFLASH];
7546 const char *sd_filename;
7547 const char *mtd_filename;
7548 const char *kernel_filename, *kernel_cmdline;
7549 DisplayState *ds = &display_state;
7550 int cyls, heads, secs, translation;
7551 char net_clients[MAX_NET_CLIENTS][256];
7552 int nb_net_clients;
7553 int optind;
7554 const char *r, *optarg;
7555 CharDriverState *monitor_hd;
7556 char monitor_device[128];
7557 char serial_devices[MAX_SERIAL_PORTS][128];
7558 int serial_device_index;
7559 char parallel_devices[MAX_PARALLEL_PORTS][128];
7560 int parallel_device_index;
7561 const char *loadvm = NULL;
7562 QEMUMachine *machine;
7563 const char *cpu_model;
7564 char usb_devices[MAX_USB_CMDLINE][128];
7565 int usb_devices_index;
7566 int fds[2];
7567 const char *pid_file = NULL;
7568 VLANState *vlan;
7570 LIST_INIT (&vm_change_state_head);
7571 #ifndef _WIN32
7573 struct sigaction act;
7574 sigfillset(&act.sa_mask);
7575 act.sa_flags = 0;
7576 act.sa_handler = SIG_IGN;
7577 sigaction(SIGPIPE, &act, NULL);
7579 #else
7580 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7581 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7582 QEMU to run on a single CPU */
7584 HANDLE h;
7585 DWORD mask, smask;
7586 int i;
7587 h = GetCurrentProcess();
7588 if (GetProcessAffinityMask(h, &mask, &smask)) {
7589 for(i = 0; i < 32; i++) {
7590 if (mask & (1 << i))
7591 break;
7593 if (i != 32) {
7594 mask = 1 << i;
7595 SetProcessAffinityMask(h, mask);
7599 #endif
7601 register_machines();
7602 machine = first_machine;
7603 cpu_model = NULL;
7604 initrd_filename = NULL;
7605 for(i = 0; i < MAX_FD; i++)
7606 fd_filename[i] = NULL;
7607 for(i = 0; i < MAX_DISKS; i++)
7608 hd_filename[i] = NULL;
7609 for(i = 0; i < MAX_PFLASH; i++)
7610 pflash_filename[i] = NULL;
7611 pflash_index = 0;
7612 sd_filename = NULL;
7613 mtd_filename = NULL;
7614 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7615 vga_ram_size = VGA_RAM_SIZE;
7616 #ifdef CONFIG_GDBSTUB
7617 use_gdbstub = 0;
7618 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7619 #endif
7620 snapshot = 0;
7621 nographic = 0;
7622 kernel_filename = NULL;
7623 kernel_cmdline = "";
7624 #ifdef TARGET_PPC
7625 cdrom_index = 1;
7626 #else
7627 cdrom_index = 2;
7628 #endif
7629 cyls = heads = secs = 0;
7630 translation = BIOS_ATA_TRANSLATION_AUTO;
7631 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7633 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7634 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7635 serial_devices[i][0] = '\0';
7636 serial_device_index = 0;
7638 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7639 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7640 parallel_devices[i][0] = '\0';
7641 parallel_device_index = 0;
7643 usb_devices_index = 0;
7645 nb_net_clients = 0;
7647 nb_nics = 0;
7648 /* default mac address of the first network interface */
7650 optind = 1;
7651 for(;;) {
7652 if (optind >= argc)
7653 break;
7654 r = argv[optind];
7655 if (r[0] != '-') {
7656 hd_filename[0] = argv[optind++];
7657 } else {
7658 const QEMUOption *popt;
7660 optind++;
7661 /* Treat --foo the same as -foo. */
7662 if (r[1] == '-')
7663 r++;
7664 popt = qemu_options;
7665 for(;;) {
7666 if (!popt->name) {
7667 fprintf(stderr, "%s: invalid option -- '%s'\n",
7668 argv[0], r);
7669 exit(1);
7671 if (!strcmp(popt->name, r + 1))
7672 break;
7673 popt++;
7675 if (popt->flags & HAS_ARG) {
7676 if (optind >= argc) {
7677 fprintf(stderr, "%s: option '%s' requires an argument\n",
7678 argv[0], r);
7679 exit(1);
7681 optarg = argv[optind++];
7682 } else {
7683 optarg = NULL;
7686 switch(popt->index) {
7687 case QEMU_OPTION_M:
7688 machine = find_machine(optarg);
7689 if (!machine) {
7690 QEMUMachine *m;
7691 printf("Supported machines are:\n");
7692 for(m = first_machine; m != NULL; m = m->next) {
7693 printf("%-10s %s%s\n",
7694 m->name, m->desc,
7695 m == first_machine ? " (default)" : "");
7697 exit(*optarg != '?');
7699 break;
7700 case QEMU_OPTION_cpu:
7701 /* hw initialization will check this */
7702 if (*optarg == '?') {
7703 /* XXX: implement xxx_cpu_list for targets that still miss it */
7704 #if defined(cpu_list)
7705 cpu_list(stdout, &fprintf);
7706 #endif
7707 exit(0);
7708 } else {
7709 cpu_model = optarg;
7711 break;
7712 case QEMU_OPTION_initrd:
7713 initrd_filename = optarg;
7714 break;
7715 case QEMU_OPTION_hda:
7716 case QEMU_OPTION_hdb:
7717 case QEMU_OPTION_hdc:
7718 case QEMU_OPTION_hdd:
7720 int hd_index;
7721 hd_index = popt->index - QEMU_OPTION_hda;
7722 hd_filename[hd_index] = optarg;
7723 if (hd_index == cdrom_index)
7724 cdrom_index = -1;
7726 break;
7727 case QEMU_OPTION_mtdblock:
7728 mtd_filename = optarg;
7729 break;
7730 case QEMU_OPTION_sd:
7731 sd_filename = optarg;
7732 break;
7733 case QEMU_OPTION_pflash:
7734 if (pflash_index >= MAX_PFLASH) {
7735 fprintf(stderr, "qemu: too many parallel flash images\n");
7736 exit(1);
7738 pflash_filename[pflash_index++] = optarg;
7739 break;
7740 case QEMU_OPTION_snapshot:
7741 snapshot = 1;
7742 break;
7743 case QEMU_OPTION_hdachs:
7745 const char *p;
7746 p = optarg;
7747 cyls = strtol(p, (char **)&p, 0);
7748 if (cyls < 1 || cyls > 16383)
7749 goto chs_fail;
7750 if (*p != ',')
7751 goto chs_fail;
7752 p++;
7753 heads = strtol(p, (char **)&p, 0);
7754 if (heads < 1 || heads > 16)
7755 goto chs_fail;
7756 if (*p != ',')
7757 goto chs_fail;
7758 p++;
7759 secs = strtol(p, (char **)&p, 0);
7760 if (secs < 1 || secs > 63)
7761 goto chs_fail;
7762 if (*p == ',') {
7763 p++;
7764 if (!strcmp(p, "none"))
7765 translation = BIOS_ATA_TRANSLATION_NONE;
7766 else if (!strcmp(p, "lba"))
7767 translation = BIOS_ATA_TRANSLATION_LBA;
7768 else if (!strcmp(p, "auto"))
7769 translation = BIOS_ATA_TRANSLATION_AUTO;
7770 else
7771 goto chs_fail;
7772 } else if (*p != '\0') {
7773 chs_fail:
7774 fprintf(stderr, "qemu: invalid physical CHS format\n");
7775 exit(1);
7778 break;
7779 case QEMU_OPTION_nographic:
7780 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7781 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7782 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7783 nographic = 1;
7784 break;
7785 case QEMU_OPTION_portrait:
7786 graphic_rotate = 1;
7787 break;
7788 case QEMU_OPTION_kernel:
7789 kernel_filename = optarg;
7790 break;
7791 case QEMU_OPTION_append:
7792 kernel_cmdline = optarg;
7793 break;
7794 case QEMU_OPTION_cdrom:
7795 if (cdrom_index >= 0) {
7796 hd_filename[cdrom_index] = optarg;
7798 break;
7799 case QEMU_OPTION_boot:
7800 if (strlen(optarg) > MAX_BOOT_DEVICES) {
7801 fprintf(stderr, "qemu: too many boot devices\n");
7802 exit(1);
7804 strncpy(boot_device, optarg, MAX_BOOT_DEVICES);
7805 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7806 #define BOOTCHARS "acdn"
7807 #else
7808 #define BOOTCHARS "acd"
7809 #endif
7810 if (strlen(boot_device) != strspn(boot_device, BOOTCHARS)) {
7811 fprintf(stderr, "qemu: invalid boot device "
7812 "sequence '%s'\n", boot_device);
7813 exit(1);
7815 break;
7816 case QEMU_OPTION_fda:
7817 fd_filename[0] = optarg;
7818 break;
7819 case QEMU_OPTION_fdb:
7820 fd_filename[1] = optarg;
7821 break;
7822 #ifdef TARGET_I386
7823 case QEMU_OPTION_no_fd_bootchk:
7824 fd_bootchk = 0;
7825 break;
7826 #endif
7827 case QEMU_OPTION_no_code_copy:
7828 code_copy_enabled = 0;
7829 break;
7830 case QEMU_OPTION_net:
7831 if (nb_net_clients >= MAX_NET_CLIENTS) {
7832 fprintf(stderr, "qemu: too many network clients\n");
7833 exit(1);
7835 pstrcpy(net_clients[nb_net_clients],
7836 sizeof(net_clients[0]),
7837 optarg);
7838 nb_net_clients++;
7839 break;
7840 #ifdef CONFIG_SLIRP
7841 case QEMU_OPTION_tftp:
7842 tftp_prefix = optarg;
7843 break;
7844 case QEMU_OPTION_bootp:
7845 bootp_filename = optarg;
7846 break;
7847 #ifndef _WIN32
7848 case QEMU_OPTION_smb:
7849 net_slirp_smb(optarg);
7850 break;
7851 #endif
7852 case QEMU_OPTION_redir:
7853 net_slirp_redir(optarg);
7854 break;
7855 #endif
7856 #ifdef HAS_AUDIO
7857 case QEMU_OPTION_audio_help:
7858 AUD_help ();
7859 exit (0);
7860 break;
7861 case QEMU_OPTION_soundhw:
7862 select_soundhw (optarg);
7863 break;
7864 #endif
7865 case QEMU_OPTION_h:
7866 help(0);
7867 break;
7868 case QEMU_OPTION_m:
7869 ram_size = atoi(optarg) * 1024 * 1024;
7870 if (ram_size <= 0)
7871 help(1);
7872 if (ram_size > PHYS_RAM_MAX_SIZE) {
7873 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7874 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7875 exit(1);
7877 break;
7878 case QEMU_OPTION_d:
7880 int mask;
7881 CPULogItem *item;
7883 mask = cpu_str_to_log_mask(optarg);
7884 if (!mask) {
7885 printf("Log items (comma separated):\n");
7886 for(item = cpu_log_items; item->mask != 0; item++) {
7887 printf("%-10s %s\n", item->name, item->help);
7889 exit(1);
7891 cpu_set_log(mask);
7893 break;
7894 #ifdef CONFIG_GDBSTUB
7895 case QEMU_OPTION_s:
7896 use_gdbstub = 1;
7897 break;
7898 case QEMU_OPTION_p:
7899 gdbstub_port = optarg;
7900 break;
7901 #endif
7902 case QEMU_OPTION_L:
7903 bios_dir = optarg;
7904 break;
7905 case QEMU_OPTION_bios:
7906 bios_name = optarg;
7907 break;
7908 case QEMU_OPTION_S:
7909 autostart = 0;
7910 break;
7911 case QEMU_OPTION_k:
7912 keyboard_layout = optarg;
7913 break;
7914 case QEMU_OPTION_localtime:
7915 rtc_utc = 0;
7916 break;
7917 case QEMU_OPTION_cirrusvga:
7918 cirrus_vga_enabled = 1;
7919 vmsvga_enabled = 0;
7920 break;
7921 case QEMU_OPTION_vmsvga:
7922 cirrus_vga_enabled = 0;
7923 vmsvga_enabled = 1;
7924 break;
7925 case QEMU_OPTION_std_vga:
7926 cirrus_vga_enabled = 0;
7927 vmsvga_enabled = 0;
7928 break;
7929 case QEMU_OPTION_g:
7931 const char *p;
7932 int w, h, depth;
7933 p = optarg;
7934 w = strtol(p, (char **)&p, 10);
7935 if (w <= 0) {
7936 graphic_error:
7937 fprintf(stderr, "qemu: invalid resolution or depth\n");
7938 exit(1);
7940 if (*p != 'x')
7941 goto graphic_error;
7942 p++;
7943 h = strtol(p, (char **)&p, 10);
7944 if (h <= 0)
7945 goto graphic_error;
7946 if (*p == 'x') {
7947 p++;
7948 depth = strtol(p, (char **)&p, 10);
7949 if (depth != 8 && depth != 15 && depth != 16 &&
7950 depth != 24 && depth != 32)
7951 goto graphic_error;
7952 } else if (*p == '\0') {
7953 depth = graphic_depth;
7954 } else {
7955 goto graphic_error;
7958 graphic_width = w;
7959 graphic_height = h;
7960 graphic_depth = depth;
7962 break;
7963 case QEMU_OPTION_echr:
7965 char *r;
7966 term_escape_char = strtol(optarg, &r, 0);
7967 if (r == optarg)
7968 printf("Bad argument to echr\n");
7969 break;
7971 case QEMU_OPTION_monitor:
7972 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7973 break;
7974 case QEMU_OPTION_serial:
7975 if (serial_device_index >= MAX_SERIAL_PORTS) {
7976 fprintf(stderr, "qemu: too many serial ports\n");
7977 exit(1);
7979 pstrcpy(serial_devices[serial_device_index],
7980 sizeof(serial_devices[0]), optarg);
7981 serial_device_index++;
7982 break;
7983 case QEMU_OPTION_parallel:
7984 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7985 fprintf(stderr, "qemu: too many parallel ports\n");
7986 exit(1);
7988 pstrcpy(parallel_devices[parallel_device_index],
7989 sizeof(parallel_devices[0]), optarg);
7990 parallel_device_index++;
7991 break;
7992 case QEMU_OPTION_loadvm:
7993 loadvm = optarg;
7994 break;
7995 case QEMU_OPTION_full_screen:
7996 full_screen = 1;
7997 break;
7998 #ifdef CONFIG_SDL
7999 case QEMU_OPTION_no_frame:
8000 no_frame = 1;
8001 break;
8002 case QEMU_OPTION_alt_grab:
8003 alt_grab = 1;
8004 break;
8005 case QEMU_OPTION_no_quit:
8006 no_quit = 1;
8007 break;
8008 #endif
8009 case QEMU_OPTION_pidfile:
8010 pid_file = optarg;
8011 break;
8012 #ifdef TARGET_I386
8013 case QEMU_OPTION_win2k_hack:
8014 win2k_install_hack = 1;
8015 break;
8016 #endif
8017 #ifdef USE_KQEMU
8018 case QEMU_OPTION_no_kqemu:
8019 kqemu_allowed = 0;
8020 break;
8021 case QEMU_OPTION_kernel_kqemu:
8022 kqemu_allowed = 2;
8023 break;
8024 #endif
8025 case QEMU_OPTION_usb:
8026 usb_enabled = 1;
8027 break;
8028 case QEMU_OPTION_usbdevice:
8029 usb_enabled = 1;
8030 if (usb_devices_index >= MAX_USB_CMDLINE) {
8031 fprintf(stderr, "Too many USB devices\n");
8032 exit(1);
8034 pstrcpy(usb_devices[usb_devices_index],
8035 sizeof(usb_devices[usb_devices_index]),
8036 optarg);
8037 usb_devices_index++;
8038 break;
8039 case QEMU_OPTION_smp:
8040 smp_cpus = atoi(optarg);
8041 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8042 fprintf(stderr, "Invalid number of CPUs\n");
8043 exit(1);
8045 break;
8046 case QEMU_OPTION_vnc:
8047 vnc_display = optarg;
8048 break;
8049 case QEMU_OPTION_no_acpi:
8050 acpi_enabled = 0;
8051 break;
8052 case QEMU_OPTION_no_reboot:
8053 no_reboot = 1;
8054 break;
8055 case QEMU_OPTION_show_cursor:
8056 cursor_hide = 0;
8057 break;
8058 case QEMU_OPTION_daemonize:
8059 daemonize = 1;
8060 break;
8061 case QEMU_OPTION_option_rom:
8062 if (nb_option_roms >= MAX_OPTION_ROMS) {
8063 fprintf(stderr, "Too many option ROMs\n");
8064 exit(1);
8066 option_rom[nb_option_roms] = optarg;
8067 nb_option_roms++;
8068 break;
8069 case QEMU_OPTION_semihosting:
8070 semihosting_enabled = 1;
8071 break;
8072 case QEMU_OPTION_name:
8073 qemu_name = optarg;
8074 break;
8075 #ifdef TARGET_SPARC
8076 case QEMU_OPTION_prom_env:
8077 if (nb_prom_envs >= MAX_PROM_ENVS) {
8078 fprintf(stderr, "Too many prom variables\n");
8079 exit(1);
8081 prom_envs[nb_prom_envs] = optarg;
8082 nb_prom_envs++;
8083 break;
8084 #endif
8085 #ifdef TARGET_ARM
8086 case QEMU_OPTION_old_param:
8087 old_param = 1;
8088 #endif
8089 case QEMU_OPTION_clock:
8090 configure_alarms(optarg);
8091 break;
8092 case QEMU_OPTION_startdate:
8094 struct tm tm;
8095 if (!strcmp(optarg, "now")) {
8096 rtc_start_date = -1;
8097 } else {
8098 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8099 &tm.tm_year,
8100 &tm.tm_mon,
8101 &tm.tm_mday,
8102 &tm.tm_hour,
8103 &tm.tm_min,
8104 &tm.tm_sec) == 6) {
8105 /* OK */
8106 } else if (sscanf(optarg, "%d-%d-%d",
8107 &tm.tm_year,
8108 &tm.tm_mon,
8109 &tm.tm_mday) == 3) {
8110 tm.tm_hour = 0;
8111 tm.tm_min = 0;
8112 tm.tm_sec = 0;
8113 } else {
8114 goto date_fail;
8116 tm.tm_year -= 1900;
8117 tm.tm_mon--;
8118 rtc_start_date = timegm(&tm);
8119 if (rtc_start_date == -1) {
8120 date_fail:
8121 fprintf(stderr, "Invalid date format. Valid format are:\n"
8122 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8123 exit(1);
8127 break;
8132 #ifndef _WIN32
8133 if (daemonize && !nographic && vnc_display == NULL) {
8134 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8135 daemonize = 0;
8138 if (daemonize) {
8139 pid_t pid;
8141 if (pipe(fds) == -1)
8142 exit(1);
8144 pid = fork();
8145 if (pid > 0) {
8146 uint8_t status;
8147 ssize_t len;
8149 close(fds[1]);
8151 again:
8152 len = read(fds[0], &status, 1);
8153 if (len == -1 && (errno == EINTR))
8154 goto again;
8156 if (len != 1)
8157 exit(1);
8158 else if (status == 1) {
8159 fprintf(stderr, "Could not acquire pidfile\n");
8160 exit(1);
8161 } else
8162 exit(0);
8163 } else if (pid < 0)
8164 exit(1);
8166 setsid();
8168 pid = fork();
8169 if (pid > 0)
8170 exit(0);
8171 else if (pid < 0)
8172 exit(1);
8174 umask(027);
8175 chdir("/");
8177 signal(SIGTSTP, SIG_IGN);
8178 signal(SIGTTOU, SIG_IGN);
8179 signal(SIGTTIN, SIG_IGN);
8181 #endif
8183 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8184 if (daemonize) {
8185 uint8_t status = 1;
8186 write(fds[1], &status, 1);
8187 } else
8188 fprintf(stderr, "Could not acquire pid file\n");
8189 exit(1);
8192 #ifdef USE_KQEMU
8193 if (smp_cpus > 1)
8194 kqemu_allowed = 0;
8195 #endif
8196 linux_boot = (kernel_filename != NULL);
8198 if (!linux_boot &&
8199 (!strchr(boot_device, 'n')) &&
8200 hd_filename[0] == '\0' &&
8201 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8202 fd_filename[0] == '\0')
8203 help(1);
8205 /* boot to floppy or the default cd if no hard disk defined yet */
8206 if (!boot_device[0]) {
8207 if (hd_filename[0] != '\0')
8208 boot_device[0] = 'c';
8209 else if (fd_filename[0] != '\0')
8210 boot_device[0] = 'a';
8211 else
8212 boot_device[0] = 'd';
8213 boot_device[1] = 0;
8215 setvbuf(stdout, NULL, _IOLBF, 0);
8217 init_timers();
8218 init_timer_alarm();
8219 qemu_aio_init();
8221 #ifdef _WIN32
8222 socket_init();
8223 #endif
8225 /* init network clients */
8226 if (nb_net_clients == 0) {
8227 /* if no clients, we use a default config */
8228 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8229 "nic");
8230 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8231 "user");
8232 nb_net_clients = 2;
8235 for(i = 0;i < nb_net_clients; i++) {
8236 if (net_client_init(net_clients[i]) < 0)
8237 exit(1);
8239 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8240 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8241 continue;
8242 if (vlan->nb_guest_devs == 0) {
8243 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8244 exit(1);
8246 if (vlan->nb_host_devs == 0)
8247 fprintf(stderr,
8248 "Warning: vlan %d is not connected to host network\n",
8249 vlan->id);
8252 #ifdef TARGET_I386
8253 if (strchr(boot_device, 'n')) {
8254 for (i = 0; i < nb_nics; i++) {
8255 const char *model = nd_table[i].model;
8256 char buf[1024];
8257 if (model == NULL)
8258 model = "ne2k_pci";
8259 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8260 if (get_image_size(buf) > 0) {
8261 option_rom[nb_option_roms] = strdup(buf);
8262 nb_option_roms++;
8263 break;
8266 if (i == nb_nics) {
8267 fprintf(stderr, "No valid PXE rom found for network device\n");
8268 exit(1);
8271 #endif
8273 /* init the memory */
8274 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8276 phys_ram_base = qemu_vmalloc(phys_ram_size);
8277 if (!phys_ram_base) {
8278 fprintf(stderr, "Could not allocate physical memory\n");
8279 exit(1);
8282 /* we always create the cdrom drive, even if no disk is there */
8283 bdrv_init();
8284 if (cdrom_index >= 0) {
8285 bs_table[cdrom_index] = bdrv_new("cdrom");
8286 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8289 /* open the virtual block devices */
8290 for(i = 0; i < MAX_DISKS; i++) {
8291 if (hd_filename[i]) {
8292 if (!bs_table[i]) {
8293 char buf[64];
8294 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8295 bs_table[i] = bdrv_new(buf);
8297 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8298 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8299 hd_filename[i]);
8300 exit(1);
8302 if (i == 0 && cyls != 0) {
8303 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8304 bdrv_set_translation_hint(bs_table[i], translation);
8309 /* we always create at least one floppy disk */
8310 fd_table[0] = bdrv_new("fda");
8311 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8313 for(i = 0; i < MAX_FD; i++) {
8314 if (fd_filename[i]) {
8315 if (!fd_table[i]) {
8316 char buf[64];
8317 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8318 fd_table[i] = bdrv_new(buf);
8319 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8321 if (fd_filename[i][0] != '\0') {
8322 if (bdrv_open(fd_table[i], fd_filename[i],
8323 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8324 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8325 fd_filename[i]);
8326 exit(1);
8332 /* Open the virtual parallel flash block devices */
8333 for(i = 0; i < MAX_PFLASH; i++) {
8334 if (pflash_filename[i]) {
8335 if (!pflash_table[i]) {
8336 char buf[64];
8337 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8338 pflash_table[i] = bdrv_new(buf);
8340 if (bdrv_open(pflash_table[i], pflash_filename[i],
8341 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8342 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8343 pflash_filename[i]);
8344 exit(1);
8349 sd_bdrv = bdrv_new ("sd");
8350 /* FIXME: This isn't really a floppy, but it's a reasonable
8351 approximation. */
8352 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8353 if (sd_filename) {
8354 if (bdrv_open(sd_bdrv, sd_filename,
8355 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8356 fprintf(stderr, "qemu: could not open SD card image %s\n",
8357 sd_filename);
8358 } else
8359 qemu_key_check(sd_bdrv, sd_filename);
8362 if (mtd_filename) {
8363 mtd_bdrv = bdrv_new ("mtd");
8364 if (bdrv_open(mtd_bdrv, mtd_filename,
8365 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8366 qemu_key_check(mtd_bdrv, mtd_filename)) {
8367 fprintf(stderr, "qemu: could not open Flash image %s\n",
8368 mtd_filename);
8369 bdrv_delete(mtd_bdrv);
8370 mtd_bdrv = 0;
8374 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8375 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8377 init_ioports();
8379 /* terminal init */
8380 memset(&display_state, 0, sizeof(display_state));
8381 if (nographic) {
8382 /* nearly nothing to do */
8383 dumb_display_init(ds);
8384 } else if (vnc_display != NULL) {
8385 vnc_display_init(ds);
8386 if (vnc_display_open(ds, vnc_display) < 0)
8387 exit(1);
8388 } else {
8389 #if defined(CONFIG_SDL)
8390 sdl_display_init(ds, full_screen, no_frame);
8391 #elif defined(CONFIG_COCOA)
8392 cocoa_display_init(ds, full_screen);
8393 #endif
8396 /* Maintain compatibility with multiple stdio monitors */
8397 if (!strcmp(monitor_device,"stdio")) {
8398 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8399 if (!strcmp(serial_devices[i],"mon:stdio")) {
8400 monitor_device[0] = '\0';
8401 break;
8402 } else if (!strcmp(serial_devices[i],"stdio")) {
8403 monitor_device[0] = '\0';
8404 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8405 break;
8409 if (monitor_device[0] != '\0') {
8410 monitor_hd = qemu_chr_open(monitor_device);
8411 if (!monitor_hd) {
8412 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8413 exit(1);
8415 monitor_init(monitor_hd, !nographic);
8418 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8419 const char *devname = serial_devices[i];
8420 if (devname[0] != '\0' && strcmp(devname, "none")) {
8421 serial_hds[i] = qemu_chr_open(devname);
8422 if (!serial_hds[i]) {
8423 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8424 devname);
8425 exit(1);
8427 if (strstart(devname, "vc", 0))
8428 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8432 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8433 const char *devname = parallel_devices[i];
8434 if (devname[0] != '\0' && strcmp(devname, "none")) {
8435 parallel_hds[i] = qemu_chr_open(devname);
8436 if (!parallel_hds[i]) {
8437 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8438 devname);
8439 exit(1);
8441 if (strstart(devname, "vc", 0))
8442 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8446 machine->init(ram_size, vga_ram_size, boot_device,
8447 ds, fd_filename, snapshot,
8448 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8450 /* init USB devices */
8451 if (usb_enabled) {
8452 for(i = 0; i < usb_devices_index; i++) {
8453 if (usb_device_add(usb_devices[i]) < 0) {
8454 fprintf(stderr, "Warning: could not add USB device %s\n",
8455 usb_devices[i]);
8460 if (display_state.dpy_refresh) {
8461 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8462 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8465 #ifdef CONFIG_GDBSTUB
8466 if (use_gdbstub) {
8467 /* XXX: use standard host:port notation and modify options
8468 accordingly. */
8469 if (gdbserver_start(gdbstub_port) < 0) {
8470 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8471 gdbstub_port);
8472 exit(1);
8475 #endif
8477 if (loadvm)
8478 do_loadvm(loadvm);
8481 /* XXX: simplify init */
8482 read_passwords();
8483 if (autostart) {
8484 vm_start();
8488 if (daemonize) {
8489 uint8_t status = 0;
8490 ssize_t len;
8491 int fd;
8493 again1:
8494 len = write(fds[1], &status, 1);
8495 if (len == -1 && (errno == EINTR))
8496 goto again1;
8498 if (len != 1)
8499 exit(1);
8501 TFR(fd = open("/dev/null", O_RDWR));
8502 if (fd == -1)
8503 exit(1);
8505 dup2(fd, 0);
8506 dup2(fd, 1);
8507 dup2(fd, 2);
8509 close(fd);
8512 main_loop();
8513 quit_timers();
8515 #if !defined(_WIN32)
8516 /* close network clients */
8517 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8518 VLANClientState *vc;
8520 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8521 if (vc->fd_read == tap_receive) {
8522 char ifname[64];
8523 TAPState *s = vc->opaque;
8525 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8526 s->down_script[0])
8527 launch_script(s->down_script, ifname, s->fd);
8531 #endif
8532 return 0;