ARMv7 support.
[qemu/mini2440.git] / vl.c
blob7ffc904e05548daf4a3fb964907c8aecf877e68e
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_base0);
6130 qemu_put_be32(f, env->cp15.c2_base1);
6131 qemu_put_be32(f, env->cp15.c2_mask);
6132 qemu_put_be32(f, env->cp15.c2_data);
6133 qemu_put_be32(f, env->cp15.c2_insn);
6134 qemu_put_be32(f, env->cp15.c3);
6135 qemu_put_be32(f, env->cp15.c5_insn);
6136 qemu_put_be32(f, env->cp15.c5_data);
6137 for (i = 0; i < 8; i++) {
6138 qemu_put_be32(f, env->cp15.c6_region[i]);
6140 qemu_put_be32(f, env->cp15.c6_insn);
6141 qemu_put_be32(f, env->cp15.c6_data);
6142 qemu_put_be32(f, env->cp15.c9_insn);
6143 qemu_put_be32(f, env->cp15.c9_data);
6144 qemu_put_be32(f, env->cp15.c13_fcse);
6145 qemu_put_be32(f, env->cp15.c13_context);
6146 qemu_put_be32(f, env->cp15.c13_tls1);
6147 qemu_put_be32(f, env->cp15.c13_tls2);
6148 qemu_put_be32(f, env->cp15.c13_tls3);
6149 qemu_put_be32(f, env->cp15.c15_cpar);
6151 qemu_put_be32(f, env->features);
6153 if (arm_feature(env, ARM_FEATURE_VFP)) {
6154 for (i = 0; i < 16; i++) {
6155 CPU_DoubleU u;
6156 u.d = env->vfp.regs[i];
6157 qemu_put_be32(f, u.l.upper);
6158 qemu_put_be32(f, u.l.lower);
6160 for (i = 0; i < 16; i++) {
6161 qemu_put_be32(f, env->vfp.xregs[i]);
6164 /* TODO: Should use proper FPSCR access functions. */
6165 qemu_put_be32(f, env->vfp.vec_len);
6166 qemu_put_be32(f, env->vfp.vec_stride);
6168 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6169 for (i = 16; i < 32; i++) {
6170 CPU_DoubleU u;
6171 u.d = env->vfp.regs[i];
6172 qemu_put_be32(f, u.l.upper);
6173 qemu_put_be32(f, u.l.lower);
6178 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6179 for (i = 0; i < 16; i++) {
6180 qemu_put_be64(f, env->iwmmxt.regs[i]);
6182 for (i = 0; i < 16; i++) {
6183 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6187 if (arm_feature(env, ARM_FEATURE_M)) {
6188 qemu_put_be32(f, env->v7m.other_sp);
6189 qemu_put_be32(f, env->v7m.vecbase);
6190 qemu_put_be32(f, env->v7m.basepri);
6191 qemu_put_be32(f, env->v7m.control);
6192 qemu_put_be32(f, env->v7m.current_sp);
6193 qemu_put_be32(f, env->v7m.exception);
6197 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6199 CPUARMState *env = (CPUARMState *)opaque;
6200 int i;
6202 if (version_id != ARM_CPU_SAVE_VERSION)
6203 return -EINVAL;
6205 for (i = 0; i < 16; i++) {
6206 env->regs[i] = qemu_get_be32(f);
6208 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6209 env->spsr = qemu_get_be32(f);
6210 for (i = 0; i < 6; i++) {
6211 env->banked_spsr[i] = qemu_get_be32(f);
6212 env->banked_r13[i] = qemu_get_be32(f);
6213 env->banked_r14[i] = qemu_get_be32(f);
6215 for (i = 0; i < 5; i++) {
6216 env->usr_regs[i] = qemu_get_be32(f);
6217 env->fiq_regs[i] = qemu_get_be32(f);
6219 env->cp15.c0_cpuid = qemu_get_be32(f);
6220 env->cp15.c0_cachetype = qemu_get_be32(f);
6221 env->cp15.c1_sys = qemu_get_be32(f);
6222 env->cp15.c1_coproc = qemu_get_be32(f);
6223 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6224 env->cp15.c2_base0 = qemu_get_be32(f);
6225 env->cp15.c2_base1 = qemu_get_be32(f);
6226 env->cp15.c2_mask = qemu_get_be32(f);
6227 env->cp15.c2_data = qemu_get_be32(f);
6228 env->cp15.c2_insn = qemu_get_be32(f);
6229 env->cp15.c3 = qemu_get_be32(f);
6230 env->cp15.c5_insn = qemu_get_be32(f);
6231 env->cp15.c5_data = qemu_get_be32(f);
6232 for (i = 0; i < 8; i++) {
6233 env->cp15.c6_region[i] = qemu_get_be32(f);
6235 env->cp15.c6_insn = qemu_get_be32(f);
6236 env->cp15.c6_data = qemu_get_be32(f);
6237 env->cp15.c9_insn = qemu_get_be32(f);
6238 env->cp15.c9_data = qemu_get_be32(f);
6239 env->cp15.c13_fcse = qemu_get_be32(f);
6240 env->cp15.c13_context = qemu_get_be32(f);
6241 env->cp15.c13_tls1 = qemu_get_be32(f);
6242 env->cp15.c13_tls2 = qemu_get_be32(f);
6243 env->cp15.c13_tls3 = qemu_get_be32(f);
6244 env->cp15.c15_cpar = qemu_get_be32(f);
6246 env->features = qemu_get_be32(f);
6248 if (arm_feature(env, ARM_FEATURE_VFP)) {
6249 for (i = 0; i < 16; i++) {
6250 CPU_DoubleU u;
6251 u.l.upper = qemu_get_be32(f);
6252 u.l.lower = qemu_get_be32(f);
6253 env->vfp.regs[i] = u.d;
6255 for (i = 0; i < 16; i++) {
6256 env->vfp.xregs[i] = qemu_get_be32(f);
6259 /* TODO: Should use proper FPSCR access functions. */
6260 env->vfp.vec_len = qemu_get_be32(f);
6261 env->vfp.vec_stride = qemu_get_be32(f);
6263 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6264 for (i = 0; i < 16; i++) {
6265 CPU_DoubleU u;
6266 u.l.upper = qemu_get_be32(f);
6267 u.l.lower = qemu_get_be32(f);
6268 env->vfp.regs[i] = u.d;
6273 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6274 for (i = 0; i < 16; i++) {
6275 env->iwmmxt.regs[i] = qemu_get_be64(f);
6277 for (i = 0; i < 16; i++) {
6278 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6282 if (arm_feature(env, ARM_FEATURE_M)) {
6283 env->v7m.other_sp = qemu_get_be32(f);
6284 env->v7m.vecbase = qemu_get_be32(f);
6285 env->v7m.basepri = qemu_get_be32(f);
6286 env->v7m.control = qemu_get_be32(f);
6287 env->v7m.current_sp = qemu_get_be32(f);
6288 env->v7m.exception = qemu_get_be32(f);
6291 return 0;
6294 #else
6296 #warning No CPU save/restore functions
6298 #endif
6300 /***********************************************************/
6301 /* ram save/restore */
6303 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6305 int v;
6307 v = qemu_get_byte(f);
6308 switch(v) {
6309 case 0:
6310 if (qemu_get_buffer(f, buf, len) != len)
6311 return -EIO;
6312 break;
6313 case 1:
6314 v = qemu_get_byte(f);
6315 memset(buf, v, len);
6316 break;
6317 default:
6318 return -EINVAL;
6320 return 0;
6323 static int ram_load_v1(QEMUFile *f, void *opaque)
6325 int i, ret;
6327 if (qemu_get_be32(f) != phys_ram_size)
6328 return -EINVAL;
6329 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6330 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6331 if (ret)
6332 return ret;
6334 return 0;
6337 #define BDRV_HASH_BLOCK_SIZE 1024
6338 #define IOBUF_SIZE 4096
6339 #define RAM_CBLOCK_MAGIC 0xfabe
6341 typedef struct RamCompressState {
6342 z_stream zstream;
6343 QEMUFile *f;
6344 uint8_t buf[IOBUF_SIZE];
6345 } RamCompressState;
6347 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6349 int ret;
6350 memset(s, 0, sizeof(*s));
6351 s->f = f;
6352 ret = deflateInit2(&s->zstream, 1,
6353 Z_DEFLATED, 15,
6354 9, Z_DEFAULT_STRATEGY);
6355 if (ret != Z_OK)
6356 return -1;
6357 s->zstream.avail_out = IOBUF_SIZE;
6358 s->zstream.next_out = s->buf;
6359 return 0;
6362 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6364 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6365 qemu_put_be16(s->f, len);
6366 qemu_put_buffer(s->f, buf, len);
6369 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6371 int ret;
6373 s->zstream.avail_in = len;
6374 s->zstream.next_in = (uint8_t *)buf;
6375 while (s->zstream.avail_in > 0) {
6376 ret = deflate(&s->zstream, Z_NO_FLUSH);
6377 if (ret != Z_OK)
6378 return -1;
6379 if (s->zstream.avail_out == 0) {
6380 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6381 s->zstream.avail_out = IOBUF_SIZE;
6382 s->zstream.next_out = s->buf;
6385 return 0;
6388 static void ram_compress_close(RamCompressState *s)
6390 int len, ret;
6392 /* compress last bytes */
6393 for(;;) {
6394 ret = deflate(&s->zstream, Z_FINISH);
6395 if (ret == Z_OK || ret == Z_STREAM_END) {
6396 len = IOBUF_SIZE - s->zstream.avail_out;
6397 if (len > 0) {
6398 ram_put_cblock(s, s->buf, len);
6400 s->zstream.avail_out = IOBUF_SIZE;
6401 s->zstream.next_out = s->buf;
6402 if (ret == Z_STREAM_END)
6403 break;
6404 } else {
6405 goto fail;
6408 fail:
6409 deflateEnd(&s->zstream);
6412 typedef struct RamDecompressState {
6413 z_stream zstream;
6414 QEMUFile *f;
6415 uint8_t buf[IOBUF_SIZE];
6416 } RamDecompressState;
6418 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6420 int ret;
6421 memset(s, 0, sizeof(*s));
6422 s->f = f;
6423 ret = inflateInit(&s->zstream);
6424 if (ret != Z_OK)
6425 return -1;
6426 return 0;
6429 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6431 int ret, clen;
6433 s->zstream.avail_out = len;
6434 s->zstream.next_out = buf;
6435 while (s->zstream.avail_out > 0) {
6436 if (s->zstream.avail_in == 0) {
6437 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6438 return -1;
6439 clen = qemu_get_be16(s->f);
6440 if (clen > IOBUF_SIZE)
6441 return -1;
6442 qemu_get_buffer(s->f, s->buf, clen);
6443 s->zstream.avail_in = clen;
6444 s->zstream.next_in = s->buf;
6446 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6447 if (ret != Z_OK && ret != Z_STREAM_END) {
6448 return -1;
6451 return 0;
6454 static void ram_decompress_close(RamDecompressState *s)
6456 inflateEnd(&s->zstream);
6459 static void ram_save(QEMUFile *f, void *opaque)
6461 int i;
6462 RamCompressState s1, *s = &s1;
6463 uint8_t buf[10];
6465 qemu_put_be32(f, phys_ram_size);
6466 if (ram_compress_open(s, f) < 0)
6467 return;
6468 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6469 #if 0
6470 if (tight_savevm_enabled) {
6471 int64_t sector_num;
6472 int j;
6474 /* find if the memory block is available on a virtual
6475 block device */
6476 sector_num = -1;
6477 for(j = 0; j < MAX_DISKS; j++) {
6478 if (bs_table[j]) {
6479 sector_num = bdrv_hash_find(bs_table[j],
6480 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6481 if (sector_num >= 0)
6482 break;
6485 if (j == MAX_DISKS)
6486 goto normal_compress;
6487 buf[0] = 1;
6488 buf[1] = j;
6489 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6490 ram_compress_buf(s, buf, 10);
6491 } else
6492 #endif
6494 // normal_compress:
6495 buf[0] = 0;
6496 ram_compress_buf(s, buf, 1);
6497 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6500 ram_compress_close(s);
6503 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6505 RamDecompressState s1, *s = &s1;
6506 uint8_t buf[10];
6507 int i;
6509 if (version_id == 1)
6510 return ram_load_v1(f, opaque);
6511 if (version_id != 2)
6512 return -EINVAL;
6513 if (qemu_get_be32(f) != phys_ram_size)
6514 return -EINVAL;
6515 if (ram_decompress_open(s, f) < 0)
6516 return -EINVAL;
6517 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6518 if (ram_decompress_buf(s, buf, 1) < 0) {
6519 fprintf(stderr, "Error while reading ram block header\n");
6520 goto error;
6522 if (buf[0] == 0) {
6523 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6524 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6525 goto error;
6527 } else
6528 #if 0
6529 if (buf[0] == 1) {
6530 int bs_index;
6531 int64_t sector_num;
6533 ram_decompress_buf(s, buf + 1, 9);
6534 bs_index = buf[1];
6535 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6536 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6537 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6538 goto error;
6540 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6541 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6542 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6543 bs_index, sector_num);
6544 goto error;
6546 } else
6547 #endif
6549 error:
6550 printf("Error block header\n");
6551 return -EINVAL;
6554 ram_decompress_close(s);
6555 return 0;
6558 /***********************************************************/
6559 /* bottom halves (can be seen as timers which expire ASAP) */
6561 struct QEMUBH {
6562 QEMUBHFunc *cb;
6563 void *opaque;
6564 int scheduled;
6565 QEMUBH *next;
6568 static QEMUBH *first_bh = NULL;
6570 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6572 QEMUBH *bh;
6573 bh = qemu_mallocz(sizeof(QEMUBH));
6574 if (!bh)
6575 return NULL;
6576 bh->cb = cb;
6577 bh->opaque = opaque;
6578 return bh;
6581 int qemu_bh_poll(void)
6583 QEMUBH *bh, **pbh;
6584 int ret;
6586 ret = 0;
6587 for(;;) {
6588 pbh = &first_bh;
6589 bh = *pbh;
6590 if (!bh)
6591 break;
6592 ret = 1;
6593 *pbh = bh->next;
6594 bh->scheduled = 0;
6595 bh->cb(bh->opaque);
6597 return ret;
6600 void qemu_bh_schedule(QEMUBH *bh)
6602 CPUState *env = cpu_single_env;
6603 if (bh->scheduled)
6604 return;
6605 bh->scheduled = 1;
6606 bh->next = first_bh;
6607 first_bh = bh;
6609 /* stop the currently executing CPU to execute the BH ASAP */
6610 if (env) {
6611 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6615 void qemu_bh_cancel(QEMUBH *bh)
6617 QEMUBH **pbh;
6618 if (bh->scheduled) {
6619 pbh = &first_bh;
6620 while (*pbh != bh)
6621 pbh = &(*pbh)->next;
6622 *pbh = bh->next;
6623 bh->scheduled = 0;
6627 void qemu_bh_delete(QEMUBH *bh)
6629 qemu_bh_cancel(bh);
6630 qemu_free(bh);
6633 /***********************************************************/
6634 /* machine registration */
6636 QEMUMachine *first_machine = NULL;
6638 int qemu_register_machine(QEMUMachine *m)
6640 QEMUMachine **pm;
6641 pm = &first_machine;
6642 while (*pm != NULL)
6643 pm = &(*pm)->next;
6644 m->next = NULL;
6645 *pm = m;
6646 return 0;
6649 QEMUMachine *find_machine(const char *name)
6651 QEMUMachine *m;
6653 for(m = first_machine; m != NULL; m = m->next) {
6654 if (!strcmp(m->name, name))
6655 return m;
6657 return NULL;
6660 /***********************************************************/
6661 /* main execution loop */
6663 void gui_update(void *opaque)
6665 DisplayState *ds = opaque;
6666 ds->dpy_refresh(ds);
6667 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6670 struct vm_change_state_entry {
6671 VMChangeStateHandler *cb;
6672 void *opaque;
6673 LIST_ENTRY (vm_change_state_entry) entries;
6676 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6678 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6679 void *opaque)
6681 VMChangeStateEntry *e;
6683 e = qemu_mallocz(sizeof (*e));
6684 if (!e)
6685 return NULL;
6687 e->cb = cb;
6688 e->opaque = opaque;
6689 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6690 return e;
6693 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6695 LIST_REMOVE (e, entries);
6696 qemu_free (e);
6699 static void vm_state_notify(int running)
6701 VMChangeStateEntry *e;
6703 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6704 e->cb(e->opaque, running);
6708 /* XXX: support several handlers */
6709 static VMStopHandler *vm_stop_cb;
6710 static void *vm_stop_opaque;
6712 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6714 vm_stop_cb = cb;
6715 vm_stop_opaque = opaque;
6716 return 0;
6719 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6721 vm_stop_cb = NULL;
6724 void vm_start(void)
6726 if (!vm_running) {
6727 cpu_enable_ticks();
6728 vm_running = 1;
6729 vm_state_notify(1);
6730 qemu_rearm_alarm_timer(alarm_timer);
6734 void vm_stop(int reason)
6736 if (vm_running) {
6737 cpu_disable_ticks();
6738 vm_running = 0;
6739 if (reason != 0) {
6740 if (vm_stop_cb) {
6741 vm_stop_cb(vm_stop_opaque, reason);
6744 vm_state_notify(0);
6748 /* reset/shutdown handler */
6750 typedef struct QEMUResetEntry {
6751 QEMUResetHandler *func;
6752 void *opaque;
6753 struct QEMUResetEntry *next;
6754 } QEMUResetEntry;
6756 static QEMUResetEntry *first_reset_entry;
6757 static int reset_requested;
6758 static int shutdown_requested;
6759 static int powerdown_requested;
6761 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6763 QEMUResetEntry **pre, *re;
6765 pre = &first_reset_entry;
6766 while (*pre != NULL)
6767 pre = &(*pre)->next;
6768 re = qemu_mallocz(sizeof(QEMUResetEntry));
6769 re->func = func;
6770 re->opaque = opaque;
6771 re->next = NULL;
6772 *pre = re;
6775 static void qemu_system_reset(void)
6777 QEMUResetEntry *re;
6779 /* reset all devices */
6780 for(re = first_reset_entry; re != NULL; re = re->next) {
6781 re->func(re->opaque);
6785 void qemu_system_reset_request(void)
6787 if (no_reboot) {
6788 shutdown_requested = 1;
6789 } else {
6790 reset_requested = 1;
6792 if (cpu_single_env)
6793 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6796 void qemu_system_shutdown_request(void)
6798 shutdown_requested = 1;
6799 if (cpu_single_env)
6800 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6803 void qemu_system_powerdown_request(void)
6805 powerdown_requested = 1;
6806 if (cpu_single_env)
6807 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6810 void main_loop_wait(int timeout)
6812 IOHandlerRecord *ioh;
6813 fd_set rfds, wfds, xfds;
6814 int ret, nfds;
6815 #ifdef _WIN32
6816 int ret2, i;
6817 #endif
6818 struct timeval tv;
6819 PollingEntry *pe;
6822 /* XXX: need to suppress polling by better using win32 events */
6823 ret = 0;
6824 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6825 ret |= pe->func(pe->opaque);
6827 #ifdef _WIN32
6828 if (ret == 0) {
6829 int err;
6830 WaitObjects *w = &wait_objects;
6832 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6833 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6834 if (w->func[ret - WAIT_OBJECT_0])
6835 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6837 /* Check for additional signaled events */
6838 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6840 /* Check if event is signaled */
6841 ret2 = WaitForSingleObject(w->events[i], 0);
6842 if(ret2 == WAIT_OBJECT_0) {
6843 if (w->func[i])
6844 w->func[i](w->opaque[i]);
6845 } else if (ret2 == WAIT_TIMEOUT) {
6846 } else {
6847 err = GetLastError();
6848 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6851 } else if (ret == WAIT_TIMEOUT) {
6852 } else {
6853 err = GetLastError();
6854 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6857 #endif
6858 /* poll any events */
6859 /* XXX: separate device handlers from system ones */
6860 nfds = -1;
6861 FD_ZERO(&rfds);
6862 FD_ZERO(&wfds);
6863 FD_ZERO(&xfds);
6864 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6865 if (ioh->deleted)
6866 continue;
6867 if (ioh->fd_read &&
6868 (!ioh->fd_read_poll ||
6869 ioh->fd_read_poll(ioh->opaque) != 0)) {
6870 FD_SET(ioh->fd, &rfds);
6871 if (ioh->fd > nfds)
6872 nfds = ioh->fd;
6874 if (ioh->fd_write) {
6875 FD_SET(ioh->fd, &wfds);
6876 if (ioh->fd > nfds)
6877 nfds = ioh->fd;
6881 tv.tv_sec = 0;
6882 #ifdef _WIN32
6883 tv.tv_usec = 0;
6884 #else
6885 tv.tv_usec = timeout * 1000;
6886 #endif
6887 #if defined(CONFIG_SLIRP)
6888 if (slirp_inited) {
6889 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6891 #endif
6892 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6893 if (ret > 0) {
6894 IOHandlerRecord **pioh;
6896 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6897 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6898 ioh->fd_read(ioh->opaque);
6900 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6901 ioh->fd_write(ioh->opaque);
6905 /* remove deleted IO handlers */
6906 pioh = &first_io_handler;
6907 while (*pioh) {
6908 ioh = *pioh;
6909 if (ioh->deleted) {
6910 *pioh = ioh->next;
6911 qemu_free(ioh);
6912 } else
6913 pioh = &ioh->next;
6916 #if defined(CONFIG_SLIRP)
6917 if (slirp_inited) {
6918 if (ret < 0) {
6919 FD_ZERO(&rfds);
6920 FD_ZERO(&wfds);
6921 FD_ZERO(&xfds);
6923 slirp_select_poll(&rfds, &wfds, &xfds);
6925 #endif
6926 qemu_aio_poll();
6928 if (vm_running) {
6929 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6930 qemu_get_clock(vm_clock));
6931 /* run dma transfers, if any */
6932 DMA_run();
6935 /* real time timers */
6936 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6937 qemu_get_clock(rt_clock));
6939 /* Check bottom-halves last in case any of the earlier events triggered
6940 them. */
6941 qemu_bh_poll();
6945 static CPUState *cur_cpu;
6947 int main_loop(void)
6949 int ret, timeout;
6950 #ifdef CONFIG_PROFILER
6951 int64_t ti;
6952 #endif
6953 CPUState *env;
6955 cur_cpu = first_cpu;
6956 for(;;) {
6957 if (vm_running) {
6959 env = cur_cpu;
6960 for(;;) {
6961 /* get next cpu */
6962 env = env->next_cpu;
6963 if (!env)
6964 env = first_cpu;
6965 #ifdef CONFIG_PROFILER
6966 ti = profile_getclock();
6967 #endif
6968 ret = cpu_exec(env);
6969 #ifdef CONFIG_PROFILER
6970 qemu_time += profile_getclock() - ti;
6971 #endif
6972 if (ret == EXCP_HLT) {
6973 /* Give the next CPU a chance to run. */
6974 cur_cpu = env;
6975 continue;
6977 if (ret != EXCP_HALTED)
6978 break;
6979 /* all CPUs are halted ? */
6980 if (env == cur_cpu)
6981 break;
6983 cur_cpu = env;
6985 if (shutdown_requested) {
6986 ret = EXCP_INTERRUPT;
6987 break;
6989 if (reset_requested) {
6990 reset_requested = 0;
6991 qemu_system_reset();
6992 ret = EXCP_INTERRUPT;
6994 if (powerdown_requested) {
6995 powerdown_requested = 0;
6996 qemu_system_powerdown();
6997 ret = EXCP_INTERRUPT;
6999 if (ret == EXCP_DEBUG) {
7000 vm_stop(EXCP_DEBUG);
7002 /* If all cpus are halted then wait until the next IRQ */
7003 /* XXX: use timeout computed from timers */
7004 if (ret == EXCP_HALTED)
7005 timeout = 10;
7006 else
7007 timeout = 0;
7008 } else {
7009 timeout = 10;
7011 #ifdef CONFIG_PROFILER
7012 ti = profile_getclock();
7013 #endif
7014 main_loop_wait(timeout);
7015 #ifdef CONFIG_PROFILER
7016 dev_time += profile_getclock() - ti;
7017 #endif
7019 cpu_disable_ticks();
7020 return ret;
7023 static void help(int exitcode)
7025 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7026 "usage: %s [options] [disk_image]\n"
7027 "\n"
7028 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7029 "\n"
7030 "Standard options:\n"
7031 "-M machine select emulated machine (-M ? for list)\n"
7032 "-cpu cpu select CPU (-cpu ? for list)\n"
7033 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7034 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7035 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7036 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7037 "-mtdblock file use 'file' as on-board Flash memory image\n"
7038 "-sd file use 'file' as SecureDigital card image\n"
7039 "-pflash file use 'file' as a parallel flash image\n"
7040 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7041 "-snapshot write to temporary files instead of disk image files\n"
7042 #ifdef CONFIG_SDL
7043 "-no-frame open SDL window without a frame and window decorations\n"
7044 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7045 "-no-quit disable SDL window close capability\n"
7046 #endif
7047 #ifdef TARGET_I386
7048 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7049 #endif
7050 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7051 "-smp n set the number of CPUs to 'n' [default=1]\n"
7052 "-nographic disable graphical output and redirect serial I/Os to console\n"
7053 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7054 #ifndef _WIN32
7055 "-k language use keyboard layout (for example \"fr\" for French)\n"
7056 #endif
7057 #ifdef HAS_AUDIO
7058 "-audio-help print list of audio drivers and their options\n"
7059 "-soundhw c1,... enable audio support\n"
7060 " and only specified sound cards (comma separated list)\n"
7061 " use -soundhw ? to get the list of supported cards\n"
7062 " use -soundhw all to enable all of them\n"
7063 #endif
7064 "-localtime set the real time clock to local time [default=utc]\n"
7065 "-full-screen start in full screen\n"
7066 #ifdef TARGET_I386
7067 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7068 #endif
7069 "-usb enable the USB driver (will be the default soon)\n"
7070 "-usbdevice name add the host or guest USB device 'name'\n"
7071 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7072 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7073 #endif
7074 "-name string set the name of the guest\n"
7075 "\n"
7076 "Network options:\n"
7077 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7078 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7079 #ifdef CONFIG_SLIRP
7080 "-net user[,vlan=n][,hostname=host]\n"
7081 " connect the user mode network stack to VLAN 'n' and send\n"
7082 " hostname 'host' to DHCP clients\n"
7083 #endif
7084 #ifdef _WIN32
7085 "-net tap[,vlan=n],ifname=name\n"
7086 " connect the host TAP network interface to VLAN 'n'\n"
7087 #else
7088 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7089 " connect the host TAP network interface to VLAN 'n' and use the\n"
7090 " network scripts 'file' (default=%s)\n"
7091 " and 'dfile' (default=%s);\n"
7092 " use '[down]script=no' to disable script execution;\n"
7093 " use 'fd=h' to connect to an already opened TAP interface\n"
7094 #endif
7095 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7096 " connect the vlan 'n' to another VLAN using a socket connection\n"
7097 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7098 " connect the vlan 'n' to multicast maddr and port\n"
7099 "-net none use it alone to have zero network devices; if no -net option\n"
7100 " is provided, the default is '-net nic -net user'\n"
7101 "\n"
7102 #ifdef CONFIG_SLIRP
7103 "-tftp dir allow tftp access to files in dir [-net user]\n"
7104 "-bootp file advertise file in BOOTP replies\n"
7105 #ifndef _WIN32
7106 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7107 #endif
7108 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7109 " redirect TCP or UDP connections from host to guest [-net user]\n"
7110 #endif
7111 "\n"
7112 "Linux boot specific:\n"
7113 "-kernel bzImage use 'bzImage' as kernel image\n"
7114 "-append cmdline use 'cmdline' as kernel command line\n"
7115 "-initrd file use 'file' as initial ram disk\n"
7116 "\n"
7117 "Debug/Expert options:\n"
7118 "-monitor dev redirect the monitor to char device 'dev'\n"
7119 "-serial dev redirect the serial port to char device 'dev'\n"
7120 "-parallel dev redirect the parallel port to char device 'dev'\n"
7121 "-pidfile file Write PID to 'file'\n"
7122 "-S freeze CPU at startup (use 'c' to start execution)\n"
7123 "-s wait gdb connection to port\n"
7124 "-p port set gdb connection port [default=%s]\n"
7125 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7126 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7127 " translation (t=none or lba) (usually qemu can guess them)\n"
7128 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7129 #ifdef USE_KQEMU
7130 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7131 "-no-kqemu disable KQEMU kernel module usage\n"
7132 #endif
7133 #ifdef TARGET_I386
7134 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7135 " (default is CL-GD5446 PCI VGA)\n"
7136 "-no-acpi disable ACPI\n"
7137 #endif
7138 "-no-reboot exit instead of rebooting\n"
7139 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7140 "-vnc display start a VNC server on display\n"
7141 #ifndef _WIN32
7142 "-daemonize daemonize QEMU after initializing\n"
7143 #endif
7144 "-option-rom rom load a file, rom, into the option ROM space\n"
7145 #ifdef TARGET_SPARC
7146 "-prom-env variable=value set OpenBIOS nvram variables\n"
7147 #endif
7148 "-clock force the use of the given methods for timer alarm.\n"
7149 " To see what timers are available use -clock help\n"
7150 "\n"
7151 "During emulation, the following keys are useful:\n"
7152 "ctrl-alt-f toggle full screen\n"
7153 "ctrl-alt-n switch to virtual console 'n'\n"
7154 "ctrl-alt toggle mouse and keyboard grab\n"
7155 "\n"
7156 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7158 "qemu",
7159 DEFAULT_RAM_SIZE,
7160 #ifndef _WIN32
7161 DEFAULT_NETWORK_SCRIPT,
7162 DEFAULT_NETWORK_DOWN_SCRIPT,
7163 #endif
7164 DEFAULT_GDBSTUB_PORT,
7165 "/tmp/qemu.log");
7166 exit(exitcode);
7169 #define HAS_ARG 0x0001
7171 enum {
7172 QEMU_OPTION_h,
7174 QEMU_OPTION_M,
7175 QEMU_OPTION_cpu,
7176 QEMU_OPTION_fda,
7177 QEMU_OPTION_fdb,
7178 QEMU_OPTION_hda,
7179 QEMU_OPTION_hdb,
7180 QEMU_OPTION_hdc,
7181 QEMU_OPTION_hdd,
7182 QEMU_OPTION_cdrom,
7183 QEMU_OPTION_mtdblock,
7184 QEMU_OPTION_sd,
7185 QEMU_OPTION_pflash,
7186 QEMU_OPTION_boot,
7187 QEMU_OPTION_snapshot,
7188 #ifdef TARGET_I386
7189 QEMU_OPTION_no_fd_bootchk,
7190 #endif
7191 QEMU_OPTION_m,
7192 QEMU_OPTION_nographic,
7193 QEMU_OPTION_portrait,
7194 #ifdef HAS_AUDIO
7195 QEMU_OPTION_audio_help,
7196 QEMU_OPTION_soundhw,
7197 #endif
7199 QEMU_OPTION_net,
7200 QEMU_OPTION_tftp,
7201 QEMU_OPTION_bootp,
7202 QEMU_OPTION_smb,
7203 QEMU_OPTION_redir,
7205 QEMU_OPTION_kernel,
7206 QEMU_OPTION_append,
7207 QEMU_OPTION_initrd,
7209 QEMU_OPTION_S,
7210 QEMU_OPTION_s,
7211 QEMU_OPTION_p,
7212 QEMU_OPTION_d,
7213 QEMU_OPTION_hdachs,
7214 QEMU_OPTION_L,
7215 QEMU_OPTION_bios,
7216 QEMU_OPTION_no_code_copy,
7217 QEMU_OPTION_k,
7218 QEMU_OPTION_localtime,
7219 QEMU_OPTION_cirrusvga,
7220 QEMU_OPTION_vmsvga,
7221 QEMU_OPTION_g,
7222 QEMU_OPTION_std_vga,
7223 QEMU_OPTION_echr,
7224 QEMU_OPTION_monitor,
7225 QEMU_OPTION_serial,
7226 QEMU_OPTION_parallel,
7227 QEMU_OPTION_loadvm,
7228 QEMU_OPTION_full_screen,
7229 QEMU_OPTION_no_frame,
7230 QEMU_OPTION_alt_grab,
7231 QEMU_OPTION_no_quit,
7232 QEMU_OPTION_pidfile,
7233 QEMU_OPTION_no_kqemu,
7234 QEMU_OPTION_kernel_kqemu,
7235 QEMU_OPTION_win2k_hack,
7236 QEMU_OPTION_usb,
7237 QEMU_OPTION_usbdevice,
7238 QEMU_OPTION_smp,
7239 QEMU_OPTION_vnc,
7240 QEMU_OPTION_no_acpi,
7241 QEMU_OPTION_no_reboot,
7242 QEMU_OPTION_show_cursor,
7243 QEMU_OPTION_daemonize,
7244 QEMU_OPTION_option_rom,
7245 QEMU_OPTION_semihosting,
7246 QEMU_OPTION_name,
7247 QEMU_OPTION_prom_env,
7248 QEMU_OPTION_old_param,
7249 QEMU_OPTION_clock,
7250 QEMU_OPTION_startdate,
7253 typedef struct QEMUOption {
7254 const char *name;
7255 int flags;
7256 int index;
7257 } QEMUOption;
7259 const QEMUOption qemu_options[] = {
7260 { "h", 0, QEMU_OPTION_h },
7261 { "help", 0, QEMU_OPTION_h },
7263 { "M", HAS_ARG, QEMU_OPTION_M },
7264 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7265 { "fda", HAS_ARG, QEMU_OPTION_fda },
7266 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7267 { "hda", HAS_ARG, QEMU_OPTION_hda },
7268 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7269 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7270 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7271 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7272 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7273 { "sd", HAS_ARG, QEMU_OPTION_sd },
7274 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7275 { "boot", HAS_ARG, QEMU_OPTION_boot },
7276 { "snapshot", 0, QEMU_OPTION_snapshot },
7277 #ifdef TARGET_I386
7278 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7279 #endif
7280 { "m", HAS_ARG, QEMU_OPTION_m },
7281 { "nographic", 0, QEMU_OPTION_nographic },
7282 { "portrait", 0, QEMU_OPTION_portrait },
7283 { "k", HAS_ARG, QEMU_OPTION_k },
7284 #ifdef HAS_AUDIO
7285 { "audio-help", 0, QEMU_OPTION_audio_help },
7286 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7287 #endif
7289 { "net", HAS_ARG, QEMU_OPTION_net},
7290 #ifdef CONFIG_SLIRP
7291 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7292 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7293 #ifndef _WIN32
7294 { "smb", HAS_ARG, QEMU_OPTION_smb },
7295 #endif
7296 { "redir", HAS_ARG, QEMU_OPTION_redir },
7297 #endif
7299 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7300 { "append", HAS_ARG, QEMU_OPTION_append },
7301 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7303 { "S", 0, QEMU_OPTION_S },
7304 { "s", 0, QEMU_OPTION_s },
7305 { "p", HAS_ARG, QEMU_OPTION_p },
7306 { "d", HAS_ARG, QEMU_OPTION_d },
7307 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7308 { "L", HAS_ARG, QEMU_OPTION_L },
7309 { "bios", HAS_ARG, QEMU_OPTION_bios },
7310 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7311 #ifdef USE_KQEMU
7312 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7313 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7314 #endif
7315 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7316 { "g", 1, QEMU_OPTION_g },
7317 #endif
7318 { "localtime", 0, QEMU_OPTION_localtime },
7319 { "std-vga", 0, QEMU_OPTION_std_vga },
7320 { "echr", HAS_ARG, QEMU_OPTION_echr },
7321 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7322 { "serial", HAS_ARG, QEMU_OPTION_serial },
7323 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7324 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7325 { "full-screen", 0, QEMU_OPTION_full_screen },
7326 #ifdef CONFIG_SDL
7327 { "no-frame", 0, QEMU_OPTION_no_frame },
7328 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7329 { "no-quit", 0, QEMU_OPTION_no_quit },
7330 #endif
7331 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7332 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7333 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7334 { "smp", HAS_ARG, QEMU_OPTION_smp },
7335 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7337 /* temporary options */
7338 { "usb", 0, QEMU_OPTION_usb },
7339 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7340 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7341 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7342 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7343 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7344 { "daemonize", 0, QEMU_OPTION_daemonize },
7345 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7346 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7347 { "semihosting", 0, QEMU_OPTION_semihosting },
7348 #endif
7349 { "name", HAS_ARG, QEMU_OPTION_name },
7350 #if defined(TARGET_SPARC)
7351 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7352 #endif
7353 #if defined(TARGET_ARM)
7354 { "old-param", 0, QEMU_OPTION_old_param },
7355 #endif
7356 { "clock", HAS_ARG, QEMU_OPTION_clock },
7357 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7358 { NULL },
7361 /* password input */
7363 int qemu_key_check(BlockDriverState *bs, const char *name)
7365 char password[256];
7366 int i;
7368 if (!bdrv_is_encrypted(bs))
7369 return 0;
7371 term_printf("%s is encrypted.\n", name);
7372 for(i = 0; i < 3; i++) {
7373 monitor_readline("Password: ", 1, password, sizeof(password));
7374 if (bdrv_set_key(bs, password) == 0)
7375 return 0;
7376 term_printf("invalid password\n");
7378 return -EPERM;
7381 static BlockDriverState *get_bdrv(int index)
7383 BlockDriverState *bs;
7385 if (index < 4) {
7386 bs = bs_table[index];
7387 } else if (index < 6) {
7388 bs = fd_table[index - 4];
7389 } else {
7390 bs = NULL;
7392 return bs;
7395 static void read_passwords(void)
7397 BlockDriverState *bs;
7398 int i;
7400 for(i = 0; i < 6; i++) {
7401 bs = get_bdrv(i);
7402 if (bs)
7403 qemu_key_check(bs, bdrv_get_device_name(bs));
7407 /* XXX: currently we cannot use simultaneously different CPUs */
7408 void register_machines(void)
7410 #if defined(TARGET_I386)
7411 qemu_register_machine(&pc_machine);
7412 qemu_register_machine(&isapc_machine);
7413 #elif defined(TARGET_PPC)
7414 qemu_register_machine(&heathrow_machine);
7415 qemu_register_machine(&core99_machine);
7416 qemu_register_machine(&prep_machine);
7417 qemu_register_machine(&ref405ep_machine);
7418 qemu_register_machine(&taihu_machine);
7419 #elif defined(TARGET_MIPS)
7420 qemu_register_machine(&mips_machine);
7421 qemu_register_machine(&mips_malta_machine);
7422 qemu_register_machine(&mips_pica61_machine);
7423 qemu_register_machine(&mips_mipssim_machine);
7424 #elif defined(TARGET_SPARC)
7425 #ifdef TARGET_SPARC64
7426 qemu_register_machine(&sun4u_machine);
7427 #else
7428 qemu_register_machine(&ss5_machine);
7429 qemu_register_machine(&ss10_machine);
7430 #endif
7431 #elif defined(TARGET_ARM)
7432 qemu_register_machine(&integratorcp_machine);
7433 qemu_register_machine(&versatilepb_machine);
7434 qemu_register_machine(&versatileab_machine);
7435 qemu_register_machine(&realview_machine);
7436 qemu_register_machine(&akitapda_machine);
7437 qemu_register_machine(&spitzpda_machine);
7438 qemu_register_machine(&borzoipda_machine);
7439 qemu_register_machine(&terrierpda_machine);
7440 qemu_register_machine(&palmte_machine);
7441 qemu_register_machine(&lm3s811evb_machine);
7442 qemu_register_machine(&lm3s6965evb_machine);
7443 #elif defined(TARGET_SH4)
7444 qemu_register_machine(&shix_machine);
7445 qemu_register_machine(&r2d_machine);
7446 #elif defined(TARGET_ALPHA)
7447 /* XXX: TODO */
7448 #elif defined(TARGET_M68K)
7449 qemu_register_machine(&mcf5208evb_machine);
7450 qemu_register_machine(&an5206_machine);
7451 qemu_register_machine(&dummy_m68k_machine);
7452 #elif defined(TARGET_CRIS)
7453 qemu_register_machine(&bareetraxfs_machine);
7454 #else
7455 #error unsupported CPU
7456 #endif
7459 #ifdef HAS_AUDIO
7460 struct soundhw soundhw[] = {
7461 #ifdef HAS_AUDIO_CHOICE
7462 #ifdef TARGET_I386
7464 "pcspk",
7465 "PC speaker",
7468 { .init_isa = pcspk_audio_init }
7470 #endif
7472 "sb16",
7473 "Creative Sound Blaster 16",
7476 { .init_isa = SB16_init }
7479 #ifdef CONFIG_ADLIB
7481 "adlib",
7482 #ifdef HAS_YMF262
7483 "Yamaha YMF262 (OPL3)",
7484 #else
7485 "Yamaha YM3812 (OPL2)",
7486 #endif
7489 { .init_isa = Adlib_init }
7491 #endif
7493 #ifdef CONFIG_GUS
7495 "gus",
7496 "Gravis Ultrasound GF1",
7499 { .init_isa = GUS_init }
7501 #endif
7504 "es1370",
7505 "ENSONIQ AudioPCI ES1370",
7508 { .init_pci = es1370_init }
7510 #endif
7512 { NULL, NULL, 0, 0, { NULL } }
7515 static void select_soundhw (const char *optarg)
7517 struct soundhw *c;
7519 if (*optarg == '?') {
7520 show_valid_cards:
7522 printf ("Valid sound card names (comma separated):\n");
7523 for (c = soundhw; c->name; ++c) {
7524 printf ("%-11s %s\n", c->name, c->descr);
7526 printf ("\n-soundhw all will enable all of the above\n");
7527 exit (*optarg != '?');
7529 else {
7530 size_t l;
7531 const char *p;
7532 char *e;
7533 int bad_card = 0;
7535 if (!strcmp (optarg, "all")) {
7536 for (c = soundhw; c->name; ++c) {
7537 c->enabled = 1;
7539 return;
7542 p = optarg;
7543 while (*p) {
7544 e = strchr (p, ',');
7545 l = !e ? strlen (p) : (size_t) (e - p);
7547 for (c = soundhw; c->name; ++c) {
7548 if (!strncmp (c->name, p, l)) {
7549 c->enabled = 1;
7550 break;
7554 if (!c->name) {
7555 if (l > 80) {
7556 fprintf (stderr,
7557 "Unknown sound card name (too big to show)\n");
7559 else {
7560 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7561 (int) l, p);
7563 bad_card = 1;
7565 p += l + (e != NULL);
7568 if (bad_card)
7569 goto show_valid_cards;
7572 #endif
7574 #ifdef _WIN32
7575 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7577 exit(STATUS_CONTROL_C_EXIT);
7578 return TRUE;
7580 #endif
7582 #define MAX_NET_CLIENTS 32
7584 int main(int argc, char **argv)
7586 #ifdef CONFIG_GDBSTUB
7587 int use_gdbstub;
7588 const char *gdbstub_port;
7589 #endif
7590 int i, cdrom_index, pflash_index;
7591 int snapshot, linux_boot;
7592 const char *initrd_filename;
7593 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7594 const char *pflash_filename[MAX_PFLASH];
7595 const char *sd_filename;
7596 const char *mtd_filename;
7597 const char *kernel_filename, *kernel_cmdline;
7598 DisplayState *ds = &display_state;
7599 int cyls, heads, secs, translation;
7600 char net_clients[MAX_NET_CLIENTS][256];
7601 int nb_net_clients;
7602 int optind;
7603 const char *r, *optarg;
7604 CharDriverState *monitor_hd;
7605 char monitor_device[128];
7606 char serial_devices[MAX_SERIAL_PORTS][128];
7607 int serial_device_index;
7608 char parallel_devices[MAX_PARALLEL_PORTS][128];
7609 int parallel_device_index;
7610 const char *loadvm = NULL;
7611 QEMUMachine *machine;
7612 const char *cpu_model;
7613 char usb_devices[MAX_USB_CMDLINE][128];
7614 int usb_devices_index;
7615 int fds[2];
7616 const char *pid_file = NULL;
7617 VLANState *vlan;
7619 LIST_INIT (&vm_change_state_head);
7620 #ifndef _WIN32
7622 struct sigaction act;
7623 sigfillset(&act.sa_mask);
7624 act.sa_flags = 0;
7625 act.sa_handler = SIG_IGN;
7626 sigaction(SIGPIPE, &act, NULL);
7628 #else
7629 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7630 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7631 QEMU to run on a single CPU */
7633 HANDLE h;
7634 DWORD mask, smask;
7635 int i;
7636 h = GetCurrentProcess();
7637 if (GetProcessAffinityMask(h, &mask, &smask)) {
7638 for(i = 0; i < 32; i++) {
7639 if (mask & (1 << i))
7640 break;
7642 if (i != 32) {
7643 mask = 1 << i;
7644 SetProcessAffinityMask(h, mask);
7648 #endif
7650 register_machines();
7651 machine = first_machine;
7652 cpu_model = NULL;
7653 initrd_filename = NULL;
7654 for(i = 0; i < MAX_FD; i++)
7655 fd_filename[i] = NULL;
7656 for(i = 0; i < MAX_DISKS; i++)
7657 hd_filename[i] = NULL;
7658 for(i = 0; i < MAX_PFLASH; i++)
7659 pflash_filename[i] = NULL;
7660 pflash_index = 0;
7661 sd_filename = NULL;
7662 mtd_filename = NULL;
7663 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7664 vga_ram_size = VGA_RAM_SIZE;
7665 #ifdef CONFIG_GDBSTUB
7666 use_gdbstub = 0;
7667 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7668 #endif
7669 snapshot = 0;
7670 nographic = 0;
7671 kernel_filename = NULL;
7672 kernel_cmdline = "";
7673 #ifdef TARGET_PPC
7674 cdrom_index = 1;
7675 #else
7676 cdrom_index = 2;
7677 #endif
7678 cyls = heads = secs = 0;
7679 translation = BIOS_ATA_TRANSLATION_AUTO;
7680 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7682 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7683 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7684 serial_devices[i][0] = '\0';
7685 serial_device_index = 0;
7687 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7688 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7689 parallel_devices[i][0] = '\0';
7690 parallel_device_index = 0;
7692 usb_devices_index = 0;
7694 nb_net_clients = 0;
7696 nb_nics = 0;
7697 /* default mac address of the first network interface */
7699 optind = 1;
7700 for(;;) {
7701 if (optind >= argc)
7702 break;
7703 r = argv[optind];
7704 if (r[0] != '-') {
7705 hd_filename[0] = argv[optind++];
7706 } else {
7707 const QEMUOption *popt;
7709 optind++;
7710 /* Treat --foo the same as -foo. */
7711 if (r[1] == '-')
7712 r++;
7713 popt = qemu_options;
7714 for(;;) {
7715 if (!popt->name) {
7716 fprintf(stderr, "%s: invalid option -- '%s'\n",
7717 argv[0], r);
7718 exit(1);
7720 if (!strcmp(popt->name, r + 1))
7721 break;
7722 popt++;
7724 if (popt->flags & HAS_ARG) {
7725 if (optind >= argc) {
7726 fprintf(stderr, "%s: option '%s' requires an argument\n",
7727 argv[0], r);
7728 exit(1);
7730 optarg = argv[optind++];
7731 } else {
7732 optarg = NULL;
7735 switch(popt->index) {
7736 case QEMU_OPTION_M:
7737 machine = find_machine(optarg);
7738 if (!machine) {
7739 QEMUMachine *m;
7740 printf("Supported machines are:\n");
7741 for(m = first_machine; m != NULL; m = m->next) {
7742 printf("%-10s %s%s\n",
7743 m->name, m->desc,
7744 m == first_machine ? " (default)" : "");
7746 exit(*optarg != '?');
7748 break;
7749 case QEMU_OPTION_cpu:
7750 /* hw initialization will check this */
7751 if (*optarg == '?') {
7752 /* XXX: implement xxx_cpu_list for targets that still miss it */
7753 #if defined(cpu_list)
7754 cpu_list(stdout, &fprintf);
7755 #endif
7756 exit(0);
7757 } else {
7758 cpu_model = optarg;
7760 break;
7761 case QEMU_OPTION_initrd:
7762 initrd_filename = optarg;
7763 break;
7764 case QEMU_OPTION_hda:
7765 case QEMU_OPTION_hdb:
7766 case QEMU_OPTION_hdc:
7767 case QEMU_OPTION_hdd:
7769 int hd_index;
7770 hd_index = popt->index - QEMU_OPTION_hda;
7771 hd_filename[hd_index] = optarg;
7772 if (hd_index == cdrom_index)
7773 cdrom_index = -1;
7775 break;
7776 case QEMU_OPTION_mtdblock:
7777 mtd_filename = optarg;
7778 break;
7779 case QEMU_OPTION_sd:
7780 sd_filename = optarg;
7781 break;
7782 case QEMU_OPTION_pflash:
7783 if (pflash_index >= MAX_PFLASH) {
7784 fprintf(stderr, "qemu: too many parallel flash images\n");
7785 exit(1);
7787 pflash_filename[pflash_index++] = optarg;
7788 break;
7789 case QEMU_OPTION_snapshot:
7790 snapshot = 1;
7791 break;
7792 case QEMU_OPTION_hdachs:
7794 const char *p;
7795 p = optarg;
7796 cyls = strtol(p, (char **)&p, 0);
7797 if (cyls < 1 || cyls > 16383)
7798 goto chs_fail;
7799 if (*p != ',')
7800 goto chs_fail;
7801 p++;
7802 heads = strtol(p, (char **)&p, 0);
7803 if (heads < 1 || heads > 16)
7804 goto chs_fail;
7805 if (*p != ',')
7806 goto chs_fail;
7807 p++;
7808 secs = strtol(p, (char **)&p, 0);
7809 if (secs < 1 || secs > 63)
7810 goto chs_fail;
7811 if (*p == ',') {
7812 p++;
7813 if (!strcmp(p, "none"))
7814 translation = BIOS_ATA_TRANSLATION_NONE;
7815 else if (!strcmp(p, "lba"))
7816 translation = BIOS_ATA_TRANSLATION_LBA;
7817 else if (!strcmp(p, "auto"))
7818 translation = BIOS_ATA_TRANSLATION_AUTO;
7819 else
7820 goto chs_fail;
7821 } else if (*p != '\0') {
7822 chs_fail:
7823 fprintf(stderr, "qemu: invalid physical CHS format\n");
7824 exit(1);
7827 break;
7828 case QEMU_OPTION_nographic:
7829 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7830 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7831 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7832 nographic = 1;
7833 break;
7834 case QEMU_OPTION_portrait:
7835 graphic_rotate = 1;
7836 break;
7837 case QEMU_OPTION_kernel:
7838 kernel_filename = optarg;
7839 break;
7840 case QEMU_OPTION_append:
7841 kernel_cmdline = optarg;
7842 break;
7843 case QEMU_OPTION_cdrom:
7844 if (cdrom_index >= 0) {
7845 hd_filename[cdrom_index] = optarg;
7847 break;
7848 case QEMU_OPTION_boot:
7849 if (strlen(optarg) > MAX_BOOT_DEVICES) {
7850 fprintf(stderr, "qemu: too many boot devices\n");
7851 exit(1);
7853 strncpy(boot_device, optarg, MAX_BOOT_DEVICES);
7854 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7855 #define BOOTCHARS "acdn"
7856 #else
7857 #define BOOTCHARS "acd"
7858 #endif
7859 if (strlen(boot_device) != strspn(boot_device, BOOTCHARS)) {
7860 fprintf(stderr, "qemu: invalid boot device "
7861 "sequence '%s'\n", boot_device);
7862 exit(1);
7864 break;
7865 case QEMU_OPTION_fda:
7866 fd_filename[0] = optarg;
7867 break;
7868 case QEMU_OPTION_fdb:
7869 fd_filename[1] = optarg;
7870 break;
7871 #ifdef TARGET_I386
7872 case QEMU_OPTION_no_fd_bootchk:
7873 fd_bootchk = 0;
7874 break;
7875 #endif
7876 case QEMU_OPTION_no_code_copy:
7877 code_copy_enabled = 0;
7878 break;
7879 case QEMU_OPTION_net:
7880 if (nb_net_clients >= MAX_NET_CLIENTS) {
7881 fprintf(stderr, "qemu: too many network clients\n");
7882 exit(1);
7884 pstrcpy(net_clients[nb_net_clients],
7885 sizeof(net_clients[0]),
7886 optarg);
7887 nb_net_clients++;
7888 break;
7889 #ifdef CONFIG_SLIRP
7890 case QEMU_OPTION_tftp:
7891 tftp_prefix = optarg;
7892 break;
7893 case QEMU_OPTION_bootp:
7894 bootp_filename = optarg;
7895 break;
7896 #ifndef _WIN32
7897 case QEMU_OPTION_smb:
7898 net_slirp_smb(optarg);
7899 break;
7900 #endif
7901 case QEMU_OPTION_redir:
7902 net_slirp_redir(optarg);
7903 break;
7904 #endif
7905 #ifdef HAS_AUDIO
7906 case QEMU_OPTION_audio_help:
7907 AUD_help ();
7908 exit (0);
7909 break;
7910 case QEMU_OPTION_soundhw:
7911 select_soundhw (optarg);
7912 break;
7913 #endif
7914 case QEMU_OPTION_h:
7915 help(0);
7916 break;
7917 case QEMU_OPTION_m:
7918 ram_size = atoi(optarg) * 1024 * 1024;
7919 if (ram_size <= 0)
7920 help(1);
7921 if (ram_size > PHYS_RAM_MAX_SIZE) {
7922 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7923 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7924 exit(1);
7926 break;
7927 case QEMU_OPTION_d:
7929 int mask;
7930 CPULogItem *item;
7932 mask = cpu_str_to_log_mask(optarg);
7933 if (!mask) {
7934 printf("Log items (comma separated):\n");
7935 for(item = cpu_log_items; item->mask != 0; item++) {
7936 printf("%-10s %s\n", item->name, item->help);
7938 exit(1);
7940 cpu_set_log(mask);
7942 break;
7943 #ifdef CONFIG_GDBSTUB
7944 case QEMU_OPTION_s:
7945 use_gdbstub = 1;
7946 break;
7947 case QEMU_OPTION_p:
7948 gdbstub_port = optarg;
7949 break;
7950 #endif
7951 case QEMU_OPTION_L:
7952 bios_dir = optarg;
7953 break;
7954 case QEMU_OPTION_bios:
7955 bios_name = optarg;
7956 break;
7957 case QEMU_OPTION_S:
7958 autostart = 0;
7959 break;
7960 case QEMU_OPTION_k:
7961 keyboard_layout = optarg;
7962 break;
7963 case QEMU_OPTION_localtime:
7964 rtc_utc = 0;
7965 break;
7966 case QEMU_OPTION_cirrusvga:
7967 cirrus_vga_enabled = 1;
7968 vmsvga_enabled = 0;
7969 break;
7970 case QEMU_OPTION_vmsvga:
7971 cirrus_vga_enabled = 0;
7972 vmsvga_enabled = 1;
7973 break;
7974 case QEMU_OPTION_std_vga:
7975 cirrus_vga_enabled = 0;
7976 vmsvga_enabled = 0;
7977 break;
7978 case QEMU_OPTION_g:
7980 const char *p;
7981 int w, h, depth;
7982 p = optarg;
7983 w = strtol(p, (char **)&p, 10);
7984 if (w <= 0) {
7985 graphic_error:
7986 fprintf(stderr, "qemu: invalid resolution or depth\n");
7987 exit(1);
7989 if (*p != 'x')
7990 goto graphic_error;
7991 p++;
7992 h = strtol(p, (char **)&p, 10);
7993 if (h <= 0)
7994 goto graphic_error;
7995 if (*p == 'x') {
7996 p++;
7997 depth = strtol(p, (char **)&p, 10);
7998 if (depth != 8 && depth != 15 && depth != 16 &&
7999 depth != 24 && depth != 32)
8000 goto graphic_error;
8001 } else if (*p == '\0') {
8002 depth = graphic_depth;
8003 } else {
8004 goto graphic_error;
8007 graphic_width = w;
8008 graphic_height = h;
8009 graphic_depth = depth;
8011 break;
8012 case QEMU_OPTION_echr:
8014 char *r;
8015 term_escape_char = strtol(optarg, &r, 0);
8016 if (r == optarg)
8017 printf("Bad argument to echr\n");
8018 break;
8020 case QEMU_OPTION_monitor:
8021 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8022 break;
8023 case QEMU_OPTION_serial:
8024 if (serial_device_index >= MAX_SERIAL_PORTS) {
8025 fprintf(stderr, "qemu: too many serial ports\n");
8026 exit(1);
8028 pstrcpy(serial_devices[serial_device_index],
8029 sizeof(serial_devices[0]), optarg);
8030 serial_device_index++;
8031 break;
8032 case QEMU_OPTION_parallel:
8033 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8034 fprintf(stderr, "qemu: too many parallel ports\n");
8035 exit(1);
8037 pstrcpy(parallel_devices[parallel_device_index],
8038 sizeof(parallel_devices[0]), optarg);
8039 parallel_device_index++;
8040 break;
8041 case QEMU_OPTION_loadvm:
8042 loadvm = optarg;
8043 break;
8044 case QEMU_OPTION_full_screen:
8045 full_screen = 1;
8046 break;
8047 #ifdef CONFIG_SDL
8048 case QEMU_OPTION_no_frame:
8049 no_frame = 1;
8050 break;
8051 case QEMU_OPTION_alt_grab:
8052 alt_grab = 1;
8053 break;
8054 case QEMU_OPTION_no_quit:
8055 no_quit = 1;
8056 break;
8057 #endif
8058 case QEMU_OPTION_pidfile:
8059 pid_file = optarg;
8060 break;
8061 #ifdef TARGET_I386
8062 case QEMU_OPTION_win2k_hack:
8063 win2k_install_hack = 1;
8064 break;
8065 #endif
8066 #ifdef USE_KQEMU
8067 case QEMU_OPTION_no_kqemu:
8068 kqemu_allowed = 0;
8069 break;
8070 case QEMU_OPTION_kernel_kqemu:
8071 kqemu_allowed = 2;
8072 break;
8073 #endif
8074 case QEMU_OPTION_usb:
8075 usb_enabled = 1;
8076 break;
8077 case QEMU_OPTION_usbdevice:
8078 usb_enabled = 1;
8079 if (usb_devices_index >= MAX_USB_CMDLINE) {
8080 fprintf(stderr, "Too many USB devices\n");
8081 exit(1);
8083 pstrcpy(usb_devices[usb_devices_index],
8084 sizeof(usb_devices[usb_devices_index]),
8085 optarg);
8086 usb_devices_index++;
8087 break;
8088 case QEMU_OPTION_smp:
8089 smp_cpus = atoi(optarg);
8090 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8091 fprintf(stderr, "Invalid number of CPUs\n");
8092 exit(1);
8094 break;
8095 case QEMU_OPTION_vnc:
8096 vnc_display = optarg;
8097 break;
8098 case QEMU_OPTION_no_acpi:
8099 acpi_enabled = 0;
8100 break;
8101 case QEMU_OPTION_no_reboot:
8102 no_reboot = 1;
8103 break;
8104 case QEMU_OPTION_show_cursor:
8105 cursor_hide = 0;
8106 break;
8107 case QEMU_OPTION_daemonize:
8108 daemonize = 1;
8109 break;
8110 case QEMU_OPTION_option_rom:
8111 if (nb_option_roms >= MAX_OPTION_ROMS) {
8112 fprintf(stderr, "Too many option ROMs\n");
8113 exit(1);
8115 option_rom[nb_option_roms] = optarg;
8116 nb_option_roms++;
8117 break;
8118 case QEMU_OPTION_semihosting:
8119 semihosting_enabled = 1;
8120 break;
8121 case QEMU_OPTION_name:
8122 qemu_name = optarg;
8123 break;
8124 #ifdef TARGET_SPARC
8125 case QEMU_OPTION_prom_env:
8126 if (nb_prom_envs >= MAX_PROM_ENVS) {
8127 fprintf(stderr, "Too many prom variables\n");
8128 exit(1);
8130 prom_envs[nb_prom_envs] = optarg;
8131 nb_prom_envs++;
8132 break;
8133 #endif
8134 #ifdef TARGET_ARM
8135 case QEMU_OPTION_old_param:
8136 old_param = 1;
8137 #endif
8138 case QEMU_OPTION_clock:
8139 configure_alarms(optarg);
8140 break;
8141 case QEMU_OPTION_startdate:
8143 struct tm tm;
8144 if (!strcmp(optarg, "now")) {
8145 rtc_start_date = -1;
8146 } else {
8147 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8148 &tm.tm_year,
8149 &tm.tm_mon,
8150 &tm.tm_mday,
8151 &tm.tm_hour,
8152 &tm.tm_min,
8153 &tm.tm_sec) == 6) {
8154 /* OK */
8155 } else if (sscanf(optarg, "%d-%d-%d",
8156 &tm.tm_year,
8157 &tm.tm_mon,
8158 &tm.tm_mday) == 3) {
8159 tm.tm_hour = 0;
8160 tm.tm_min = 0;
8161 tm.tm_sec = 0;
8162 } else {
8163 goto date_fail;
8165 tm.tm_year -= 1900;
8166 tm.tm_mon--;
8167 rtc_start_date = mktimegm(&tm);
8168 if (rtc_start_date == -1) {
8169 date_fail:
8170 fprintf(stderr, "Invalid date format. Valid format are:\n"
8171 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8172 exit(1);
8176 break;
8181 #ifndef _WIN32
8182 if (daemonize && !nographic && vnc_display == NULL) {
8183 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8184 daemonize = 0;
8187 if (daemonize) {
8188 pid_t pid;
8190 if (pipe(fds) == -1)
8191 exit(1);
8193 pid = fork();
8194 if (pid > 0) {
8195 uint8_t status;
8196 ssize_t len;
8198 close(fds[1]);
8200 again:
8201 len = read(fds[0], &status, 1);
8202 if (len == -1 && (errno == EINTR))
8203 goto again;
8205 if (len != 1)
8206 exit(1);
8207 else if (status == 1) {
8208 fprintf(stderr, "Could not acquire pidfile\n");
8209 exit(1);
8210 } else
8211 exit(0);
8212 } else if (pid < 0)
8213 exit(1);
8215 setsid();
8217 pid = fork();
8218 if (pid > 0)
8219 exit(0);
8220 else if (pid < 0)
8221 exit(1);
8223 umask(027);
8224 chdir("/");
8226 signal(SIGTSTP, SIG_IGN);
8227 signal(SIGTTOU, SIG_IGN);
8228 signal(SIGTTIN, SIG_IGN);
8230 #endif
8232 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8233 if (daemonize) {
8234 uint8_t status = 1;
8235 write(fds[1], &status, 1);
8236 } else
8237 fprintf(stderr, "Could not acquire pid file\n");
8238 exit(1);
8241 #ifdef USE_KQEMU
8242 if (smp_cpus > 1)
8243 kqemu_allowed = 0;
8244 #endif
8245 linux_boot = (kernel_filename != NULL);
8247 if (!linux_boot &&
8248 (!strchr(boot_device, 'n')) &&
8249 hd_filename[0] == '\0' &&
8250 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8251 fd_filename[0] == '\0')
8252 help(1);
8254 /* boot to floppy or the default cd if no hard disk defined yet */
8255 if (!boot_device[0]) {
8256 if (hd_filename[0] != '\0')
8257 boot_device[0] = 'c';
8258 else if (fd_filename[0] != '\0')
8259 boot_device[0] = 'a';
8260 else
8261 boot_device[0] = 'd';
8262 boot_device[1] = 0;
8264 setvbuf(stdout, NULL, _IOLBF, 0);
8266 init_timers();
8267 init_timer_alarm();
8268 qemu_aio_init();
8270 #ifdef _WIN32
8271 socket_init();
8272 #endif
8274 /* init network clients */
8275 if (nb_net_clients == 0) {
8276 /* if no clients, we use a default config */
8277 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8278 "nic");
8279 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8280 "user");
8281 nb_net_clients = 2;
8284 for(i = 0;i < nb_net_clients; i++) {
8285 if (net_client_init(net_clients[i]) < 0)
8286 exit(1);
8288 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8289 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8290 continue;
8291 if (vlan->nb_guest_devs == 0) {
8292 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8293 exit(1);
8295 if (vlan->nb_host_devs == 0)
8296 fprintf(stderr,
8297 "Warning: vlan %d is not connected to host network\n",
8298 vlan->id);
8301 #ifdef TARGET_I386
8302 if (strchr(boot_device, 'n')) {
8303 for (i = 0; i < nb_nics; i++) {
8304 const char *model = nd_table[i].model;
8305 char buf[1024];
8306 if (model == NULL)
8307 model = "ne2k_pci";
8308 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8309 if (get_image_size(buf) > 0) {
8310 option_rom[nb_option_roms] = strdup(buf);
8311 nb_option_roms++;
8312 break;
8315 if (i == nb_nics) {
8316 fprintf(stderr, "No valid PXE rom found for network device\n");
8317 exit(1);
8320 #endif
8322 /* init the memory */
8323 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8325 phys_ram_base = qemu_vmalloc(phys_ram_size);
8326 if (!phys_ram_base) {
8327 fprintf(stderr, "Could not allocate physical memory\n");
8328 exit(1);
8331 /* we always create the cdrom drive, even if no disk is there */
8332 bdrv_init();
8333 if (cdrom_index >= 0) {
8334 bs_table[cdrom_index] = bdrv_new("cdrom");
8335 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8338 /* open the virtual block devices */
8339 for(i = 0; i < MAX_DISKS; i++) {
8340 if (hd_filename[i]) {
8341 if (!bs_table[i]) {
8342 char buf[64];
8343 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8344 bs_table[i] = bdrv_new(buf);
8346 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8347 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8348 hd_filename[i]);
8349 exit(1);
8351 if (i == 0 && cyls != 0) {
8352 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8353 bdrv_set_translation_hint(bs_table[i], translation);
8358 /* we always create at least one floppy disk */
8359 fd_table[0] = bdrv_new("fda");
8360 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8362 for(i = 0; i < MAX_FD; i++) {
8363 if (fd_filename[i]) {
8364 if (!fd_table[i]) {
8365 char buf[64];
8366 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8367 fd_table[i] = bdrv_new(buf);
8368 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8370 if (fd_filename[i][0] != '\0') {
8371 if (bdrv_open(fd_table[i], fd_filename[i],
8372 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8373 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8374 fd_filename[i]);
8375 exit(1);
8381 /* Open the virtual parallel flash block devices */
8382 for(i = 0; i < MAX_PFLASH; i++) {
8383 if (pflash_filename[i]) {
8384 if (!pflash_table[i]) {
8385 char buf[64];
8386 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8387 pflash_table[i] = bdrv_new(buf);
8389 if (bdrv_open(pflash_table[i], pflash_filename[i],
8390 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8391 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8392 pflash_filename[i]);
8393 exit(1);
8398 sd_bdrv = bdrv_new ("sd");
8399 /* FIXME: This isn't really a floppy, but it's a reasonable
8400 approximation. */
8401 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8402 if (sd_filename) {
8403 if (bdrv_open(sd_bdrv, sd_filename,
8404 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8405 fprintf(stderr, "qemu: could not open SD card image %s\n",
8406 sd_filename);
8407 } else
8408 qemu_key_check(sd_bdrv, sd_filename);
8411 if (mtd_filename) {
8412 mtd_bdrv = bdrv_new ("mtd");
8413 if (bdrv_open(mtd_bdrv, mtd_filename,
8414 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8415 qemu_key_check(mtd_bdrv, mtd_filename)) {
8416 fprintf(stderr, "qemu: could not open Flash image %s\n",
8417 mtd_filename);
8418 bdrv_delete(mtd_bdrv);
8419 mtd_bdrv = 0;
8423 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8424 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8426 init_ioports();
8428 /* terminal init */
8429 memset(&display_state, 0, sizeof(display_state));
8430 if (nographic) {
8431 /* nearly nothing to do */
8432 dumb_display_init(ds);
8433 } else if (vnc_display != NULL) {
8434 vnc_display_init(ds);
8435 if (vnc_display_open(ds, vnc_display) < 0)
8436 exit(1);
8437 } else {
8438 #if defined(CONFIG_SDL)
8439 sdl_display_init(ds, full_screen, no_frame);
8440 #elif defined(CONFIG_COCOA)
8441 cocoa_display_init(ds, full_screen);
8442 #endif
8445 /* Maintain compatibility with multiple stdio monitors */
8446 if (!strcmp(monitor_device,"stdio")) {
8447 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8448 if (!strcmp(serial_devices[i],"mon:stdio")) {
8449 monitor_device[0] = '\0';
8450 break;
8451 } else if (!strcmp(serial_devices[i],"stdio")) {
8452 monitor_device[0] = '\0';
8453 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8454 break;
8458 if (monitor_device[0] != '\0') {
8459 monitor_hd = qemu_chr_open(monitor_device);
8460 if (!monitor_hd) {
8461 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8462 exit(1);
8464 monitor_init(monitor_hd, !nographic);
8467 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8468 const char *devname = serial_devices[i];
8469 if (devname[0] != '\0' && strcmp(devname, "none")) {
8470 serial_hds[i] = qemu_chr_open(devname);
8471 if (!serial_hds[i]) {
8472 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8473 devname);
8474 exit(1);
8476 if (strstart(devname, "vc", 0))
8477 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8481 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8482 const char *devname = parallel_devices[i];
8483 if (devname[0] != '\0' && strcmp(devname, "none")) {
8484 parallel_hds[i] = qemu_chr_open(devname);
8485 if (!parallel_hds[i]) {
8486 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8487 devname);
8488 exit(1);
8490 if (strstart(devname, "vc", 0))
8491 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8495 machine->init(ram_size, vga_ram_size, boot_device,
8496 ds, fd_filename, snapshot,
8497 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8499 /* init USB devices */
8500 if (usb_enabled) {
8501 for(i = 0; i < usb_devices_index; i++) {
8502 if (usb_device_add(usb_devices[i]) < 0) {
8503 fprintf(stderr, "Warning: could not add USB device %s\n",
8504 usb_devices[i]);
8509 if (display_state.dpy_refresh) {
8510 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8511 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8514 #ifdef CONFIG_GDBSTUB
8515 if (use_gdbstub) {
8516 /* XXX: use standard host:port notation and modify options
8517 accordingly. */
8518 if (gdbserver_start(gdbstub_port) < 0) {
8519 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8520 gdbstub_port);
8521 exit(1);
8524 #endif
8526 if (loadvm)
8527 do_loadvm(loadvm);
8530 /* XXX: simplify init */
8531 read_passwords();
8532 if (autostart) {
8533 vm_start();
8537 if (daemonize) {
8538 uint8_t status = 0;
8539 ssize_t len;
8540 int fd;
8542 again1:
8543 len = write(fds[1], &status, 1);
8544 if (len == -1 && (errno == EINTR))
8545 goto again1;
8547 if (len != 1)
8548 exit(1);
8550 TFR(fd = open("/dev/null", O_RDWR));
8551 if (fd == -1)
8552 exit(1);
8554 dup2(fd, 0);
8555 dup2(fd, 1);
8556 dup2(fd, 2);
8558 close(fd);
8561 main_loop();
8562 quit_timers();
8564 #if !defined(_WIN32)
8565 /* close network clients */
8566 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8567 VLANClientState *vc;
8569 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8570 if (vc->fd_read == tap_receive) {
8571 char ifname[64];
8572 TAPState *s = vc->opaque;
8574 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8575 s->down_script[0])
8576 launch_script(s->down_script, ifname, s->fd);
8580 #endif
8581 return 0;