Enable all alignment checks
[qemu/qemu_0_9_1_stable.git] / vl.c
blob6d8fe35428a378be1886e0e5df145fe9203af793
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #include <sys/select.h>
46 #include <arpa/inet.h>
47 #ifdef _BSD
48 #include <sys/stat.h>
49 #ifndef __APPLE__
50 #include <libutil.h>
51 #endif
52 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
53 #include <freebsd/stdlib.h>
54 #else
55 #ifndef __sun__
56 #include <linux/if.h>
57 #include <linux/if_tun.h>
58 #include <pty.h>
59 #include <malloc.h>
60 #include <linux/rtc.h>
62 /* For the benefit of older linux systems which don't supply it,
63 we use a local copy of hpet.h. */
64 /* #include <linux/hpet.h> */
65 #include "hpet.h"
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #else
70 #include <sys/stat.h>
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #include <net/if.h>
81 #include <syslog.h>
82 #include <stropts.h>
83 #endif
84 #endif
85 #else
86 #include <winsock2.h>
87 int inet_aton(const char *cp, struct in_addr *ia);
88 #endif
90 #if defined(CONFIG_SLIRP)
91 #include "libslirp.h"
92 #endif
94 #ifdef _WIN32
95 #include <malloc.h>
96 #include <sys/timeb.h>
97 #include <windows.h>
98 #define getopt_long_only getopt_long
99 #define memalign(align, size) malloc(size)
100 #endif
102 #include "qemu_socket.h"
104 #ifdef CONFIG_SDL
105 #ifdef __APPLE__
106 #include <SDL/SDL.h>
107 #endif
108 #endif /* CONFIG_SDL */
110 #ifdef CONFIG_COCOA
111 #undef main
112 #define main qemu_main
113 #endif /* CONFIG_COCOA */
115 #include "disas.h"
117 #include "exec-all.h"
119 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
120 #ifdef __sun__
121 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
122 #else
123 #define SMBD_COMMAND "/usr/sbin/smbd"
124 #endif
126 //#define DEBUG_UNUSED_IOPORT
127 //#define DEBUG_IOPORT
129 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
131 #ifdef TARGET_PPC
132 #define DEFAULT_RAM_SIZE 144
133 #else
134 #define DEFAULT_RAM_SIZE 128
135 #endif
136 /* in ms */
137 #define GUI_REFRESH_INTERVAL 30
139 /* Max number of USB devices that can be specified on the commandline. */
140 #define MAX_USB_CMDLINE 8
142 /* XXX: use a two level table to limit memory usage */
143 #define MAX_IOPORTS 65536
145 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
146 const char *bios_name = NULL;
147 char phys_ram_file[1024];
148 void *ioport_opaque[MAX_IOPORTS];
149 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
150 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
151 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
152 to store the VM snapshots */
153 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
154 BlockDriverState *pflash_table[MAX_PFLASH];
155 BlockDriverState *sd_bdrv;
156 BlockDriverState *mtd_bdrv;
157 /* point to the block driver where the snapshots are managed */
158 BlockDriverState *bs_snapshots;
159 int vga_ram_size;
160 static DisplayState display_state;
161 int nographic;
162 const char* keyboard_layout = NULL;
163 int64_t ticks_per_sec;
164 int boot_device = 'c';
165 int ram_size;
166 int pit_min_timer_count = 0;
167 int nb_nics;
168 NICInfo nd_table[MAX_NICS];
169 int vm_running;
170 int rtc_utc = 1;
171 int cirrus_vga_enabled = 1;
172 int vmsvga_enabled = 0;
173 #ifdef TARGET_SPARC
174 int graphic_width = 1024;
175 int graphic_height = 768;
176 int graphic_depth = 8;
177 #else
178 int graphic_width = 800;
179 int graphic_height = 600;
180 int graphic_depth = 15;
181 #endif
182 int full_screen = 0;
183 int no_frame = 0;
184 int no_quit = 0;
185 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
186 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
187 #ifdef TARGET_I386
188 int win2k_install_hack = 0;
189 #endif
190 int usb_enabled = 0;
191 static VLANState *first_vlan;
192 int smp_cpus = 1;
193 const char *vnc_display;
194 #if defined(TARGET_SPARC)
195 #define MAX_CPUS 16
196 #elif defined(TARGET_I386)
197 #define MAX_CPUS 255
198 #else
199 #define MAX_CPUS 1
200 #endif
201 int acpi_enabled = 1;
202 int fd_bootchk = 1;
203 int no_reboot = 0;
204 int cursor_hide = 1;
205 int graphic_rotate = 0;
206 int daemonize = 0;
207 const char *option_rom[MAX_OPTION_ROMS];
208 int nb_option_roms;
209 int semihosting_enabled = 0;
210 int autostart = 1;
211 #ifdef TARGET_ARM
212 int old_param = 0;
213 #endif
214 const char *qemu_name;
215 int alt_grab = 0;
216 #ifdef TARGET_SPARC
217 unsigned int nb_prom_envs = 0;
218 const char *prom_envs[MAX_PROM_ENVS];
219 #endif
221 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
223 /***********************************************************/
224 /* x86 ISA bus support */
226 target_phys_addr_t isa_mem_base = 0;
227 PicState2 *isa_pic;
229 uint32_t default_ioport_readb(void *opaque, uint32_t address)
231 #ifdef DEBUG_UNUSED_IOPORT
232 fprintf(stderr, "unused inb: port=0x%04x\n", address);
233 #endif
234 return 0xff;
237 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
239 #ifdef DEBUG_UNUSED_IOPORT
240 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
241 #endif
244 /* default is to make two byte accesses */
245 uint32_t default_ioport_readw(void *opaque, uint32_t address)
247 uint32_t data;
248 data = ioport_read_table[0][address](ioport_opaque[address], address);
249 address = (address + 1) & (MAX_IOPORTS - 1);
250 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
251 return data;
254 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
256 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
257 address = (address + 1) & (MAX_IOPORTS - 1);
258 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
261 uint32_t default_ioport_readl(void *opaque, uint32_t address)
263 #ifdef DEBUG_UNUSED_IOPORT
264 fprintf(stderr, "unused inl: port=0x%04x\n", address);
265 #endif
266 return 0xffffffff;
269 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
271 #ifdef DEBUG_UNUSED_IOPORT
272 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
273 #endif
276 void init_ioports(void)
278 int i;
280 for(i = 0; i < MAX_IOPORTS; i++) {
281 ioport_read_table[0][i] = default_ioport_readb;
282 ioport_write_table[0][i] = default_ioport_writeb;
283 ioport_read_table[1][i] = default_ioport_readw;
284 ioport_write_table[1][i] = default_ioport_writew;
285 ioport_read_table[2][i] = default_ioport_readl;
286 ioport_write_table[2][i] = default_ioport_writel;
290 /* size is the word size in byte */
291 int register_ioport_read(int start, int length, int size,
292 IOPortReadFunc *func, void *opaque)
294 int i, bsize;
296 if (size == 1) {
297 bsize = 0;
298 } else if (size == 2) {
299 bsize = 1;
300 } else if (size == 4) {
301 bsize = 2;
302 } else {
303 hw_error("register_ioport_read: invalid size");
304 return -1;
306 for(i = start; i < start + length; i += size) {
307 ioport_read_table[bsize][i] = func;
308 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
309 hw_error("register_ioport_read: invalid opaque");
310 ioport_opaque[i] = opaque;
312 return 0;
315 /* size is the word size in byte */
316 int register_ioport_write(int start, int length, int size,
317 IOPortWriteFunc *func, void *opaque)
319 int i, bsize;
321 if (size == 1) {
322 bsize = 0;
323 } else if (size == 2) {
324 bsize = 1;
325 } else if (size == 4) {
326 bsize = 2;
327 } else {
328 hw_error("register_ioport_write: invalid size");
329 return -1;
331 for(i = start; i < start + length; i += size) {
332 ioport_write_table[bsize][i] = func;
333 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
334 hw_error("register_ioport_write: invalid opaque");
335 ioport_opaque[i] = opaque;
337 return 0;
340 void isa_unassign_ioport(int start, int length)
342 int i;
344 for(i = start; i < start + length; i++) {
345 ioport_read_table[0][i] = default_ioport_readb;
346 ioport_read_table[1][i] = default_ioport_readw;
347 ioport_read_table[2][i] = default_ioport_readl;
349 ioport_write_table[0][i] = default_ioport_writeb;
350 ioport_write_table[1][i] = default_ioport_writew;
351 ioport_write_table[2][i] = default_ioport_writel;
355 /***********************************************************/
357 void cpu_outb(CPUState *env, int addr, int val)
359 #ifdef DEBUG_IOPORT
360 if (loglevel & CPU_LOG_IOPORT)
361 fprintf(logfile, "outb: %04x %02x\n", addr, val);
362 #endif
363 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
364 #ifdef USE_KQEMU
365 if (env)
366 env->last_io_time = cpu_get_time_fast();
367 #endif
370 void cpu_outw(CPUState *env, int addr, int val)
372 #ifdef DEBUG_IOPORT
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outw: %04x %04x\n", addr, val);
375 #endif
376 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
377 #ifdef USE_KQEMU
378 if (env)
379 env->last_io_time = cpu_get_time_fast();
380 #endif
383 void cpu_outl(CPUState *env, int addr, int val)
385 #ifdef DEBUG_IOPORT
386 if (loglevel & CPU_LOG_IOPORT)
387 fprintf(logfile, "outl: %04x %08x\n", addr, val);
388 #endif
389 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390 #ifdef USE_KQEMU
391 if (env)
392 env->last_io_time = cpu_get_time_fast();
393 #endif
396 int cpu_inb(CPUState *env, int addr)
398 int val;
399 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
400 #ifdef DEBUG_IOPORT
401 if (loglevel & CPU_LOG_IOPORT)
402 fprintf(logfile, "inb : %04x %02x\n", addr, val);
403 #endif
404 #ifdef USE_KQEMU
405 if (env)
406 env->last_io_time = cpu_get_time_fast();
407 #endif
408 return val;
411 int cpu_inw(CPUState *env, int addr)
413 int val;
414 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
415 #ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "inw : %04x %04x\n", addr, val);
418 #endif
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
423 return val;
426 int cpu_inl(CPUState *env, int addr)
428 int val;
429 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
430 #ifdef DEBUG_IOPORT
431 if (loglevel & CPU_LOG_IOPORT)
432 fprintf(logfile, "inl : %04x %08x\n", addr, val);
433 #endif
434 #ifdef USE_KQEMU
435 if (env)
436 env->last_io_time = cpu_get_time_fast();
437 #endif
438 return val;
441 /***********************************************************/
442 void hw_error(const char *fmt, ...)
444 va_list ap;
445 CPUState *env;
447 va_start(ap, fmt);
448 fprintf(stderr, "qemu: hardware error: ");
449 vfprintf(stderr, fmt, ap);
450 fprintf(stderr, "\n");
451 for(env = first_cpu; env != NULL; env = env->next_cpu) {
452 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
453 #ifdef TARGET_I386
454 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
455 #else
456 cpu_dump_state(env, stderr, fprintf, 0);
457 #endif
459 va_end(ap);
460 abort();
463 /***********************************************************/
464 /* keyboard/mouse */
466 static QEMUPutKBDEvent *qemu_put_kbd_event;
467 static void *qemu_put_kbd_event_opaque;
468 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
469 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
471 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
473 qemu_put_kbd_event_opaque = opaque;
474 qemu_put_kbd_event = func;
477 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
478 void *opaque, int absolute,
479 const char *name)
481 QEMUPutMouseEntry *s, *cursor;
483 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
484 if (!s)
485 return NULL;
487 s->qemu_put_mouse_event = func;
488 s->qemu_put_mouse_event_opaque = opaque;
489 s->qemu_put_mouse_event_absolute = absolute;
490 s->qemu_put_mouse_event_name = qemu_strdup(name);
491 s->next = NULL;
493 if (!qemu_put_mouse_event_head) {
494 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
495 return s;
498 cursor = qemu_put_mouse_event_head;
499 while (cursor->next != NULL)
500 cursor = cursor->next;
502 cursor->next = s;
503 qemu_put_mouse_event_current = s;
505 return s;
508 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
510 QEMUPutMouseEntry *prev = NULL, *cursor;
512 if (!qemu_put_mouse_event_head || entry == NULL)
513 return;
515 cursor = qemu_put_mouse_event_head;
516 while (cursor != NULL && cursor != entry) {
517 prev = cursor;
518 cursor = cursor->next;
521 if (cursor == NULL) // does not exist or list empty
522 return;
523 else if (prev == NULL) { // entry is head
524 qemu_put_mouse_event_head = cursor->next;
525 if (qemu_put_mouse_event_current == entry)
526 qemu_put_mouse_event_current = cursor->next;
527 qemu_free(entry->qemu_put_mouse_event_name);
528 qemu_free(entry);
529 return;
532 prev->next = entry->next;
534 if (qemu_put_mouse_event_current == entry)
535 qemu_put_mouse_event_current = prev;
537 qemu_free(entry->qemu_put_mouse_event_name);
538 qemu_free(entry);
541 void kbd_put_keycode(int keycode)
543 if (qemu_put_kbd_event) {
544 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
548 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
550 QEMUPutMouseEvent *mouse_event;
551 void *mouse_event_opaque;
552 int width;
554 if (!qemu_put_mouse_event_current) {
555 return;
558 mouse_event =
559 qemu_put_mouse_event_current->qemu_put_mouse_event;
560 mouse_event_opaque =
561 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
563 if (mouse_event) {
564 if (graphic_rotate) {
565 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
566 width = 0x7fff;
567 else
568 width = graphic_width;
569 mouse_event(mouse_event_opaque,
570 width - dy, dx, dz, buttons_state);
571 } else
572 mouse_event(mouse_event_opaque,
573 dx, dy, dz, buttons_state);
577 int kbd_mouse_is_absolute(void)
579 if (!qemu_put_mouse_event_current)
580 return 0;
582 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
585 void do_info_mice(void)
587 QEMUPutMouseEntry *cursor;
588 int index = 0;
590 if (!qemu_put_mouse_event_head) {
591 term_printf("No mouse devices connected\n");
592 return;
595 term_printf("Mouse devices available:\n");
596 cursor = qemu_put_mouse_event_head;
597 while (cursor != NULL) {
598 term_printf("%c Mouse #%d: %s\n",
599 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
600 index, cursor->qemu_put_mouse_event_name);
601 index++;
602 cursor = cursor->next;
606 void do_mouse_set(int index)
608 QEMUPutMouseEntry *cursor;
609 int i = 0;
611 if (!qemu_put_mouse_event_head) {
612 term_printf("No mouse devices connected\n");
613 return;
616 cursor = qemu_put_mouse_event_head;
617 while (cursor != NULL && index != i) {
618 i++;
619 cursor = cursor->next;
622 if (cursor != NULL)
623 qemu_put_mouse_event_current = cursor;
624 else
625 term_printf("Mouse at given index not found\n");
628 /* compute with 96 bit intermediate result: (a*b)/c */
629 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
631 union {
632 uint64_t ll;
633 struct {
634 #ifdef WORDS_BIGENDIAN
635 uint32_t high, low;
636 #else
637 uint32_t low, high;
638 #endif
639 } l;
640 } u, res;
641 uint64_t rl, rh;
643 u.ll = a;
644 rl = (uint64_t)u.l.low * (uint64_t)b;
645 rh = (uint64_t)u.l.high * (uint64_t)b;
646 rh += (rl >> 32);
647 res.l.high = rh / c;
648 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
649 return res.ll;
652 /***********************************************************/
653 /* real time host monotonic timer */
655 #define QEMU_TIMER_BASE 1000000000LL
657 #ifdef WIN32
659 static int64_t clock_freq;
661 static void init_get_clock(void)
663 LARGE_INTEGER freq;
664 int ret;
665 ret = QueryPerformanceFrequency(&freq);
666 if (ret == 0) {
667 fprintf(stderr, "Could not calibrate ticks\n");
668 exit(1);
670 clock_freq = freq.QuadPart;
673 static int64_t get_clock(void)
675 LARGE_INTEGER ti;
676 QueryPerformanceCounter(&ti);
677 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
680 #else
682 static int use_rt_clock;
684 static void init_get_clock(void)
686 use_rt_clock = 0;
687 #if defined(__linux__)
689 struct timespec ts;
690 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
691 use_rt_clock = 1;
694 #endif
697 static int64_t get_clock(void)
699 #if defined(__linux__)
700 if (use_rt_clock) {
701 struct timespec ts;
702 clock_gettime(CLOCK_MONOTONIC, &ts);
703 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
704 } else
705 #endif
707 /* XXX: using gettimeofday leads to problems if the date
708 changes, so it should be avoided. */
709 struct timeval tv;
710 gettimeofday(&tv, NULL);
711 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
715 #endif
717 /***********************************************************/
718 /* guest cycle counter */
720 static int64_t cpu_ticks_prev;
721 static int64_t cpu_ticks_offset;
722 static int64_t cpu_clock_offset;
723 static int cpu_ticks_enabled;
725 /* return the host CPU cycle counter and handle stop/restart */
726 int64_t cpu_get_ticks(void)
728 if (!cpu_ticks_enabled) {
729 return cpu_ticks_offset;
730 } else {
731 int64_t ticks;
732 ticks = cpu_get_real_ticks();
733 if (cpu_ticks_prev > ticks) {
734 /* Note: non increasing ticks may happen if the host uses
735 software suspend */
736 cpu_ticks_offset += cpu_ticks_prev - ticks;
738 cpu_ticks_prev = ticks;
739 return ticks + cpu_ticks_offset;
743 /* return the host CPU monotonic timer and handle stop/restart */
744 static int64_t cpu_get_clock(void)
746 int64_t ti;
747 if (!cpu_ticks_enabled) {
748 return cpu_clock_offset;
749 } else {
750 ti = get_clock();
751 return ti + cpu_clock_offset;
755 /* enable cpu_get_ticks() */
756 void cpu_enable_ticks(void)
758 if (!cpu_ticks_enabled) {
759 cpu_ticks_offset -= cpu_get_real_ticks();
760 cpu_clock_offset -= get_clock();
761 cpu_ticks_enabled = 1;
765 /* disable cpu_get_ticks() : the clock is stopped. You must not call
766 cpu_get_ticks() after that. */
767 void cpu_disable_ticks(void)
769 if (cpu_ticks_enabled) {
770 cpu_ticks_offset = cpu_get_ticks();
771 cpu_clock_offset = cpu_get_clock();
772 cpu_ticks_enabled = 0;
776 /***********************************************************/
777 /* timers */
779 #define QEMU_TIMER_REALTIME 0
780 #define QEMU_TIMER_VIRTUAL 1
782 struct QEMUClock {
783 int type;
784 /* XXX: add frequency */
787 struct QEMUTimer {
788 QEMUClock *clock;
789 int64_t expire_time;
790 QEMUTimerCB *cb;
791 void *opaque;
792 struct QEMUTimer *next;
795 struct qemu_alarm_timer {
796 char const *name;
797 unsigned int flags;
799 int (*start)(struct qemu_alarm_timer *t);
800 void (*stop)(struct qemu_alarm_timer *t);
801 void (*rearm)(struct qemu_alarm_timer *t);
802 void *priv;
805 #define ALARM_FLAG_DYNTICKS 0x1
807 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
809 return t->flags & ALARM_FLAG_DYNTICKS;
812 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
814 if (!alarm_has_dynticks(t))
815 return;
817 t->rearm(t);
820 /* TODO: MIN_TIMER_REARM_US should be optimized */
821 #define MIN_TIMER_REARM_US 250
823 static struct qemu_alarm_timer *alarm_timer;
825 #ifdef _WIN32
827 struct qemu_alarm_win32 {
828 MMRESULT timerId;
829 HANDLE host_alarm;
830 unsigned int period;
831 } alarm_win32_data = {0, NULL, -1};
833 static int win32_start_timer(struct qemu_alarm_timer *t);
834 static void win32_stop_timer(struct qemu_alarm_timer *t);
835 static void win32_rearm_timer(struct qemu_alarm_timer *t);
837 #else
839 static int unix_start_timer(struct qemu_alarm_timer *t);
840 static void unix_stop_timer(struct qemu_alarm_timer *t);
842 #ifdef __linux__
844 static int dynticks_start_timer(struct qemu_alarm_timer *t);
845 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
846 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
848 static int hpet_start_timer(struct qemu_alarm_timer *t);
849 static void hpet_stop_timer(struct qemu_alarm_timer *t);
851 static int rtc_start_timer(struct qemu_alarm_timer *t);
852 static void rtc_stop_timer(struct qemu_alarm_timer *t);
854 #endif /* __linux__ */
856 #endif /* _WIN32 */
858 static struct qemu_alarm_timer alarm_timers[] = {
859 #ifndef _WIN32
860 #ifdef __linux__
861 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
862 dynticks_stop_timer, dynticks_rearm_timer, NULL},
863 /* HPET - if available - is preferred */
864 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
865 /* ...otherwise try RTC */
866 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
867 #endif
868 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
869 #else
870 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
871 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
872 {"win32", 0, win32_start_timer,
873 win32_stop_timer, NULL, &alarm_win32_data},
874 #endif
875 {NULL, }
878 static void show_available_alarms()
880 int i;
882 printf("Available alarm timers, in order of precedence:\n");
883 for (i = 0; alarm_timers[i].name; i++)
884 printf("%s\n", alarm_timers[i].name);
887 static void configure_alarms(char const *opt)
889 int i;
890 int cur = 0;
891 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
892 char *arg;
893 char *name;
895 if (!strcmp(opt, "help")) {
896 show_available_alarms();
897 exit(0);
900 arg = strdup(opt);
902 /* Reorder the array */
903 name = strtok(arg, ",");
904 while (name) {
905 struct qemu_alarm_timer tmp;
907 for (i = 0; i < count && alarm_timers[i].name; i++) {
908 if (!strcmp(alarm_timers[i].name, name))
909 break;
912 if (i == count) {
913 fprintf(stderr, "Unknown clock %s\n", name);
914 goto next;
917 if (i < cur)
918 /* Ignore */
919 goto next;
921 /* Swap */
922 tmp = alarm_timers[i];
923 alarm_timers[i] = alarm_timers[cur];
924 alarm_timers[cur] = tmp;
926 cur++;
927 next:
928 name = strtok(NULL, ",");
931 free(arg);
933 if (cur) {
934 /* Disable remaining timers */
935 for (i = cur; i < count; i++)
936 alarm_timers[i].name = NULL;
939 /* debug */
940 show_available_alarms();
943 QEMUClock *rt_clock;
944 QEMUClock *vm_clock;
946 static QEMUTimer *active_timers[2];
948 QEMUClock *qemu_new_clock(int type)
950 QEMUClock *clock;
951 clock = qemu_mallocz(sizeof(QEMUClock));
952 if (!clock)
953 return NULL;
954 clock->type = type;
955 return clock;
958 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
960 QEMUTimer *ts;
962 ts = qemu_mallocz(sizeof(QEMUTimer));
963 ts->clock = clock;
964 ts->cb = cb;
965 ts->opaque = opaque;
966 return ts;
969 void qemu_free_timer(QEMUTimer *ts)
971 qemu_free(ts);
974 /* stop a timer, but do not dealloc it */
975 void qemu_del_timer(QEMUTimer *ts)
977 QEMUTimer **pt, *t;
979 /* NOTE: this code must be signal safe because
980 qemu_timer_expired() can be called from a signal. */
981 pt = &active_timers[ts->clock->type];
982 for(;;) {
983 t = *pt;
984 if (!t)
985 break;
986 if (t == ts) {
987 *pt = t->next;
988 break;
990 pt = &t->next;
994 /* modify the current timer so that it will be fired when current_time
995 >= expire_time. The corresponding callback will be called. */
996 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
998 QEMUTimer **pt, *t;
1000 qemu_del_timer(ts);
1002 /* add the timer in the sorted list */
1003 /* NOTE: this code must be signal safe because
1004 qemu_timer_expired() can be called from a signal. */
1005 pt = &active_timers[ts->clock->type];
1006 for(;;) {
1007 t = *pt;
1008 if (!t)
1009 break;
1010 if (t->expire_time > expire_time)
1011 break;
1012 pt = &t->next;
1014 ts->expire_time = expire_time;
1015 ts->next = *pt;
1016 *pt = ts;
1019 int qemu_timer_pending(QEMUTimer *ts)
1021 QEMUTimer *t;
1022 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1023 if (t == ts)
1024 return 1;
1026 return 0;
1029 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1031 if (!timer_head)
1032 return 0;
1033 return (timer_head->expire_time <= current_time);
1036 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1038 QEMUTimer *ts;
1040 for(;;) {
1041 ts = *ptimer_head;
1042 if (!ts || ts->expire_time > current_time)
1043 break;
1044 /* remove timer from the list before calling the callback */
1045 *ptimer_head = ts->next;
1046 ts->next = NULL;
1048 /* run the callback (the timer list can be modified) */
1049 ts->cb(ts->opaque);
1051 qemu_rearm_alarm_timer(alarm_timer);
1054 int64_t qemu_get_clock(QEMUClock *clock)
1056 switch(clock->type) {
1057 case QEMU_TIMER_REALTIME:
1058 return get_clock() / 1000000;
1059 default:
1060 case QEMU_TIMER_VIRTUAL:
1061 return cpu_get_clock();
1065 static void init_timers(void)
1067 init_get_clock();
1068 ticks_per_sec = QEMU_TIMER_BASE;
1069 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1070 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1073 /* save a timer */
1074 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1076 uint64_t expire_time;
1078 if (qemu_timer_pending(ts)) {
1079 expire_time = ts->expire_time;
1080 } else {
1081 expire_time = -1;
1083 qemu_put_be64(f, expire_time);
1086 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1088 uint64_t expire_time;
1090 expire_time = qemu_get_be64(f);
1091 if (expire_time != -1) {
1092 qemu_mod_timer(ts, expire_time);
1093 } else {
1094 qemu_del_timer(ts);
1098 static void timer_save(QEMUFile *f, void *opaque)
1100 if (cpu_ticks_enabled) {
1101 hw_error("cannot save state if virtual timers are running");
1103 qemu_put_be64s(f, &cpu_ticks_offset);
1104 qemu_put_be64s(f, &ticks_per_sec);
1105 qemu_put_be64s(f, &cpu_clock_offset);
1108 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1110 if (version_id != 1 && version_id != 2)
1111 return -EINVAL;
1112 if (cpu_ticks_enabled) {
1113 return -EINVAL;
1115 qemu_get_be64s(f, &cpu_ticks_offset);
1116 qemu_get_be64s(f, &ticks_per_sec);
1117 if (version_id == 2) {
1118 qemu_get_be64s(f, &cpu_clock_offset);
1120 return 0;
1123 #ifdef _WIN32
1124 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1125 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1126 #else
1127 static void host_alarm_handler(int host_signum)
1128 #endif
1130 #if 0
1131 #define DISP_FREQ 1000
1133 static int64_t delta_min = INT64_MAX;
1134 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1135 static int count;
1136 ti = qemu_get_clock(vm_clock);
1137 if (last_clock != 0) {
1138 delta = ti - last_clock;
1139 if (delta < delta_min)
1140 delta_min = delta;
1141 if (delta > delta_max)
1142 delta_max = delta;
1143 delta_cum += delta;
1144 if (++count == DISP_FREQ) {
1145 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1146 muldiv64(delta_min, 1000000, ticks_per_sec),
1147 muldiv64(delta_max, 1000000, ticks_per_sec),
1148 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1149 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1150 count = 0;
1151 delta_min = INT64_MAX;
1152 delta_max = 0;
1153 delta_cum = 0;
1156 last_clock = ti;
1158 #endif
1159 if (alarm_has_dynticks(alarm_timer) ||
1160 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1161 qemu_get_clock(vm_clock)) ||
1162 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1163 qemu_get_clock(rt_clock))) {
1164 #ifdef _WIN32
1165 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1166 SetEvent(data->host_alarm);
1167 #endif
1168 CPUState *env = cpu_single_env;
1169 if (env) {
1170 /* stop the currently executing cpu because a timer occured */
1171 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1172 #ifdef USE_KQEMU
1173 if (env->kqemu_enabled) {
1174 kqemu_cpu_interrupt(env);
1176 #endif
1181 static uint64_t qemu_next_deadline(void)
1183 int64_t nearest_delta_us = INT64_MAX;
1184 int64_t vmdelta_us;
1186 if (active_timers[QEMU_TIMER_REALTIME])
1187 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1188 qemu_get_clock(rt_clock))*1000;
1190 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1191 /* round up */
1192 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1193 qemu_get_clock(vm_clock)+999)/1000;
1194 if (vmdelta_us < nearest_delta_us)
1195 nearest_delta_us = vmdelta_us;
1198 /* Avoid arming the timer to negative, zero, or too low values */
1199 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1200 nearest_delta_us = MIN_TIMER_REARM_US;
1202 return nearest_delta_us;
1205 #ifndef _WIN32
1207 #if defined(__linux__)
1209 #define RTC_FREQ 1024
1211 static void enable_sigio_timer(int fd)
1213 struct sigaction act;
1215 /* timer signal */
1216 sigfillset(&act.sa_mask);
1217 act.sa_flags = 0;
1218 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1219 act.sa_flags |= SA_ONSTACK;
1220 #endif
1221 act.sa_handler = host_alarm_handler;
1223 sigaction(SIGIO, &act, NULL);
1224 fcntl(fd, F_SETFL, O_ASYNC);
1225 fcntl(fd, F_SETOWN, getpid());
1228 static int hpet_start_timer(struct qemu_alarm_timer *t)
1230 struct hpet_info info;
1231 int r, fd;
1233 fd = open("/dev/hpet", O_RDONLY);
1234 if (fd < 0)
1235 return -1;
1237 /* Set frequency */
1238 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1239 if (r < 0) {
1240 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1241 "error, but for better emulation accuracy type:\n"
1242 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1243 goto fail;
1246 /* Check capabilities */
1247 r = ioctl(fd, HPET_INFO, &info);
1248 if (r < 0)
1249 goto fail;
1251 /* Enable periodic mode */
1252 r = ioctl(fd, HPET_EPI, 0);
1253 if (info.hi_flags && (r < 0))
1254 goto fail;
1256 /* Enable interrupt */
1257 r = ioctl(fd, HPET_IE_ON, 0);
1258 if (r < 0)
1259 goto fail;
1261 enable_sigio_timer(fd);
1262 t->priv = (void *)(long)fd;
1264 return 0;
1265 fail:
1266 close(fd);
1267 return -1;
1270 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1272 int fd = (long)t->priv;
1274 close(fd);
1277 static int rtc_start_timer(struct qemu_alarm_timer *t)
1279 int rtc_fd;
1281 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1282 if (rtc_fd < 0)
1283 return -1;
1284 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1285 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1286 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1287 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1288 goto fail;
1290 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1291 fail:
1292 close(rtc_fd);
1293 return -1;
1296 enable_sigio_timer(rtc_fd);
1298 t->priv = (void *)(long)rtc_fd;
1300 return 0;
1303 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1305 int rtc_fd = (long)t->priv;
1307 close(rtc_fd);
1310 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1312 struct sigevent ev;
1313 timer_t host_timer;
1314 struct sigaction act;
1316 sigfillset(&act.sa_mask);
1317 act.sa_flags = 0;
1318 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1319 act.sa_flags |= SA_ONSTACK;
1320 #endif
1321 act.sa_handler = host_alarm_handler;
1323 sigaction(SIGALRM, &act, NULL);
1325 ev.sigev_value.sival_int = 0;
1326 ev.sigev_notify = SIGEV_SIGNAL;
1327 ev.sigev_signo = SIGALRM;
1329 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1330 perror("timer_create");
1332 /* disable dynticks */
1333 fprintf(stderr, "Dynamic Ticks disabled\n");
1335 return -1;
1338 t->priv = (void *)host_timer;
1340 return 0;
1343 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1345 timer_t host_timer = (timer_t)t->priv;
1347 timer_delete(host_timer);
1350 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1352 timer_t host_timer = (timer_t)t->priv;
1353 struct itimerspec timeout;
1354 int64_t nearest_delta_us = INT64_MAX;
1355 int64_t current_us;
1357 if (!active_timers[QEMU_TIMER_REALTIME] &&
1358 !active_timers[QEMU_TIMER_VIRTUAL])
1359 return;
1361 nearest_delta_us = qemu_next_deadline();
1363 /* check whether a timer is already running */
1364 if (timer_gettime(host_timer, &timeout)) {
1365 perror("gettime");
1366 fprintf(stderr, "Internal timer error: aborting\n");
1367 exit(1);
1369 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1370 if (current_us && current_us <= nearest_delta_us)
1371 return;
1373 timeout.it_interval.tv_sec = 0;
1374 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1375 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1376 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1377 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1378 perror("settime");
1379 fprintf(stderr, "Internal timer error: aborting\n");
1380 exit(1);
1384 #endif /* defined(__linux__) */
1386 static int unix_start_timer(struct qemu_alarm_timer *t)
1388 struct sigaction act;
1389 struct itimerval itv;
1390 int err;
1392 /* timer signal */
1393 sigfillset(&act.sa_mask);
1394 act.sa_flags = 0;
1395 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1396 act.sa_flags |= SA_ONSTACK;
1397 #endif
1398 act.sa_handler = host_alarm_handler;
1400 sigaction(SIGALRM, &act, NULL);
1402 itv.it_interval.tv_sec = 0;
1403 /* for i386 kernel 2.6 to get 1 ms */
1404 itv.it_interval.tv_usec = 999;
1405 itv.it_value.tv_sec = 0;
1406 itv.it_value.tv_usec = 10 * 1000;
1408 err = setitimer(ITIMER_REAL, &itv, NULL);
1409 if (err)
1410 return -1;
1412 return 0;
1415 static void unix_stop_timer(struct qemu_alarm_timer *t)
1417 struct itimerval itv;
1419 memset(&itv, 0, sizeof(itv));
1420 setitimer(ITIMER_REAL, &itv, NULL);
1423 #endif /* !defined(_WIN32) */
1425 #ifdef _WIN32
1427 static int win32_start_timer(struct qemu_alarm_timer *t)
1429 TIMECAPS tc;
1430 struct qemu_alarm_win32 *data = t->priv;
1431 UINT flags;
1433 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1434 if (!data->host_alarm) {
1435 perror("Failed CreateEvent");
1436 return -1;
1439 memset(&tc, 0, sizeof(tc));
1440 timeGetDevCaps(&tc, sizeof(tc));
1442 if (data->period < tc.wPeriodMin)
1443 data->period = tc.wPeriodMin;
1445 timeBeginPeriod(data->period);
1447 flags = TIME_CALLBACK_FUNCTION;
1448 if (alarm_has_dynticks(t))
1449 flags |= TIME_ONESHOT;
1450 else
1451 flags |= TIME_PERIODIC;
1453 data->timerId = timeSetEvent(1, // interval (ms)
1454 data->period, // resolution
1455 host_alarm_handler, // function
1456 (DWORD)t, // parameter
1457 flags);
1459 if (!data->timerId) {
1460 perror("Failed to initialize win32 alarm timer");
1462 timeEndPeriod(data->period);
1463 CloseHandle(data->host_alarm);
1464 return -1;
1467 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1469 return 0;
1472 static void win32_stop_timer(struct qemu_alarm_timer *t)
1474 struct qemu_alarm_win32 *data = t->priv;
1476 timeKillEvent(data->timerId);
1477 timeEndPeriod(data->period);
1479 CloseHandle(data->host_alarm);
1482 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1484 struct qemu_alarm_win32 *data = t->priv;
1485 uint64_t nearest_delta_us;
1487 if (!active_timers[QEMU_TIMER_REALTIME] &&
1488 !active_timers[QEMU_TIMER_VIRTUAL])
1489 return;
1491 nearest_delta_us = qemu_next_deadline();
1492 nearest_delta_us /= 1000;
1494 timeKillEvent(data->timerId);
1496 data->timerId = timeSetEvent(1,
1497 data->period,
1498 host_alarm_handler,
1499 (DWORD)t,
1500 TIME_ONESHOT | TIME_PERIODIC);
1502 if (!data->timerId) {
1503 perror("Failed to re-arm win32 alarm timer");
1505 timeEndPeriod(data->period);
1506 CloseHandle(data->host_alarm);
1507 exit(1);
1511 #endif /* _WIN32 */
1513 static void init_timer_alarm(void)
1515 struct qemu_alarm_timer *t;
1516 int i, err = -1;
1518 for (i = 0; alarm_timers[i].name; i++) {
1519 t = &alarm_timers[i];
1521 err = t->start(t);
1522 if (!err)
1523 break;
1526 if (err) {
1527 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1528 fprintf(stderr, "Terminating\n");
1529 exit(1);
1532 alarm_timer = t;
1535 void quit_timers(void)
1537 alarm_timer->stop(alarm_timer);
1538 alarm_timer = NULL;
1541 /***********************************************************/
1542 /* character device */
1544 static void qemu_chr_event(CharDriverState *s, int event)
1546 if (!s->chr_event)
1547 return;
1548 s->chr_event(s->handler_opaque, event);
1551 static void qemu_chr_reset_bh(void *opaque)
1553 CharDriverState *s = opaque;
1554 qemu_chr_event(s, CHR_EVENT_RESET);
1555 qemu_bh_delete(s->bh);
1556 s->bh = NULL;
1559 void qemu_chr_reset(CharDriverState *s)
1561 if (s->bh == NULL) {
1562 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1563 qemu_bh_schedule(s->bh);
1567 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1569 return s->chr_write(s, buf, len);
1572 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1574 if (!s->chr_ioctl)
1575 return -ENOTSUP;
1576 return s->chr_ioctl(s, cmd, arg);
1579 int qemu_chr_can_read(CharDriverState *s)
1581 if (!s->chr_can_read)
1582 return 0;
1583 return s->chr_can_read(s->handler_opaque);
1586 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1588 s->chr_read(s->handler_opaque, buf, len);
1592 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1594 char buf[4096];
1595 va_list ap;
1596 va_start(ap, fmt);
1597 vsnprintf(buf, sizeof(buf), fmt, ap);
1598 qemu_chr_write(s, buf, strlen(buf));
1599 va_end(ap);
1602 void qemu_chr_send_event(CharDriverState *s, int event)
1604 if (s->chr_send_event)
1605 s->chr_send_event(s, event);
1608 void qemu_chr_add_handlers(CharDriverState *s,
1609 IOCanRWHandler *fd_can_read,
1610 IOReadHandler *fd_read,
1611 IOEventHandler *fd_event,
1612 void *opaque)
1614 s->chr_can_read = fd_can_read;
1615 s->chr_read = fd_read;
1616 s->chr_event = fd_event;
1617 s->handler_opaque = opaque;
1618 if (s->chr_update_read_handler)
1619 s->chr_update_read_handler(s);
1622 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1624 return len;
1627 static CharDriverState *qemu_chr_open_null(void)
1629 CharDriverState *chr;
1631 chr = qemu_mallocz(sizeof(CharDriverState));
1632 if (!chr)
1633 return NULL;
1634 chr->chr_write = null_chr_write;
1635 return chr;
1638 /* MUX driver for serial I/O splitting */
1639 static int term_timestamps;
1640 static int64_t term_timestamps_start;
1641 #define MAX_MUX 4
1642 typedef struct {
1643 IOCanRWHandler *chr_can_read[MAX_MUX];
1644 IOReadHandler *chr_read[MAX_MUX];
1645 IOEventHandler *chr_event[MAX_MUX];
1646 void *ext_opaque[MAX_MUX];
1647 CharDriverState *drv;
1648 int mux_cnt;
1649 int term_got_escape;
1650 int max_size;
1651 } MuxDriver;
1654 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1656 MuxDriver *d = chr->opaque;
1657 int ret;
1658 if (!term_timestamps) {
1659 ret = d->drv->chr_write(d->drv, buf, len);
1660 } else {
1661 int i;
1663 ret = 0;
1664 for(i = 0; i < len; i++) {
1665 ret += d->drv->chr_write(d->drv, buf+i, 1);
1666 if (buf[i] == '\n') {
1667 char buf1[64];
1668 int64_t ti;
1669 int secs;
1671 ti = get_clock();
1672 if (term_timestamps_start == -1)
1673 term_timestamps_start = ti;
1674 ti -= term_timestamps_start;
1675 secs = ti / 1000000000;
1676 snprintf(buf1, sizeof(buf1),
1677 "[%02d:%02d:%02d.%03d] ",
1678 secs / 3600,
1679 (secs / 60) % 60,
1680 secs % 60,
1681 (int)((ti / 1000000) % 1000));
1682 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1686 return ret;
1689 static char *mux_help[] = {
1690 "% h print this help\n\r",
1691 "% x exit emulator\n\r",
1692 "% s save disk data back to file (if -snapshot)\n\r",
1693 "% t toggle console timestamps\n\r"
1694 "% b send break (magic sysrq)\n\r",
1695 "% c switch between console and monitor\n\r",
1696 "% % sends %\n\r",
1697 NULL
1700 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1701 static void mux_print_help(CharDriverState *chr)
1703 int i, j;
1704 char ebuf[15] = "Escape-Char";
1705 char cbuf[50] = "\n\r";
1707 if (term_escape_char > 0 && term_escape_char < 26) {
1708 sprintf(cbuf,"\n\r");
1709 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1710 } else {
1711 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1713 chr->chr_write(chr, cbuf, strlen(cbuf));
1714 for (i = 0; mux_help[i] != NULL; i++) {
1715 for (j=0; mux_help[i][j] != '\0'; j++) {
1716 if (mux_help[i][j] == '%')
1717 chr->chr_write(chr, ebuf, strlen(ebuf));
1718 else
1719 chr->chr_write(chr, &mux_help[i][j], 1);
1724 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1726 if (d->term_got_escape) {
1727 d->term_got_escape = 0;
1728 if (ch == term_escape_char)
1729 goto send_char;
1730 switch(ch) {
1731 case '?':
1732 case 'h':
1733 mux_print_help(chr);
1734 break;
1735 case 'x':
1737 char *term = "QEMU: Terminated\n\r";
1738 chr->chr_write(chr,term,strlen(term));
1739 exit(0);
1740 break;
1742 case 's':
1744 int i;
1745 for (i = 0; i < MAX_DISKS; i++) {
1746 if (bs_table[i])
1747 bdrv_commit(bs_table[i]);
1749 if (mtd_bdrv)
1750 bdrv_commit(mtd_bdrv);
1752 break;
1753 case 'b':
1754 qemu_chr_event(chr, CHR_EVENT_BREAK);
1755 break;
1756 case 'c':
1757 /* Switch to the next registered device */
1758 chr->focus++;
1759 if (chr->focus >= d->mux_cnt)
1760 chr->focus = 0;
1761 break;
1762 case 't':
1763 term_timestamps = !term_timestamps;
1764 term_timestamps_start = -1;
1765 break;
1767 } else if (ch == term_escape_char) {
1768 d->term_got_escape = 1;
1769 } else {
1770 send_char:
1771 return 1;
1773 return 0;
1776 static int mux_chr_can_read(void *opaque)
1778 CharDriverState *chr = opaque;
1779 MuxDriver *d = chr->opaque;
1780 if (d->chr_can_read[chr->focus])
1781 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1782 return 0;
1785 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1787 CharDriverState *chr = opaque;
1788 MuxDriver *d = chr->opaque;
1789 int i;
1790 for(i = 0; i < size; i++)
1791 if (mux_proc_byte(chr, d, buf[i]))
1792 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1795 static void mux_chr_event(void *opaque, int event)
1797 CharDriverState *chr = opaque;
1798 MuxDriver *d = chr->opaque;
1799 int i;
1801 /* Send the event to all registered listeners */
1802 for (i = 0; i < d->mux_cnt; i++)
1803 if (d->chr_event[i])
1804 d->chr_event[i](d->ext_opaque[i], event);
1807 static void mux_chr_update_read_handler(CharDriverState *chr)
1809 MuxDriver *d = chr->opaque;
1811 if (d->mux_cnt >= MAX_MUX) {
1812 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1813 return;
1815 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1816 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1817 d->chr_read[d->mux_cnt] = chr->chr_read;
1818 d->chr_event[d->mux_cnt] = chr->chr_event;
1819 /* Fix up the real driver with mux routines */
1820 if (d->mux_cnt == 0) {
1821 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1822 mux_chr_event, chr);
1824 chr->focus = d->mux_cnt;
1825 d->mux_cnt++;
1828 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1830 CharDriverState *chr;
1831 MuxDriver *d;
1833 chr = qemu_mallocz(sizeof(CharDriverState));
1834 if (!chr)
1835 return NULL;
1836 d = qemu_mallocz(sizeof(MuxDriver));
1837 if (!d) {
1838 free(chr);
1839 return NULL;
1842 chr->opaque = d;
1843 d->drv = drv;
1844 chr->focus = -1;
1845 chr->chr_write = mux_chr_write;
1846 chr->chr_update_read_handler = mux_chr_update_read_handler;
1847 return chr;
1851 #ifdef _WIN32
1853 static void socket_cleanup(void)
1855 WSACleanup();
1858 static int socket_init(void)
1860 WSADATA Data;
1861 int ret, err;
1863 ret = WSAStartup(MAKEWORD(2,2), &Data);
1864 if (ret != 0) {
1865 err = WSAGetLastError();
1866 fprintf(stderr, "WSAStartup: %d\n", err);
1867 return -1;
1869 atexit(socket_cleanup);
1870 return 0;
1873 static int send_all(int fd, const uint8_t *buf, int len1)
1875 int ret, len;
1877 len = len1;
1878 while (len > 0) {
1879 ret = send(fd, buf, len, 0);
1880 if (ret < 0) {
1881 int errno;
1882 errno = WSAGetLastError();
1883 if (errno != WSAEWOULDBLOCK) {
1884 return -1;
1886 } else if (ret == 0) {
1887 break;
1888 } else {
1889 buf += ret;
1890 len -= ret;
1893 return len1 - len;
1896 void socket_set_nonblock(int fd)
1898 unsigned long opt = 1;
1899 ioctlsocket(fd, FIONBIO, &opt);
1902 #else
1904 static int unix_write(int fd, const uint8_t *buf, int len1)
1906 int ret, len;
1908 len = len1;
1909 while (len > 0) {
1910 ret = write(fd, buf, len);
1911 if (ret < 0) {
1912 if (errno != EINTR && errno != EAGAIN)
1913 return -1;
1914 } else if (ret == 0) {
1915 break;
1916 } else {
1917 buf += ret;
1918 len -= ret;
1921 return len1 - len;
1924 static inline int send_all(int fd, const uint8_t *buf, int len1)
1926 return unix_write(fd, buf, len1);
1929 void socket_set_nonblock(int fd)
1931 fcntl(fd, F_SETFL, O_NONBLOCK);
1933 #endif /* !_WIN32 */
1935 #ifndef _WIN32
1937 typedef struct {
1938 int fd_in, fd_out;
1939 int max_size;
1940 } FDCharDriver;
1942 #define STDIO_MAX_CLIENTS 1
1943 static int stdio_nb_clients = 0;
1945 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1947 FDCharDriver *s = chr->opaque;
1948 return unix_write(s->fd_out, buf, len);
1951 static int fd_chr_read_poll(void *opaque)
1953 CharDriverState *chr = opaque;
1954 FDCharDriver *s = chr->opaque;
1956 s->max_size = qemu_chr_can_read(chr);
1957 return s->max_size;
1960 static void fd_chr_read(void *opaque)
1962 CharDriverState *chr = opaque;
1963 FDCharDriver *s = chr->opaque;
1964 int size, len;
1965 uint8_t buf[1024];
1967 len = sizeof(buf);
1968 if (len > s->max_size)
1969 len = s->max_size;
1970 if (len == 0)
1971 return;
1972 size = read(s->fd_in, buf, len);
1973 if (size == 0) {
1974 /* FD has been closed. Remove it from the active list. */
1975 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1976 return;
1978 if (size > 0) {
1979 qemu_chr_read(chr, buf, size);
1983 static void fd_chr_update_read_handler(CharDriverState *chr)
1985 FDCharDriver *s = chr->opaque;
1987 if (s->fd_in >= 0) {
1988 if (nographic && s->fd_in == 0) {
1989 } else {
1990 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1991 fd_chr_read, NULL, chr);
1996 /* open a character device to a unix fd */
1997 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1999 CharDriverState *chr;
2000 FDCharDriver *s;
2002 chr = qemu_mallocz(sizeof(CharDriverState));
2003 if (!chr)
2004 return NULL;
2005 s = qemu_mallocz(sizeof(FDCharDriver));
2006 if (!s) {
2007 free(chr);
2008 return NULL;
2010 s->fd_in = fd_in;
2011 s->fd_out = fd_out;
2012 chr->opaque = s;
2013 chr->chr_write = fd_chr_write;
2014 chr->chr_update_read_handler = fd_chr_update_read_handler;
2016 qemu_chr_reset(chr);
2018 return chr;
2021 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2023 int fd_out;
2025 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2026 if (fd_out < 0)
2027 return NULL;
2028 return qemu_chr_open_fd(-1, fd_out);
2031 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2033 int fd_in, fd_out;
2034 char filename_in[256], filename_out[256];
2036 snprintf(filename_in, 256, "%s.in", filename);
2037 snprintf(filename_out, 256, "%s.out", filename);
2038 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2039 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2040 if (fd_in < 0 || fd_out < 0) {
2041 if (fd_in >= 0)
2042 close(fd_in);
2043 if (fd_out >= 0)
2044 close(fd_out);
2045 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2046 if (fd_in < 0)
2047 return NULL;
2049 return qemu_chr_open_fd(fd_in, fd_out);
2053 /* for STDIO, we handle the case where several clients use it
2054 (nographic mode) */
2056 #define TERM_FIFO_MAX_SIZE 1
2058 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2059 static int term_fifo_size;
2061 static int stdio_read_poll(void *opaque)
2063 CharDriverState *chr = opaque;
2065 /* try to flush the queue if needed */
2066 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2067 qemu_chr_read(chr, term_fifo, 1);
2068 term_fifo_size = 0;
2070 /* see if we can absorb more chars */
2071 if (term_fifo_size == 0)
2072 return 1;
2073 else
2074 return 0;
2077 static void stdio_read(void *opaque)
2079 int size;
2080 uint8_t buf[1];
2081 CharDriverState *chr = opaque;
2083 size = read(0, buf, 1);
2084 if (size == 0) {
2085 /* stdin has been closed. Remove it from the active list. */
2086 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2087 return;
2089 if (size > 0) {
2090 if (qemu_chr_can_read(chr) > 0) {
2091 qemu_chr_read(chr, buf, 1);
2092 } else if (term_fifo_size == 0) {
2093 term_fifo[term_fifo_size++] = buf[0];
2098 /* init terminal so that we can grab keys */
2099 static struct termios oldtty;
2100 static int old_fd0_flags;
2102 static void term_exit(void)
2104 tcsetattr (0, TCSANOW, &oldtty);
2105 fcntl(0, F_SETFL, old_fd0_flags);
2108 static void term_init(void)
2110 struct termios tty;
2112 tcgetattr (0, &tty);
2113 oldtty = tty;
2114 old_fd0_flags = fcntl(0, F_GETFL);
2116 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2117 |INLCR|IGNCR|ICRNL|IXON);
2118 tty.c_oflag |= OPOST;
2119 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2120 /* if graphical mode, we allow Ctrl-C handling */
2121 if (nographic)
2122 tty.c_lflag &= ~ISIG;
2123 tty.c_cflag &= ~(CSIZE|PARENB);
2124 tty.c_cflag |= CS8;
2125 tty.c_cc[VMIN] = 1;
2126 tty.c_cc[VTIME] = 0;
2128 tcsetattr (0, TCSANOW, &tty);
2130 atexit(term_exit);
2132 fcntl(0, F_SETFL, O_NONBLOCK);
2135 static CharDriverState *qemu_chr_open_stdio(void)
2137 CharDriverState *chr;
2139 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2140 return NULL;
2141 chr = qemu_chr_open_fd(0, 1);
2142 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2143 stdio_nb_clients++;
2144 term_init();
2146 return chr;
2149 #if defined(__linux__) || defined(__sun__)
2150 static CharDriverState *qemu_chr_open_pty(void)
2152 struct termios tty;
2153 char slave_name[1024];
2154 int master_fd, slave_fd;
2156 #if defined(__linux__)
2157 /* Not satisfying */
2158 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2159 return NULL;
2161 #endif
2163 /* Disabling local echo and line-buffered output */
2164 tcgetattr (master_fd, &tty);
2165 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2166 tty.c_cc[VMIN] = 1;
2167 tty.c_cc[VTIME] = 0;
2168 tcsetattr (master_fd, TCSAFLUSH, &tty);
2170 fprintf(stderr, "char device redirected to %s\n", slave_name);
2171 return qemu_chr_open_fd(master_fd, master_fd);
2174 static void tty_serial_init(int fd, int speed,
2175 int parity, int data_bits, int stop_bits)
2177 struct termios tty;
2178 speed_t spd;
2180 #if 0
2181 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2182 speed, parity, data_bits, stop_bits);
2183 #endif
2184 tcgetattr (fd, &tty);
2186 switch(speed) {
2187 case 50:
2188 spd = B50;
2189 break;
2190 case 75:
2191 spd = B75;
2192 break;
2193 case 300:
2194 spd = B300;
2195 break;
2196 case 600:
2197 spd = B600;
2198 break;
2199 case 1200:
2200 spd = B1200;
2201 break;
2202 case 2400:
2203 spd = B2400;
2204 break;
2205 case 4800:
2206 spd = B4800;
2207 break;
2208 case 9600:
2209 spd = B9600;
2210 break;
2211 case 19200:
2212 spd = B19200;
2213 break;
2214 case 38400:
2215 spd = B38400;
2216 break;
2217 case 57600:
2218 spd = B57600;
2219 break;
2220 default:
2221 case 115200:
2222 spd = B115200;
2223 break;
2226 cfsetispeed(&tty, spd);
2227 cfsetospeed(&tty, spd);
2229 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2230 |INLCR|IGNCR|ICRNL|IXON);
2231 tty.c_oflag |= OPOST;
2232 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2233 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2234 switch(data_bits) {
2235 default:
2236 case 8:
2237 tty.c_cflag |= CS8;
2238 break;
2239 case 7:
2240 tty.c_cflag |= CS7;
2241 break;
2242 case 6:
2243 tty.c_cflag |= CS6;
2244 break;
2245 case 5:
2246 tty.c_cflag |= CS5;
2247 break;
2249 switch(parity) {
2250 default:
2251 case 'N':
2252 break;
2253 case 'E':
2254 tty.c_cflag |= PARENB;
2255 break;
2256 case 'O':
2257 tty.c_cflag |= PARENB | PARODD;
2258 break;
2260 if (stop_bits == 2)
2261 tty.c_cflag |= CSTOPB;
2263 tcsetattr (fd, TCSANOW, &tty);
2266 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2268 FDCharDriver *s = chr->opaque;
2270 switch(cmd) {
2271 case CHR_IOCTL_SERIAL_SET_PARAMS:
2273 QEMUSerialSetParams *ssp = arg;
2274 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2275 ssp->data_bits, ssp->stop_bits);
2277 break;
2278 case CHR_IOCTL_SERIAL_SET_BREAK:
2280 int enable = *(int *)arg;
2281 if (enable)
2282 tcsendbreak(s->fd_in, 1);
2284 break;
2285 default:
2286 return -ENOTSUP;
2288 return 0;
2291 static CharDriverState *qemu_chr_open_tty(const char *filename)
2293 CharDriverState *chr;
2294 int fd;
2296 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2297 fcntl(fd, F_SETFL, O_NONBLOCK);
2298 tty_serial_init(fd, 115200, 'N', 8, 1);
2299 chr = qemu_chr_open_fd(fd, fd);
2300 if (!chr) {
2301 close(fd);
2302 return NULL;
2304 chr->chr_ioctl = tty_serial_ioctl;
2305 qemu_chr_reset(chr);
2306 return chr;
2308 #else /* ! __linux__ && ! __sun__ */
2309 static CharDriverState *qemu_chr_open_pty(void)
2311 return NULL;
2313 #endif /* __linux__ || __sun__ */
2315 #if defined(__linux__)
2316 typedef struct {
2317 int fd;
2318 int mode;
2319 } ParallelCharDriver;
2321 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2323 if (s->mode != mode) {
2324 int m = mode;
2325 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2326 return 0;
2327 s->mode = mode;
2329 return 1;
2332 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2334 ParallelCharDriver *drv = chr->opaque;
2335 int fd = drv->fd;
2336 uint8_t b;
2338 switch(cmd) {
2339 case CHR_IOCTL_PP_READ_DATA:
2340 if (ioctl(fd, PPRDATA, &b) < 0)
2341 return -ENOTSUP;
2342 *(uint8_t *)arg = b;
2343 break;
2344 case CHR_IOCTL_PP_WRITE_DATA:
2345 b = *(uint8_t *)arg;
2346 if (ioctl(fd, PPWDATA, &b) < 0)
2347 return -ENOTSUP;
2348 break;
2349 case CHR_IOCTL_PP_READ_CONTROL:
2350 if (ioctl(fd, PPRCONTROL, &b) < 0)
2351 return -ENOTSUP;
2352 /* Linux gives only the lowest bits, and no way to know data
2353 direction! For better compatibility set the fixed upper
2354 bits. */
2355 *(uint8_t *)arg = b | 0xc0;
2356 break;
2357 case CHR_IOCTL_PP_WRITE_CONTROL:
2358 b = *(uint8_t *)arg;
2359 if (ioctl(fd, PPWCONTROL, &b) < 0)
2360 return -ENOTSUP;
2361 break;
2362 case CHR_IOCTL_PP_READ_STATUS:
2363 if (ioctl(fd, PPRSTATUS, &b) < 0)
2364 return -ENOTSUP;
2365 *(uint8_t *)arg = b;
2366 break;
2367 case CHR_IOCTL_PP_EPP_READ_ADDR:
2368 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2369 struct ParallelIOArg *parg = arg;
2370 int n = read(fd, parg->buffer, parg->count);
2371 if (n != parg->count) {
2372 return -EIO;
2375 break;
2376 case CHR_IOCTL_PP_EPP_READ:
2377 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2378 struct ParallelIOArg *parg = arg;
2379 int n = read(fd, parg->buffer, parg->count);
2380 if (n != parg->count) {
2381 return -EIO;
2384 break;
2385 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2386 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2387 struct ParallelIOArg *parg = arg;
2388 int n = write(fd, parg->buffer, parg->count);
2389 if (n != parg->count) {
2390 return -EIO;
2393 break;
2394 case CHR_IOCTL_PP_EPP_WRITE:
2395 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2396 struct ParallelIOArg *parg = arg;
2397 int n = write(fd, parg->buffer, parg->count);
2398 if (n != parg->count) {
2399 return -EIO;
2402 break;
2403 default:
2404 return -ENOTSUP;
2406 return 0;
2409 static void pp_close(CharDriverState *chr)
2411 ParallelCharDriver *drv = chr->opaque;
2412 int fd = drv->fd;
2414 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2415 ioctl(fd, PPRELEASE);
2416 close(fd);
2417 qemu_free(drv);
2420 static CharDriverState *qemu_chr_open_pp(const char *filename)
2422 CharDriverState *chr;
2423 ParallelCharDriver *drv;
2424 int fd;
2426 TFR(fd = open(filename, O_RDWR));
2427 if (fd < 0)
2428 return NULL;
2430 if (ioctl(fd, PPCLAIM) < 0) {
2431 close(fd);
2432 return NULL;
2435 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2436 if (!drv) {
2437 close(fd);
2438 return NULL;
2440 drv->fd = fd;
2441 drv->mode = IEEE1284_MODE_COMPAT;
2443 chr = qemu_mallocz(sizeof(CharDriverState));
2444 if (!chr) {
2445 qemu_free(drv);
2446 close(fd);
2447 return NULL;
2449 chr->chr_write = null_chr_write;
2450 chr->chr_ioctl = pp_ioctl;
2451 chr->chr_close = pp_close;
2452 chr->opaque = drv;
2454 qemu_chr_reset(chr);
2456 return chr;
2458 #endif /* __linux__ */
2460 #else /* _WIN32 */
2462 typedef struct {
2463 int max_size;
2464 HANDLE hcom, hrecv, hsend;
2465 OVERLAPPED orecv, osend;
2466 BOOL fpipe;
2467 DWORD len;
2468 } WinCharState;
2470 #define NSENDBUF 2048
2471 #define NRECVBUF 2048
2472 #define MAXCONNECT 1
2473 #define NTIMEOUT 5000
2475 static int win_chr_poll(void *opaque);
2476 static int win_chr_pipe_poll(void *opaque);
2478 static void win_chr_close(CharDriverState *chr)
2480 WinCharState *s = chr->opaque;
2482 if (s->hsend) {
2483 CloseHandle(s->hsend);
2484 s->hsend = NULL;
2486 if (s->hrecv) {
2487 CloseHandle(s->hrecv);
2488 s->hrecv = NULL;
2490 if (s->hcom) {
2491 CloseHandle(s->hcom);
2492 s->hcom = NULL;
2494 if (s->fpipe)
2495 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2496 else
2497 qemu_del_polling_cb(win_chr_poll, chr);
2500 static int win_chr_init(CharDriverState *chr, const char *filename)
2502 WinCharState *s = chr->opaque;
2503 COMMCONFIG comcfg;
2504 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2505 COMSTAT comstat;
2506 DWORD size;
2507 DWORD err;
2509 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2510 if (!s->hsend) {
2511 fprintf(stderr, "Failed CreateEvent\n");
2512 goto fail;
2514 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2515 if (!s->hrecv) {
2516 fprintf(stderr, "Failed CreateEvent\n");
2517 goto fail;
2520 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2521 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2522 if (s->hcom == INVALID_HANDLE_VALUE) {
2523 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2524 s->hcom = NULL;
2525 goto fail;
2528 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2529 fprintf(stderr, "Failed SetupComm\n");
2530 goto fail;
2533 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2534 size = sizeof(COMMCONFIG);
2535 GetDefaultCommConfig(filename, &comcfg, &size);
2536 comcfg.dcb.DCBlength = sizeof(DCB);
2537 CommConfigDialog(filename, NULL, &comcfg);
2539 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2540 fprintf(stderr, "Failed SetCommState\n");
2541 goto fail;
2544 if (!SetCommMask(s->hcom, EV_ERR)) {
2545 fprintf(stderr, "Failed SetCommMask\n");
2546 goto fail;
2549 cto.ReadIntervalTimeout = MAXDWORD;
2550 if (!SetCommTimeouts(s->hcom, &cto)) {
2551 fprintf(stderr, "Failed SetCommTimeouts\n");
2552 goto fail;
2555 if (!ClearCommError(s->hcom, &err, &comstat)) {
2556 fprintf(stderr, "Failed ClearCommError\n");
2557 goto fail;
2559 qemu_add_polling_cb(win_chr_poll, chr);
2560 return 0;
2562 fail:
2563 win_chr_close(chr);
2564 return -1;
2567 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2569 WinCharState *s = chr->opaque;
2570 DWORD len, ret, size, err;
2572 len = len1;
2573 ZeroMemory(&s->osend, sizeof(s->osend));
2574 s->osend.hEvent = s->hsend;
2575 while (len > 0) {
2576 if (s->hsend)
2577 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2578 else
2579 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2580 if (!ret) {
2581 err = GetLastError();
2582 if (err == ERROR_IO_PENDING) {
2583 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2584 if (ret) {
2585 buf += size;
2586 len -= size;
2587 } else {
2588 break;
2590 } else {
2591 break;
2593 } else {
2594 buf += size;
2595 len -= size;
2598 return len1 - len;
2601 static int win_chr_read_poll(CharDriverState *chr)
2603 WinCharState *s = chr->opaque;
2605 s->max_size = qemu_chr_can_read(chr);
2606 return s->max_size;
2609 static void win_chr_readfile(CharDriverState *chr)
2611 WinCharState *s = chr->opaque;
2612 int ret, err;
2613 uint8_t buf[1024];
2614 DWORD size;
2616 ZeroMemory(&s->orecv, sizeof(s->orecv));
2617 s->orecv.hEvent = s->hrecv;
2618 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2619 if (!ret) {
2620 err = GetLastError();
2621 if (err == ERROR_IO_PENDING) {
2622 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2626 if (size > 0) {
2627 qemu_chr_read(chr, buf, size);
2631 static void win_chr_read(CharDriverState *chr)
2633 WinCharState *s = chr->opaque;
2635 if (s->len > s->max_size)
2636 s->len = s->max_size;
2637 if (s->len == 0)
2638 return;
2640 win_chr_readfile(chr);
2643 static int win_chr_poll(void *opaque)
2645 CharDriverState *chr = opaque;
2646 WinCharState *s = chr->opaque;
2647 COMSTAT status;
2648 DWORD comerr;
2650 ClearCommError(s->hcom, &comerr, &status);
2651 if (status.cbInQue > 0) {
2652 s->len = status.cbInQue;
2653 win_chr_read_poll(chr);
2654 win_chr_read(chr);
2655 return 1;
2657 return 0;
2660 static CharDriverState *qemu_chr_open_win(const char *filename)
2662 CharDriverState *chr;
2663 WinCharState *s;
2665 chr = qemu_mallocz(sizeof(CharDriverState));
2666 if (!chr)
2667 return NULL;
2668 s = qemu_mallocz(sizeof(WinCharState));
2669 if (!s) {
2670 free(chr);
2671 return NULL;
2673 chr->opaque = s;
2674 chr->chr_write = win_chr_write;
2675 chr->chr_close = win_chr_close;
2677 if (win_chr_init(chr, filename) < 0) {
2678 free(s);
2679 free(chr);
2680 return NULL;
2682 qemu_chr_reset(chr);
2683 return chr;
2686 static int win_chr_pipe_poll(void *opaque)
2688 CharDriverState *chr = opaque;
2689 WinCharState *s = chr->opaque;
2690 DWORD size;
2692 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2693 if (size > 0) {
2694 s->len = size;
2695 win_chr_read_poll(chr);
2696 win_chr_read(chr);
2697 return 1;
2699 return 0;
2702 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2704 WinCharState *s = chr->opaque;
2705 OVERLAPPED ov;
2706 int ret;
2707 DWORD size;
2708 char openname[256];
2710 s->fpipe = TRUE;
2712 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2713 if (!s->hsend) {
2714 fprintf(stderr, "Failed CreateEvent\n");
2715 goto fail;
2717 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2718 if (!s->hrecv) {
2719 fprintf(stderr, "Failed CreateEvent\n");
2720 goto fail;
2723 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2724 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2725 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2726 PIPE_WAIT,
2727 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2728 if (s->hcom == INVALID_HANDLE_VALUE) {
2729 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2730 s->hcom = NULL;
2731 goto fail;
2734 ZeroMemory(&ov, sizeof(ov));
2735 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2736 ret = ConnectNamedPipe(s->hcom, &ov);
2737 if (ret) {
2738 fprintf(stderr, "Failed ConnectNamedPipe\n");
2739 goto fail;
2742 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2743 if (!ret) {
2744 fprintf(stderr, "Failed GetOverlappedResult\n");
2745 if (ov.hEvent) {
2746 CloseHandle(ov.hEvent);
2747 ov.hEvent = NULL;
2749 goto fail;
2752 if (ov.hEvent) {
2753 CloseHandle(ov.hEvent);
2754 ov.hEvent = NULL;
2756 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2757 return 0;
2759 fail:
2760 win_chr_close(chr);
2761 return -1;
2765 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2767 CharDriverState *chr;
2768 WinCharState *s;
2770 chr = qemu_mallocz(sizeof(CharDriverState));
2771 if (!chr)
2772 return NULL;
2773 s = qemu_mallocz(sizeof(WinCharState));
2774 if (!s) {
2775 free(chr);
2776 return NULL;
2778 chr->opaque = s;
2779 chr->chr_write = win_chr_write;
2780 chr->chr_close = win_chr_close;
2782 if (win_chr_pipe_init(chr, filename) < 0) {
2783 free(s);
2784 free(chr);
2785 return NULL;
2787 qemu_chr_reset(chr);
2788 return chr;
2791 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2793 CharDriverState *chr;
2794 WinCharState *s;
2796 chr = qemu_mallocz(sizeof(CharDriverState));
2797 if (!chr)
2798 return NULL;
2799 s = qemu_mallocz(sizeof(WinCharState));
2800 if (!s) {
2801 free(chr);
2802 return NULL;
2804 s->hcom = fd_out;
2805 chr->opaque = s;
2806 chr->chr_write = win_chr_write;
2807 qemu_chr_reset(chr);
2808 return chr;
2811 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2813 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2816 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2818 HANDLE fd_out;
2820 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2821 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2822 if (fd_out == INVALID_HANDLE_VALUE)
2823 return NULL;
2825 return qemu_chr_open_win_file(fd_out);
2827 #endif /* !_WIN32 */
2829 /***********************************************************/
2830 /* UDP Net console */
2832 typedef struct {
2833 int fd;
2834 struct sockaddr_in daddr;
2835 char buf[1024];
2836 int bufcnt;
2837 int bufptr;
2838 int max_size;
2839 } NetCharDriver;
2841 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2843 NetCharDriver *s = chr->opaque;
2845 return sendto(s->fd, buf, len, 0,
2846 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2849 static int udp_chr_read_poll(void *opaque)
2851 CharDriverState *chr = opaque;
2852 NetCharDriver *s = chr->opaque;
2854 s->max_size = qemu_chr_can_read(chr);
2856 /* If there were any stray characters in the queue process them
2857 * first
2859 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2860 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2861 s->bufptr++;
2862 s->max_size = qemu_chr_can_read(chr);
2864 return s->max_size;
2867 static void udp_chr_read(void *opaque)
2869 CharDriverState *chr = opaque;
2870 NetCharDriver *s = chr->opaque;
2872 if (s->max_size == 0)
2873 return;
2874 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2875 s->bufptr = s->bufcnt;
2876 if (s->bufcnt <= 0)
2877 return;
2879 s->bufptr = 0;
2880 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2881 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2882 s->bufptr++;
2883 s->max_size = qemu_chr_can_read(chr);
2887 static void udp_chr_update_read_handler(CharDriverState *chr)
2889 NetCharDriver *s = chr->opaque;
2891 if (s->fd >= 0) {
2892 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2893 udp_chr_read, NULL, chr);
2897 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2898 #ifndef _WIN32
2899 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2900 #endif
2901 int parse_host_src_port(struct sockaddr_in *haddr,
2902 struct sockaddr_in *saddr,
2903 const char *str);
2905 static CharDriverState *qemu_chr_open_udp(const char *def)
2907 CharDriverState *chr = NULL;
2908 NetCharDriver *s = NULL;
2909 int fd = -1;
2910 struct sockaddr_in saddr;
2912 chr = qemu_mallocz(sizeof(CharDriverState));
2913 if (!chr)
2914 goto return_err;
2915 s = qemu_mallocz(sizeof(NetCharDriver));
2916 if (!s)
2917 goto return_err;
2919 fd = socket(PF_INET, SOCK_DGRAM, 0);
2920 if (fd < 0) {
2921 perror("socket(PF_INET, SOCK_DGRAM)");
2922 goto return_err;
2925 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2926 printf("Could not parse: %s\n", def);
2927 goto return_err;
2930 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2932 perror("bind");
2933 goto return_err;
2936 s->fd = fd;
2937 s->bufcnt = 0;
2938 s->bufptr = 0;
2939 chr->opaque = s;
2940 chr->chr_write = udp_chr_write;
2941 chr->chr_update_read_handler = udp_chr_update_read_handler;
2942 return chr;
2944 return_err:
2945 if (chr)
2946 free(chr);
2947 if (s)
2948 free(s);
2949 if (fd >= 0)
2950 closesocket(fd);
2951 return NULL;
2954 /***********************************************************/
2955 /* TCP Net console */
2957 typedef struct {
2958 int fd, listen_fd;
2959 int connected;
2960 int max_size;
2961 int do_telnetopt;
2962 int do_nodelay;
2963 int is_unix;
2964 } TCPCharDriver;
2966 static void tcp_chr_accept(void *opaque);
2968 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2970 TCPCharDriver *s = chr->opaque;
2971 if (s->connected) {
2972 return send_all(s->fd, buf, len);
2973 } else {
2974 /* XXX: indicate an error ? */
2975 return len;
2979 static int tcp_chr_read_poll(void *opaque)
2981 CharDriverState *chr = opaque;
2982 TCPCharDriver *s = chr->opaque;
2983 if (!s->connected)
2984 return 0;
2985 s->max_size = qemu_chr_can_read(chr);
2986 return s->max_size;
2989 #define IAC 255
2990 #define IAC_BREAK 243
2991 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2992 TCPCharDriver *s,
2993 char *buf, int *size)
2995 /* Handle any telnet client's basic IAC options to satisfy char by
2996 * char mode with no echo. All IAC options will be removed from
2997 * the buf and the do_telnetopt variable will be used to track the
2998 * state of the width of the IAC information.
3000 * IAC commands come in sets of 3 bytes with the exception of the
3001 * "IAC BREAK" command and the double IAC.
3004 int i;
3005 int j = 0;
3007 for (i = 0; i < *size; i++) {
3008 if (s->do_telnetopt > 1) {
3009 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3010 /* Double IAC means send an IAC */
3011 if (j != i)
3012 buf[j] = buf[i];
3013 j++;
3014 s->do_telnetopt = 1;
3015 } else {
3016 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3017 /* Handle IAC break commands by sending a serial break */
3018 qemu_chr_event(chr, CHR_EVENT_BREAK);
3019 s->do_telnetopt++;
3021 s->do_telnetopt++;
3023 if (s->do_telnetopt >= 4) {
3024 s->do_telnetopt = 1;
3026 } else {
3027 if ((unsigned char)buf[i] == IAC) {
3028 s->do_telnetopt = 2;
3029 } else {
3030 if (j != i)
3031 buf[j] = buf[i];
3032 j++;
3036 *size = j;
3039 static void tcp_chr_read(void *opaque)
3041 CharDriverState *chr = opaque;
3042 TCPCharDriver *s = chr->opaque;
3043 uint8_t buf[1024];
3044 int len, size;
3046 if (!s->connected || s->max_size <= 0)
3047 return;
3048 len = sizeof(buf);
3049 if (len > s->max_size)
3050 len = s->max_size;
3051 size = recv(s->fd, buf, len, 0);
3052 if (size == 0) {
3053 /* connection closed */
3054 s->connected = 0;
3055 if (s->listen_fd >= 0) {
3056 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3058 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3059 closesocket(s->fd);
3060 s->fd = -1;
3061 } else if (size > 0) {
3062 if (s->do_telnetopt)
3063 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3064 if (size > 0)
3065 qemu_chr_read(chr, buf, size);
3069 static void tcp_chr_connect(void *opaque)
3071 CharDriverState *chr = opaque;
3072 TCPCharDriver *s = chr->opaque;
3074 s->connected = 1;
3075 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3076 tcp_chr_read, NULL, chr);
3077 qemu_chr_reset(chr);
3080 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3081 static void tcp_chr_telnet_init(int fd)
3083 char buf[3];
3084 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3085 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3086 send(fd, (char *)buf, 3, 0);
3087 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3088 send(fd, (char *)buf, 3, 0);
3089 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3090 send(fd, (char *)buf, 3, 0);
3091 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3092 send(fd, (char *)buf, 3, 0);
3095 static void socket_set_nodelay(int fd)
3097 int val = 1;
3098 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3101 static void tcp_chr_accept(void *opaque)
3103 CharDriverState *chr = opaque;
3104 TCPCharDriver *s = chr->opaque;
3105 struct sockaddr_in saddr;
3106 #ifndef _WIN32
3107 struct sockaddr_un uaddr;
3108 #endif
3109 struct sockaddr *addr;
3110 socklen_t len;
3111 int fd;
3113 for(;;) {
3114 #ifndef _WIN32
3115 if (s->is_unix) {
3116 len = sizeof(uaddr);
3117 addr = (struct sockaddr *)&uaddr;
3118 } else
3119 #endif
3121 len = sizeof(saddr);
3122 addr = (struct sockaddr *)&saddr;
3124 fd = accept(s->listen_fd, addr, &len);
3125 if (fd < 0 && errno != EINTR) {
3126 return;
3127 } else if (fd >= 0) {
3128 if (s->do_telnetopt)
3129 tcp_chr_telnet_init(fd);
3130 break;
3133 socket_set_nonblock(fd);
3134 if (s->do_nodelay)
3135 socket_set_nodelay(fd);
3136 s->fd = fd;
3137 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3138 tcp_chr_connect(chr);
3141 static void tcp_chr_close(CharDriverState *chr)
3143 TCPCharDriver *s = chr->opaque;
3144 if (s->fd >= 0)
3145 closesocket(s->fd);
3146 if (s->listen_fd >= 0)
3147 closesocket(s->listen_fd);
3148 qemu_free(s);
3151 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3152 int is_telnet,
3153 int is_unix)
3155 CharDriverState *chr = NULL;
3156 TCPCharDriver *s = NULL;
3157 int fd = -1, ret, err, val;
3158 int is_listen = 0;
3159 int is_waitconnect = 1;
3160 int do_nodelay = 0;
3161 const char *ptr;
3162 struct sockaddr_in saddr;
3163 #ifndef _WIN32
3164 struct sockaddr_un uaddr;
3165 #endif
3166 struct sockaddr *addr;
3167 socklen_t addrlen;
3169 #ifndef _WIN32
3170 if (is_unix) {
3171 addr = (struct sockaddr *)&uaddr;
3172 addrlen = sizeof(uaddr);
3173 if (parse_unix_path(&uaddr, host_str) < 0)
3174 goto fail;
3175 } else
3176 #endif
3178 addr = (struct sockaddr *)&saddr;
3179 addrlen = sizeof(saddr);
3180 if (parse_host_port(&saddr, host_str) < 0)
3181 goto fail;
3184 ptr = host_str;
3185 while((ptr = strchr(ptr,','))) {
3186 ptr++;
3187 if (!strncmp(ptr,"server",6)) {
3188 is_listen = 1;
3189 } else if (!strncmp(ptr,"nowait",6)) {
3190 is_waitconnect = 0;
3191 } else if (!strncmp(ptr,"nodelay",6)) {
3192 do_nodelay = 1;
3193 } else {
3194 printf("Unknown option: %s\n", ptr);
3195 goto fail;
3198 if (!is_listen)
3199 is_waitconnect = 0;
3201 chr = qemu_mallocz(sizeof(CharDriverState));
3202 if (!chr)
3203 goto fail;
3204 s = qemu_mallocz(sizeof(TCPCharDriver));
3205 if (!s)
3206 goto fail;
3208 #ifndef _WIN32
3209 if (is_unix)
3210 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3211 else
3212 #endif
3213 fd = socket(PF_INET, SOCK_STREAM, 0);
3215 if (fd < 0)
3216 goto fail;
3218 if (!is_waitconnect)
3219 socket_set_nonblock(fd);
3221 s->connected = 0;
3222 s->fd = -1;
3223 s->listen_fd = -1;
3224 s->is_unix = is_unix;
3225 s->do_nodelay = do_nodelay && !is_unix;
3227 chr->opaque = s;
3228 chr->chr_write = tcp_chr_write;
3229 chr->chr_close = tcp_chr_close;
3231 if (is_listen) {
3232 /* allow fast reuse */
3233 #ifndef _WIN32
3234 if (is_unix) {
3235 char path[109];
3236 strncpy(path, uaddr.sun_path, 108);
3237 path[108] = 0;
3238 unlink(path);
3239 } else
3240 #endif
3242 val = 1;
3243 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3246 ret = bind(fd, addr, addrlen);
3247 if (ret < 0)
3248 goto fail;
3250 ret = listen(fd, 0);
3251 if (ret < 0)
3252 goto fail;
3254 s->listen_fd = fd;
3255 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3256 if (is_telnet)
3257 s->do_telnetopt = 1;
3258 } else {
3259 for(;;) {
3260 ret = connect(fd, addr, addrlen);
3261 if (ret < 0) {
3262 err = socket_error();
3263 if (err == EINTR || err == EWOULDBLOCK) {
3264 } else if (err == EINPROGRESS) {
3265 break;
3266 #ifdef _WIN32
3267 } else if (err == WSAEALREADY) {
3268 break;
3269 #endif
3270 } else {
3271 goto fail;
3273 } else {
3274 s->connected = 1;
3275 break;
3278 s->fd = fd;
3279 socket_set_nodelay(fd);
3280 if (s->connected)
3281 tcp_chr_connect(chr);
3282 else
3283 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3286 if (is_listen && is_waitconnect) {
3287 printf("QEMU waiting for connection on: %s\n", host_str);
3288 tcp_chr_accept(chr);
3289 socket_set_nonblock(s->listen_fd);
3292 return chr;
3293 fail:
3294 if (fd >= 0)
3295 closesocket(fd);
3296 qemu_free(s);
3297 qemu_free(chr);
3298 return NULL;
3301 CharDriverState *qemu_chr_open(const char *filename)
3303 const char *p;
3305 if (!strcmp(filename, "vc")) {
3306 return text_console_init(&display_state, 0);
3307 } else if (strstart(filename, "vc:", &p)) {
3308 return text_console_init(&display_state, p);
3309 } else if (!strcmp(filename, "null")) {
3310 return qemu_chr_open_null();
3311 } else
3312 if (strstart(filename, "tcp:", &p)) {
3313 return qemu_chr_open_tcp(p, 0, 0);
3314 } else
3315 if (strstart(filename, "telnet:", &p)) {
3316 return qemu_chr_open_tcp(p, 1, 0);
3317 } else
3318 if (strstart(filename, "udp:", &p)) {
3319 return qemu_chr_open_udp(p);
3320 } else
3321 if (strstart(filename, "mon:", &p)) {
3322 CharDriverState *drv = qemu_chr_open(p);
3323 if (drv) {
3324 drv = qemu_chr_open_mux(drv);
3325 monitor_init(drv, !nographic);
3326 return drv;
3328 printf("Unable to open driver: %s\n", p);
3329 return 0;
3330 } else
3331 #ifndef _WIN32
3332 if (strstart(filename, "unix:", &p)) {
3333 return qemu_chr_open_tcp(p, 0, 1);
3334 } else if (strstart(filename, "file:", &p)) {
3335 return qemu_chr_open_file_out(p);
3336 } else if (strstart(filename, "pipe:", &p)) {
3337 return qemu_chr_open_pipe(p);
3338 } else if (!strcmp(filename, "pty")) {
3339 return qemu_chr_open_pty();
3340 } else if (!strcmp(filename, "stdio")) {
3341 return qemu_chr_open_stdio();
3342 } else
3343 #if defined(__linux__)
3344 if (strstart(filename, "/dev/parport", NULL)) {
3345 return qemu_chr_open_pp(filename);
3346 } else
3347 #endif
3348 #if defined(__linux__) || defined(__sun__)
3349 if (strstart(filename, "/dev/", NULL)) {
3350 return qemu_chr_open_tty(filename);
3351 } else
3352 #endif
3353 #else /* !_WIN32 */
3354 if (strstart(filename, "COM", NULL)) {
3355 return qemu_chr_open_win(filename);
3356 } else
3357 if (strstart(filename, "pipe:", &p)) {
3358 return qemu_chr_open_win_pipe(p);
3359 } else
3360 if (strstart(filename, "con:", NULL)) {
3361 return qemu_chr_open_win_con(filename);
3362 } else
3363 if (strstart(filename, "file:", &p)) {
3364 return qemu_chr_open_win_file_out(p);
3366 #endif
3368 return NULL;
3372 void qemu_chr_close(CharDriverState *chr)
3374 if (chr->chr_close)
3375 chr->chr_close(chr);
3378 /***********************************************************/
3379 /* network device redirectors */
3381 void hex_dump(FILE *f, const uint8_t *buf, int size)
3383 int len, i, j, c;
3385 for(i=0;i<size;i+=16) {
3386 len = size - i;
3387 if (len > 16)
3388 len = 16;
3389 fprintf(f, "%08x ", i);
3390 for(j=0;j<16;j++) {
3391 if (j < len)
3392 fprintf(f, " %02x", buf[i+j]);
3393 else
3394 fprintf(f, " ");
3396 fprintf(f, " ");
3397 for(j=0;j<len;j++) {
3398 c = buf[i+j];
3399 if (c < ' ' || c > '~')
3400 c = '.';
3401 fprintf(f, "%c", c);
3403 fprintf(f, "\n");
3407 static int parse_macaddr(uint8_t *macaddr, const char *p)
3409 int i;
3410 for(i = 0; i < 6; i++) {
3411 macaddr[i] = strtol(p, (char **)&p, 16);
3412 if (i == 5) {
3413 if (*p != '\0')
3414 return -1;
3415 } else {
3416 if (*p != ':')
3417 return -1;
3418 p++;
3421 return 0;
3424 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3426 const char *p, *p1;
3427 int len;
3428 p = *pp;
3429 p1 = strchr(p, sep);
3430 if (!p1)
3431 return -1;
3432 len = p1 - p;
3433 p1++;
3434 if (buf_size > 0) {
3435 if (len > buf_size - 1)
3436 len = buf_size - 1;
3437 memcpy(buf, p, len);
3438 buf[len] = '\0';
3440 *pp = p1;
3441 return 0;
3444 int parse_host_src_port(struct sockaddr_in *haddr,
3445 struct sockaddr_in *saddr,
3446 const char *input_str)
3448 char *str = strdup(input_str);
3449 char *host_str = str;
3450 char *src_str;
3451 char *ptr;
3454 * Chop off any extra arguments at the end of the string which
3455 * would start with a comma, then fill in the src port information
3456 * if it was provided else use the "any address" and "any port".
3458 if ((ptr = strchr(str,',')))
3459 *ptr = '\0';
3461 if ((src_str = strchr(input_str,'@'))) {
3462 *src_str = '\0';
3463 src_str++;
3466 if (parse_host_port(haddr, host_str) < 0)
3467 goto fail;
3469 if (!src_str || *src_str == '\0')
3470 src_str = ":0";
3472 if (parse_host_port(saddr, src_str) < 0)
3473 goto fail;
3475 free(str);
3476 return(0);
3478 fail:
3479 free(str);
3480 return -1;
3483 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3485 char buf[512];
3486 struct hostent *he;
3487 const char *p, *r;
3488 int port;
3490 p = str;
3491 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3492 return -1;
3493 saddr->sin_family = AF_INET;
3494 if (buf[0] == '\0') {
3495 saddr->sin_addr.s_addr = 0;
3496 } else {
3497 if (isdigit(buf[0])) {
3498 if (!inet_aton(buf, &saddr->sin_addr))
3499 return -1;
3500 } else {
3501 if ((he = gethostbyname(buf)) == NULL)
3502 return - 1;
3503 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3506 port = strtol(p, (char **)&r, 0);
3507 if (r == p)
3508 return -1;
3509 saddr->sin_port = htons(port);
3510 return 0;
3513 #ifndef _WIN32
3514 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3516 const char *p;
3517 int len;
3519 len = MIN(108, strlen(str));
3520 p = strchr(str, ',');
3521 if (p)
3522 len = MIN(len, p - str);
3524 memset(uaddr, 0, sizeof(*uaddr));
3526 uaddr->sun_family = AF_UNIX;
3527 memcpy(uaddr->sun_path, str, len);
3529 return 0;
3531 #endif
3533 /* find or alloc a new VLAN */
3534 VLANState *qemu_find_vlan(int id)
3536 VLANState **pvlan, *vlan;
3537 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3538 if (vlan->id == id)
3539 return vlan;
3541 vlan = qemu_mallocz(sizeof(VLANState));
3542 if (!vlan)
3543 return NULL;
3544 vlan->id = id;
3545 vlan->next = NULL;
3546 pvlan = &first_vlan;
3547 while (*pvlan != NULL)
3548 pvlan = &(*pvlan)->next;
3549 *pvlan = vlan;
3550 return vlan;
3553 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3554 IOReadHandler *fd_read,
3555 IOCanRWHandler *fd_can_read,
3556 void *opaque)
3558 VLANClientState *vc, **pvc;
3559 vc = qemu_mallocz(sizeof(VLANClientState));
3560 if (!vc)
3561 return NULL;
3562 vc->fd_read = fd_read;
3563 vc->fd_can_read = fd_can_read;
3564 vc->opaque = opaque;
3565 vc->vlan = vlan;
3567 vc->next = NULL;
3568 pvc = &vlan->first_client;
3569 while (*pvc != NULL)
3570 pvc = &(*pvc)->next;
3571 *pvc = vc;
3572 return vc;
3575 int qemu_can_send_packet(VLANClientState *vc1)
3577 VLANState *vlan = vc1->vlan;
3578 VLANClientState *vc;
3580 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3581 if (vc != vc1) {
3582 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3583 return 1;
3586 return 0;
3589 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3591 VLANState *vlan = vc1->vlan;
3592 VLANClientState *vc;
3594 #if 0
3595 printf("vlan %d send:\n", vlan->id);
3596 hex_dump(stdout, buf, size);
3597 #endif
3598 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3599 if (vc != vc1) {
3600 vc->fd_read(vc->opaque, buf, size);
3605 #if defined(CONFIG_SLIRP)
3607 /* slirp network adapter */
3609 static int slirp_inited;
3610 static VLANClientState *slirp_vc;
3612 int slirp_can_output(void)
3614 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3617 void slirp_output(const uint8_t *pkt, int pkt_len)
3619 #if 0
3620 printf("slirp output:\n");
3621 hex_dump(stdout, pkt, pkt_len);
3622 #endif
3623 if (!slirp_vc)
3624 return;
3625 qemu_send_packet(slirp_vc, pkt, pkt_len);
3628 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3630 #if 0
3631 printf("slirp input:\n");
3632 hex_dump(stdout, buf, size);
3633 #endif
3634 slirp_input(buf, size);
3637 static int net_slirp_init(VLANState *vlan)
3639 if (!slirp_inited) {
3640 slirp_inited = 1;
3641 slirp_init();
3643 slirp_vc = qemu_new_vlan_client(vlan,
3644 slirp_receive, NULL, NULL);
3645 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3646 return 0;
3649 static void net_slirp_redir(const char *redir_str)
3651 int is_udp;
3652 char buf[256], *r;
3653 const char *p;
3654 struct in_addr guest_addr;
3655 int host_port, guest_port;
3657 if (!slirp_inited) {
3658 slirp_inited = 1;
3659 slirp_init();
3662 p = redir_str;
3663 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3664 goto fail;
3665 if (!strcmp(buf, "tcp")) {
3666 is_udp = 0;
3667 } else if (!strcmp(buf, "udp")) {
3668 is_udp = 1;
3669 } else {
3670 goto fail;
3673 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3674 goto fail;
3675 host_port = strtol(buf, &r, 0);
3676 if (r == buf)
3677 goto fail;
3679 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3680 goto fail;
3681 if (buf[0] == '\0') {
3682 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3684 if (!inet_aton(buf, &guest_addr))
3685 goto fail;
3687 guest_port = strtol(p, &r, 0);
3688 if (r == p)
3689 goto fail;
3691 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3692 fprintf(stderr, "qemu: could not set up redirection\n");
3693 exit(1);
3695 return;
3696 fail:
3697 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3698 exit(1);
3701 #ifndef _WIN32
3703 char smb_dir[1024];
3705 static void smb_exit(void)
3707 DIR *d;
3708 struct dirent *de;
3709 char filename[1024];
3711 /* erase all the files in the directory */
3712 d = opendir(smb_dir);
3713 for(;;) {
3714 de = readdir(d);
3715 if (!de)
3716 break;
3717 if (strcmp(de->d_name, ".") != 0 &&
3718 strcmp(de->d_name, "..") != 0) {
3719 snprintf(filename, sizeof(filename), "%s/%s",
3720 smb_dir, de->d_name);
3721 unlink(filename);
3724 closedir(d);
3725 rmdir(smb_dir);
3728 /* automatic user mode samba server configuration */
3729 void net_slirp_smb(const char *exported_dir)
3731 char smb_conf[1024];
3732 char smb_cmdline[1024];
3733 FILE *f;
3735 if (!slirp_inited) {
3736 slirp_inited = 1;
3737 slirp_init();
3740 /* XXX: better tmp dir construction */
3741 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3742 if (mkdir(smb_dir, 0700) < 0) {
3743 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3744 exit(1);
3746 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3748 f = fopen(smb_conf, "w");
3749 if (!f) {
3750 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3751 exit(1);
3753 fprintf(f,
3754 "[global]\n"
3755 "private dir=%s\n"
3756 "smb ports=0\n"
3757 "socket address=127.0.0.1\n"
3758 "pid directory=%s\n"
3759 "lock directory=%s\n"
3760 "log file=%s/log.smbd\n"
3761 "smb passwd file=%s/smbpasswd\n"
3762 "security = share\n"
3763 "[qemu]\n"
3764 "path=%s\n"
3765 "read only=no\n"
3766 "guest ok=yes\n",
3767 smb_dir,
3768 smb_dir,
3769 smb_dir,
3770 smb_dir,
3771 smb_dir,
3772 exported_dir
3774 fclose(f);
3775 atexit(smb_exit);
3777 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3778 SMBD_COMMAND, smb_conf);
3780 slirp_add_exec(0, smb_cmdline, 4, 139);
3783 #endif /* !defined(_WIN32) */
3785 #endif /* CONFIG_SLIRP */
3787 #if !defined(_WIN32)
3789 typedef struct TAPState {
3790 VLANClientState *vc;
3791 int fd;
3792 } TAPState;
3794 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3796 TAPState *s = opaque;
3797 int ret;
3798 for(;;) {
3799 ret = write(s->fd, buf, size);
3800 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3801 } else {
3802 break;
3807 static void tap_send(void *opaque)
3809 TAPState *s = opaque;
3810 uint8_t buf[4096];
3811 int size;
3813 #ifdef __sun__
3814 struct strbuf sbuf;
3815 int f = 0;
3816 sbuf.maxlen = sizeof(buf);
3817 sbuf.buf = buf;
3818 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3819 #else
3820 size = read(s->fd, buf, sizeof(buf));
3821 #endif
3822 if (size > 0) {
3823 qemu_send_packet(s->vc, buf, size);
3827 /* fd support */
3829 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3831 TAPState *s;
3833 s = qemu_mallocz(sizeof(TAPState));
3834 if (!s)
3835 return NULL;
3836 s->fd = fd;
3837 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3838 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3839 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3840 return s;
3843 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3844 static int tap_open(char *ifname, int ifname_size)
3846 int fd;
3847 char *dev;
3848 struct stat s;
3850 TFR(fd = open("/dev/tap", O_RDWR));
3851 if (fd < 0) {
3852 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3853 return -1;
3856 fstat(fd, &s);
3857 dev = devname(s.st_rdev, S_IFCHR);
3858 pstrcpy(ifname, ifname_size, dev);
3860 fcntl(fd, F_SETFL, O_NONBLOCK);
3861 return fd;
3863 #elif defined(__sun__)
3864 #define TUNNEWPPA (('T'<<16) | 0x0001)
3866 * Allocate TAP device, returns opened fd.
3867 * Stores dev name in the first arg(must be large enough).
3869 int tap_alloc(char *dev)
3871 int tap_fd, if_fd, ppa = -1;
3872 static int ip_fd = 0;
3873 char *ptr;
3875 static int arp_fd = 0;
3876 int ip_muxid, arp_muxid;
3877 struct strioctl strioc_if, strioc_ppa;
3878 int link_type = I_PLINK;;
3879 struct lifreq ifr;
3880 char actual_name[32] = "";
3882 memset(&ifr, 0x0, sizeof(ifr));
3884 if( *dev ){
3885 ptr = dev;
3886 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3887 ppa = atoi(ptr);
3890 /* Check if IP device was opened */
3891 if( ip_fd )
3892 close(ip_fd);
3894 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3895 if (ip_fd < 0) {
3896 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3897 return -1;
3900 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3901 if (tap_fd < 0) {
3902 syslog(LOG_ERR, "Can't open /dev/tap");
3903 return -1;
3906 /* Assign a new PPA and get its unit number. */
3907 strioc_ppa.ic_cmd = TUNNEWPPA;
3908 strioc_ppa.ic_timout = 0;
3909 strioc_ppa.ic_len = sizeof(ppa);
3910 strioc_ppa.ic_dp = (char *)&ppa;
3911 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3912 syslog (LOG_ERR, "Can't assign new interface");
3914 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3915 if (if_fd < 0) {
3916 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3917 return -1;
3919 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3920 syslog(LOG_ERR, "Can't push IP module");
3921 return -1;
3924 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3925 syslog(LOG_ERR, "Can't get flags\n");
3927 snprintf (actual_name, 32, "tap%d", ppa);
3928 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3930 ifr.lifr_ppa = ppa;
3931 /* Assign ppa according to the unit number returned by tun device */
3933 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3934 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3935 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3936 syslog (LOG_ERR, "Can't get flags\n");
3937 /* Push arp module to if_fd */
3938 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3939 syslog (LOG_ERR, "Can't push ARP module (2)");
3941 /* Push arp module to ip_fd */
3942 if (ioctl (ip_fd, I_POP, NULL) < 0)
3943 syslog (LOG_ERR, "I_POP failed\n");
3944 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3945 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3946 /* Open arp_fd */
3947 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3948 if (arp_fd < 0)
3949 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3951 /* Set ifname to arp */
3952 strioc_if.ic_cmd = SIOCSLIFNAME;
3953 strioc_if.ic_timout = 0;
3954 strioc_if.ic_len = sizeof(ifr);
3955 strioc_if.ic_dp = (char *)&ifr;
3956 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3957 syslog (LOG_ERR, "Can't set ifname to arp\n");
3960 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3961 syslog(LOG_ERR, "Can't link TAP device to IP");
3962 return -1;
3965 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3966 syslog (LOG_ERR, "Can't link TAP device to ARP");
3968 close (if_fd);
3970 memset(&ifr, 0x0, sizeof(ifr));
3971 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3972 ifr.lifr_ip_muxid = ip_muxid;
3973 ifr.lifr_arp_muxid = arp_muxid;
3975 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3977 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3978 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3979 syslog (LOG_ERR, "Can't set multiplexor id");
3982 sprintf(dev, "tap%d", ppa);
3983 return tap_fd;
3986 static int tap_open(char *ifname, int ifname_size)
3988 char dev[10]="";
3989 int fd;
3990 if( (fd = tap_alloc(dev)) < 0 ){
3991 fprintf(stderr, "Cannot allocate TAP device\n");
3992 return -1;
3994 pstrcpy(ifname, ifname_size, dev);
3995 fcntl(fd, F_SETFL, O_NONBLOCK);
3996 return fd;
3998 #else
3999 static int tap_open(char *ifname, int ifname_size)
4001 struct ifreq ifr;
4002 int fd, ret;
4004 TFR(fd = open("/dev/net/tun", O_RDWR));
4005 if (fd < 0) {
4006 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4007 return -1;
4009 memset(&ifr, 0, sizeof(ifr));
4010 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4011 if (ifname[0] != '\0')
4012 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4013 else
4014 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4015 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4016 if (ret != 0) {
4017 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4018 close(fd);
4019 return -1;
4021 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4022 fcntl(fd, F_SETFL, O_NONBLOCK);
4023 return fd;
4025 #endif
4027 static int net_tap_init(VLANState *vlan, const char *ifname1,
4028 const char *setup_script)
4030 TAPState *s;
4031 int pid, status, fd;
4032 char *args[3];
4033 char **parg;
4034 char ifname[128];
4036 if (ifname1 != NULL)
4037 pstrcpy(ifname, sizeof(ifname), ifname1);
4038 else
4039 ifname[0] = '\0';
4040 TFR(fd = tap_open(ifname, sizeof(ifname)));
4041 if (fd < 0)
4042 return -1;
4044 if (!setup_script || !strcmp(setup_script, "no"))
4045 setup_script = "";
4046 if (setup_script[0] != '\0') {
4047 /* try to launch network init script */
4048 pid = fork();
4049 if (pid >= 0) {
4050 if (pid == 0) {
4051 int open_max = sysconf (_SC_OPEN_MAX), i;
4052 for (i = 0; i < open_max; i++)
4053 if (i != STDIN_FILENO &&
4054 i != STDOUT_FILENO &&
4055 i != STDERR_FILENO &&
4056 i != fd)
4057 close(i);
4059 parg = args;
4060 *parg++ = (char *)setup_script;
4061 *parg++ = ifname;
4062 *parg++ = NULL;
4063 execv(setup_script, args);
4064 _exit(1);
4066 while (waitpid(pid, &status, 0) != pid);
4067 if (!WIFEXITED(status) ||
4068 WEXITSTATUS(status) != 0) {
4069 fprintf(stderr, "%s: could not launch network script\n",
4070 setup_script);
4071 return -1;
4075 s = net_tap_fd_init(vlan, fd);
4076 if (!s)
4077 return -1;
4078 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4079 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4080 return 0;
4083 #endif /* !_WIN32 */
4085 /* network connection */
4086 typedef struct NetSocketState {
4087 VLANClientState *vc;
4088 int fd;
4089 int state; /* 0 = getting length, 1 = getting data */
4090 int index;
4091 int packet_len;
4092 uint8_t buf[4096];
4093 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4094 } NetSocketState;
4096 typedef struct NetSocketListenState {
4097 VLANState *vlan;
4098 int fd;
4099 } NetSocketListenState;
4101 /* XXX: we consider we can send the whole packet without blocking */
4102 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4104 NetSocketState *s = opaque;
4105 uint32_t len;
4106 len = htonl(size);
4108 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4109 send_all(s->fd, buf, size);
4112 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4114 NetSocketState *s = opaque;
4115 sendto(s->fd, buf, size, 0,
4116 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4119 static void net_socket_send(void *opaque)
4121 NetSocketState *s = opaque;
4122 int l, size, err;
4123 uint8_t buf1[4096];
4124 const uint8_t *buf;
4126 size = recv(s->fd, buf1, sizeof(buf1), 0);
4127 if (size < 0) {
4128 err = socket_error();
4129 if (err != EWOULDBLOCK)
4130 goto eoc;
4131 } else if (size == 0) {
4132 /* end of connection */
4133 eoc:
4134 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4135 closesocket(s->fd);
4136 return;
4138 buf = buf1;
4139 while (size > 0) {
4140 /* reassemble a packet from the network */
4141 switch(s->state) {
4142 case 0:
4143 l = 4 - s->index;
4144 if (l > size)
4145 l = size;
4146 memcpy(s->buf + s->index, buf, l);
4147 buf += l;
4148 size -= l;
4149 s->index += l;
4150 if (s->index == 4) {
4151 /* got length */
4152 s->packet_len = ntohl(*(uint32_t *)s->buf);
4153 s->index = 0;
4154 s->state = 1;
4156 break;
4157 case 1:
4158 l = s->packet_len - s->index;
4159 if (l > size)
4160 l = size;
4161 memcpy(s->buf + s->index, buf, l);
4162 s->index += l;
4163 buf += l;
4164 size -= l;
4165 if (s->index >= s->packet_len) {
4166 qemu_send_packet(s->vc, s->buf, s->packet_len);
4167 s->index = 0;
4168 s->state = 0;
4170 break;
4175 static void net_socket_send_dgram(void *opaque)
4177 NetSocketState *s = opaque;
4178 int size;
4180 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4181 if (size < 0)
4182 return;
4183 if (size == 0) {
4184 /* end of connection */
4185 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4186 return;
4188 qemu_send_packet(s->vc, s->buf, size);
4191 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4193 struct ip_mreq imr;
4194 int fd;
4195 int val, ret;
4196 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4197 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4198 inet_ntoa(mcastaddr->sin_addr),
4199 (int)ntohl(mcastaddr->sin_addr.s_addr));
4200 return -1;
4203 fd = socket(PF_INET, SOCK_DGRAM, 0);
4204 if (fd < 0) {
4205 perror("socket(PF_INET, SOCK_DGRAM)");
4206 return -1;
4209 val = 1;
4210 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4211 (const char *)&val, sizeof(val));
4212 if (ret < 0) {
4213 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4214 goto fail;
4217 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4218 if (ret < 0) {
4219 perror("bind");
4220 goto fail;
4223 /* Add host to multicast group */
4224 imr.imr_multiaddr = mcastaddr->sin_addr;
4225 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4227 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4228 (const char *)&imr, sizeof(struct ip_mreq));
4229 if (ret < 0) {
4230 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4231 goto fail;
4234 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4235 val = 1;
4236 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4237 (const char *)&val, sizeof(val));
4238 if (ret < 0) {
4239 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4240 goto fail;
4243 socket_set_nonblock(fd);
4244 return fd;
4245 fail:
4246 if (fd >= 0)
4247 closesocket(fd);
4248 return -1;
4251 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4252 int is_connected)
4254 struct sockaddr_in saddr;
4255 int newfd;
4256 socklen_t saddr_len;
4257 NetSocketState *s;
4259 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4260 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4261 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4264 if (is_connected) {
4265 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4266 /* must be bound */
4267 if (saddr.sin_addr.s_addr==0) {
4268 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4269 fd);
4270 return NULL;
4272 /* clone dgram socket */
4273 newfd = net_socket_mcast_create(&saddr);
4274 if (newfd < 0) {
4275 /* error already reported by net_socket_mcast_create() */
4276 close(fd);
4277 return NULL;
4279 /* clone newfd to fd, close newfd */
4280 dup2(newfd, fd);
4281 close(newfd);
4283 } else {
4284 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4285 fd, strerror(errno));
4286 return NULL;
4290 s = qemu_mallocz(sizeof(NetSocketState));
4291 if (!s)
4292 return NULL;
4293 s->fd = fd;
4295 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4296 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4298 /* mcast: save bound address as dst */
4299 if (is_connected) s->dgram_dst=saddr;
4301 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4302 "socket: fd=%d (%s mcast=%s:%d)",
4303 fd, is_connected? "cloned" : "",
4304 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4305 return s;
4308 static void net_socket_connect(void *opaque)
4310 NetSocketState *s = opaque;
4311 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4314 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4315 int is_connected)
4317 NetSocketState *s;
4318 s = qemu_mallocz(sizeof(NetSocketState));
4319 if (!s)
4320 return NULL;
4321 s->fd = fd;
4322 s->vc = qemu_new_vlan_client(vlan,
4323 net_socket_receive, NULL, s);
4324 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4325 "socket: fd=%d", fd);
4326 if (is_connected) {
4327 net_socket_connect(s);
4328 } else {
4329 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4331 return s;
4334 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4335 int is_connected)
4337 int so_type=-1, optlen=sizeof(so_type);
4339 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4340 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4341 return NULL;
4343 switch(so_type) {
4344 case SOCK_DGRAM:
4345 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4346 case SOCK_STREAM:
4347 return net_socket_fd_init_stream(vlan, fd, is_connected);
4348 default:
4349 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4350 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4351 return net_socket_fd_init_stream(vlan, fd, is_connected);
4353 return NULL;
4356 static void net_socket_accept(void *opaque)
4358 NetSocketListenState *s = opaque;
4359 NetSocketState *s1;
4360 struct sockaddr_in saddr;
4361 socklen_t len;
4362 int fd;
4364 for(;;) {
4365 len = sizeof(saddr);
4366 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4367 if (fd < 0 && errno != EINTR) {
4368 return;
4369 } else if (fd >= 0) {
4370 break;
4373 s1 = net_socket_fd_init(s->vlan, fd, 1);
4374 if (!s1) {
4375 closesocket(fd);
4376 } else {
4377 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4378 "socket: connection from %s:%d",
4379 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4383 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4385 NetSocketListenState *s;
4386 int fd, val, ret;
4387 struct sockaddr_in saddr;
4389 if (parse_host_port(&saddr, host_str) < 0)
4390 return -1;
4392 s = qemu_mallocz(sizeof(NetSocketListenState));
4393 if (!s)
4394 return -1;
4396 fd = socket(PF_INET, SOCK_STREAM, 0);
4397 if (fd < 0) {
4398 perror("socket");
4399 return -1;
4401 socket_set_nonblock(fd);
4403 /* allow fast reuse */
4404 val = 1;
4405 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4407 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4408 if (ret < 0) {
4409 perror("bind");
4410 return -1;
4412 ret = listen(fd, 0);
4413 if (ret < 0) {
4414 perror("listen");
4415 return -1;
4417 s->vlan = vlan;
4418 s->fd = fd;
4419 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4420 return 0;
4423 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4425 NetSocketState *s;
4426 int fd, connected, ret, err;
4427 struct sockaddr_in saddr;
4429 if (parse_host_port(&saddr, host_str) < 0)
4430 return -1;
4432 fd = socket(PF_INET, SOCK_STREAM, 0);
4433 if (fd < 0) {
4434 perror("socket");
4435 return -1;
4437 socket_set_nonblock(fd);
4439 connected = 0;
4440 for(;;) {
4441 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4442 if (ret < 0) {
4443 err = socket_error();
4444 if (err == EINTR || err == EWOULDBLOCK) {
4445 } else if (err == EINPROGRESS) {
4446 break;
4447 #ifdef _WIN32
4448 } else if (err == WSAEALREADY) {
4449 break;
4450 #endif
4451 } else {
4452 perror("connect");
4453 closesocket(fd);
4454 return -1;
4456 } else {
4457 connected = 1;
4458 break;
4461 s = net_socket_fd_init(vlan, fd, connected);
4462 if (!s)
4463 return -1;
4464 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4465 "socket: connect to %s:%d",
4466 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4467 return 0;
4470 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4472 NetSocketState *s;
4473 int fd;
4474 struct sockaddr_in saddr;
4476 if (parse_host_port(&saddr, host_str) < 0)
4477 return -1;
4480 fd = net_socket_mcast_create(&saddr);
4481 if (fd < 0)
4482 return -1;
4484 s = net_socket_fd_init(vlan, fd, 0);
4485 if (!s)
4486 return -1;
4488 s->dgram_dst = saddr;
4490 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4491 "socket: mcast=%s:%d",
4492 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4493 return 0;
4497 static int get_param_value(char *buf, int buf_size,
4498 const char *tag, const char *str)
4500 const char *p;
4501 char *q;
4502 char option[128];
4504 p = str;
4505 for(;;) {
4506 q = option;
4507 while (*p != '\0' && *p != '=') {
4508 if ((q - option) < sizeof(option) - 1)
4509 *q++ = *p;
4510 p++;
4512 *q = '\0';
4513 if (*p != '=')
4514 break;
4515 p++;
4516 if (!strcmp(tag, option)) {
4517 q = buf;
4518 while (*p != '\0' && *p != ',') {
4519 if ((q - buf) < buf_size - 1)
4520 *q++ = *p;
4521 p++;
4523 *q = '\0';
4524 return q - buf;
4525 } else {
4526 while (*p != '\0' && *p != ',') {
4527 p++;
4530 if (*p != ',')
4531 break;
4532 p++;
4534 return 0;
4537 static int net_client_init(const char *str)
4539 const char *p;
4540 char *q;
4541 char device[64];
4542 char buf[1024];
4543 int vlan_id, ret;
4544 VLANState *vlan;
4546 p = str;
4547 q = device;
4548 while (*p != '\0' && *p != ',') {
4549 if ((q - device) < sizeof(device) - 1)
4550 *q++ = *p;
4551 p++;
4553 *q = '\0';
4554 if (*p == ',')
4555 p++;
4556 vlan_id = 0;
4557 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4558 vlan_id = strtol(buf, NULL, 0);
4560 vlan = qemu_find_vlan(vlan_id);
4561 if (!vlan) {
4562 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4563 return -1;
4565 if (!strcmp(device, "nic")) {
4566 NICInfo *nd;
4567 uint8_t *macaddr;
4569 if (nb_nics >= MAX_NICS) {
4570 fprintf(stderr, "Too Many NICs\n");
4571 return -1;
4573 nd = &nd_table[nb_nics];
4574 macaddr = nd->macaddr;
4575 macaddr[0] = 0x52;
4576 macaddr[1] = 0x54;
4577 macaddr[2] = 0x00;
4578 macaddr[3] = 0x12;
4579 macaddr[4] = 0x34;
4580 macaddr[5] = 0x56 + nb_nics;
4582 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4583 if (parse_macaddr(macaddr, buf) < 0) {
4584 fprintf(stderr, "invalid syntax for ethernet address\n");
4585 return -1;
4588 if (get_param_value(buf, sizeof(buf), "model", p)) {
4589 nd->model = strdup(buf);
4591 nd->vlan = vlan;
4592 nb_nics++;
4593 vlan->nb_guest_devs++;
4594 ret = 0;
4595 } else
4596 if (!strcmp(device, "none")) {
4597 /* does nothing. It is needed to signal that no network cards
4598 are wanted */
4599 ret = 0;
4600 } else
4601 #ifdef CONFIG_SLIRP
4602 if (!strcmp(device, "user")) {
4603 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4604 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4606 vlan->nb_host_devs++;
4607 ret = net_slirp_init(vlan);
4608 } else
4609 #endif
4610 #ifdef _WIN32
4611 if (!strcmp(device, "tap")) {
4612 char ifname[64];
4613 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4614 fprintf(stderr, "tap: no interface name\n");
4615 return -1;
4617 vlan->nb_host_devs++;
4618 ret = tap_win32_init(vlan, ifname);
4619 } else
4620 #else
4621 if (!strcmp(device, "tap")) {
4622 char ifname[64];
4623 char setup_script[1024];
4624 int fd;
4625 vlan->nb_host_devs++;
4626 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4627 fd = strtol(buf, NULL, 0);
4628 ret = -1;
4629 if (net_tap_fd_init(vlan, fd))
4630 ret = 0;
4631 } else {
4632 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4633 ifname[0] = '\0';
4635 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4636 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4638 ret = net_tap_init(vlan, ifname, setup_script);
4640 } else
4641 #endif
4642 if (!strcmp(device, "socket")) {
4643 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4644 int fd;
4645 fd = strtol(buf, NULL, 0);
4646 ret = -1;
4647 if (net_socket_fd_init(vlan, fd, 1))
4648 ret = 0;
4649 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4650 ret = net_socket_listen_init(vlan, buf);
4651 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4652 ret = net_socket_connect_init(vlan, buf);
4653 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4654 ret = net_socket_mcast_init(vlan, buf);
4655 } else {
4656 fprintf(stderr, "Unknown socket options: %s\n", p);
4657 return -1;
4659 vlan->nb_host_devs++;
4660 } else
4662 fprintf(stderr, "Unknown network device: %s\n", device);
4663 return -1;
4665 if (ret < 0) {
4666 fprintf(stderr, "Could not initialize device '%s'\n", device);
4669 return ret;
4672 void do_info_network(void)
4674 VLANState *vlan;
4675 VLANClientState *vc;
4677 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4678 term_printf("VLAN %d devices:\n", vlan->id);
4679 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4680 term_printf(" %s\n", vc->info_str);
4684 /***********************************************************/
4685 /* USB devices */
4687 static USBPort *used_usb_ports;
4688 static USBPort *free_usb_ports;
4690 /* ??? Maybe change this to register a hub to keep track of the topology. */
4691 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4692 usb_attachfn attach)
4694 port->opaque = opaque;
4695 port->index = index;
4696 port->attach = attach;
4697 port->next = free_usb_ports;
4698 free_usb_ports = port;
4701 static int usb_device_add(const char *devname)
4703 const char *p;
4704 USBDevice *dev;
4705 USBPort *port;
4707 if (!free_usb_ports)
4708 return -1;
4710 if (strstart(devname, "host:", &p)) {
4711 dev = usb_host_device_open(p);
4712 } else if (!strcmp(devname, "mouse")) {
4713 dev = usb_mouse_init();
4714 } else if (!strcmp(devname, "tablet")) {
4715 dev = usb_tablet_init();
4716 } else if (!strcmp(devname, "keyboard")) {
4717 dev = usb_keyboard_init();
4718 } else if (strstart(devname, "disk:", &p)) {
4719 dev = usb_msd_init(p);
4720 } else if (!strcmp(devname, "wacom-tablet")) {
4721 dev = usb_wacom_init();
4722 } else {
4723 return -1;
4725 if (!dev)
4726 return -1;
4728 /* Find a USB port to add the device to. */
4729 port = free_usb_ports;
4730 if (!port->next) {
4731 USBDevice *hub;
4733 /* Create a new hub and chain it on. */
4734 free_usb_ports = NULL;
4735 port->next = used_usb_ports;
4736 used_usb_ports = port;
4738 hub = usb_hub_init(VM_USB_HUB_SIZE);
4739 usb_attach(port, hub);
4740 port = free_usb_ports;
4743 free_usb_ports = port->next;
4744 port->next = used_usb_ports;
4745 used_usb_ports = port;
4746 usb_attach(port, dev);
4747 return 0;
4750 static int usb_device_del(const char *devname)
4752 USBPort *port;
4753 USBPort **lastp;
4754 USBDevice *dev;
4755 int bus_num, addr;
4756 const char *p;
4758 if (!used_usb_ports)
4759 return -1;
4761 p = strchr(devname, '.');
4762 if (!p)
4763 return -1;
4764 bus_num = strtoul(devname, NULL, 0);
4765 addr = strtoul(p + 1, NULL, 0);
4766 if (bus_num != 0)
4767 return -1;
4769 lastp = &used_usb_ports;
4770 port = used_usb_ports;
4771 while (port && port->dev->addr != addr) {
4772 lastp = &port->next;
4773 port = port->next;
4776 if (!port)
4777 return -1;
4779 dev = port->dev;
4780 *lastp = port->next;
4781 usb_attach(port, NULL);
4782 dev->handle_destroy(dev);
4783 port->next = free_usb_ports;
4784 free_usb_ports = port;
4785 return 0;
4788 void do_usb_add(const char *devname)
4790 int ret;
4791 ret = usb_device_add(devname);
4792 if (ret < 0)
4793 term_printf("Could not add USB device '%s'\n", devname);
4796 void do_usb_del(const char *devname)
4798 int ret;
4799 ret = usb_device_del(devname);
4800 if (ret < 0)
4801 term_printf("Could not remove USB device '%s'\n", devname);
4804 void usb_info(void)
4806 USBDevice *dev;
4807 USBPort *port;
4808 const char *speed_str;
4810 if (!usb_enabled) {
4811 term_printf("USB support not enabled\n");
4812 return;
4815 for (port = used_usb_ports; port; port = port->next) {
4816 dev = port->dev;
4817 if (!dev)
4818 continue;
4819 switch(dev->speed) {
4820 case USB_SPEED_LOW:
4821 speed_str = "1.5";
4822 break;
4823 case USB_SPEED_FULL:
4824 speed_str = "12";
4825 break;
4826 case USB_SPEED_HIGH:
4827 speed_str = "480";
4828 break;
4829 default:
4830 speed_str = "?";
4831 break;
4833 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4834 0, dev->addr, speed_str, dev->devname);
4838 /***********************************************************/
4839 /* PCMCIA/Cardbus */
4841 static struct pcmcia_socket_entry_s {
4842 struct pcmcia_socket_s *socket;
4843 struct pcmcia_socket_entry_s *next;
4844 } *pcmcia_sockets = 0;
4846 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4848 struct pcmcia_socket_entry_s *entry;
4850 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4851 entry->socket = socket;
4852 entry->next = pcmcia_sockets;
4853 pcmcia_sockets = entry;
4856 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4858 struct pcmcia_socket_entry_s *entry, **ptr;
4860 ptr = &pcmcia_sockets;
4861 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4862 if (entry->socket == socket) {
4863 *ptr = entry->next;
4864 qemu_free(entry);
4868 void pcmcia_info(void)
4870 struct pcmcia_socket_entry_s *iter;
4871 if (!pcmcia_sockets)
4872 term_printf("No PCMCIA sockets\n");
4874 for (iter = pcmcia_sockets; iter; iter = iter->next)
4875 term_printf("%s: %s\n", iter->socket->slot_string,
4876 iter->socket->attached ? iter->socket->card_string :
4877 "Empty");
4880 /***********************************************************/
4881 /* dumb display */
4883 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4887 static void dumb_resize(DisplayState *ds, int w, int h)
4891 static void dumb_refresh(DisplayState *ds)
4893 #if defined(CONFIG_SDL)
4894 vga_hw_update();
4895 #endif
4898 static void dumb_display_init(DisplayState *ds)
4900 ds->data = NULL;
4901 ds->linesize = 0;
4902 ds->depth = 0;
4903 ds->dpy_update = dumb_update;
4904 ds->dpy_resize = dumb_resize;
4905 ds->dpy_refresh = dumb_refresh;
4908 /***********************************************************/
4909 /* I/O handling */
4911 #define MAX_IO_HANDLERS 64
4913 typedef struct IOHandlerRecord {
4914 int fd;
4915 IOCanRWHandler *fd_read_poll;
4916 IOHandler *fd_read;
4917 IOHandler *fd_write;
4918 int deleted;
4919 void *opaque;
4920 /* temporary data */
4921 struct pollfd *ufd;
4922 struct IOHandlerRecord *next;
4923 } IOHandlerRecord;
4925 static IOHandlerRecord *first_io_handler;
4927 /* XXX: fd_read_poll should be suppressed, but an API change is
4928 necessary in the character devices to suppress fd_can_read(). */
4929 int qemu_set_fd_handler2(int fd,
4930 IOCanRWHandler *fd_read_poll,
4931 IOHandler *fd_read,
4932 IOHandler *fd_write,
4933 void *opaque)
4935 IOHandlerRecord **pioh, *ioh;
4937 if (!fd_read && !fd_write) {
4938 pioh = &first_io_handler;
4939 for(;;) {
4940 ioh = *pioh;
4941 if (ioh == NULL)
4942 break;
4943 if (ioh->fd == fd) {
4944 ioh->deleted = 1;
4945 break;
4947 pioh = &ioh->next;
4949 } else {
4950 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4951 if (ioh->fd == fd)
4952 goto found;
4954 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4955 if (!ioh)
4956 return -1;
4957 ioh->next = first_io_handler;
4958 first_io_handler = ioh;
4959 found:
4960 ioh->fd = fd;
4961 ioh->fd_read_poll = fd_read_poll;
4962 ioh->fd_read = fd_read;
4963 ioh->fd_write = fd_write;
4964 ioh->opaque = opaque;
4965 ioh->deleted = 0;
4967 return 0;
4970 int qemu_set_fd_handler(int fd,
4971 IOHandler *fd_read,
4972 IOHandler *fd_write,
4973 void *opaque)
4975 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4978 /***********************************************************/
4979 /* Polling handling */
4981 typedef struct PollingEntry {
4982 PollingFunc *func;
4983 void *opaque;
4984 struct PollingEntry *next;
4985 } PollingEntry;
4987 static PollingEntry *first_polling_entry;
4989 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4991 PollingEntry **ppe, *pe;
4992 pe = qemu_mallocz(sizeof(PollingEntry));
4993 if (!pe)
4994 return -1;
4995 pe->func = func;
4996 pe->opaque = opaque;
4997 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4998 *ppe = pe;
4999 return 0;
5002 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5004 PollingEntry **ppe, *pe;
5005 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5006 pe = *ppe;
5007 if (pe->func == func && pe->opaque == opaque) {
5008 *ppe = pe->next;
5009 qemu_free(pe);
5010 break;
5015 #ifdef _WIN32
5016 /***********************************************************/
5017 /* Wait objects support */
5018 typedef struct WaitObjects {
5019 int num;
5020 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5021 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5022 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5023 } WaitObjects;
5025 static WaitObjects wait_objects = {0};
5027 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5029 WaitObjects *w = &wait_objects;
5031 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5032 return -1;
5033 w->events[w->num] = handle;
5034 w->func[w->num] = func;
5035 w->opaque[w->num] = opaque;
5036 w->num++;
5037 return 0;
5040 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5042 int i, found;
5043 WaitObjects *w = &wait_objects;
5045 found = 0;
5046 for (i = 0; i < w->num; i++) {
5047 if (w->events[i] == handle)
5048 found = 1;
5049 if (found) {
5050 w->events[i] = w->events[i + 1];
5051 w->func[i] = w->func[i + 1];
5052 w->opaque[i] = w->opaque[i + 1];
5055 if (found)
5056 w->num--;
5058 #endif
5060 /***********************************************************/
5061 /* savevm/loadvm support */
5063 #define IO_BUF_SIZE 32768
5065 struct QEMUFile {
5066 FILE *outfile;
5067 BlockDriverState *bs;
5068 int is_file;
5069 int is_writable;
5070 int64_t base_offset;
5071 int64_t buf_offset; /* start of buffer when writing, end of buffer
5072 when reading */
5073 int buf_index;
5074 int buf_size; /* 0 when writing */
5075 uint8_t buf[IO_BUF_SIZE];
5078 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5080 QEMUFile *f;
5082 f = qemu_mallocz(sizeof(QEMUFile));
5083 if (!f)
5084 return NULL;
5085 if (!strcmp(mode, "wb")) {
5086 f->is_writable = 1;
5087 } else if (!strcmp(mode, "rb")) {
5088 f->is_writable = 0;
5089 } else {
5090 goto fail;
5092 f->outfile = fopen(filename, mode);
5093 if (!f->outfile)
5094 goto fail;
5095 f->is_file = 1;
5096 return f;
5097 fail:
5098 if (f->outfile)
5099 fclose(f->outfile);
5100 qemu_free(f);
5101 return NULL;
5104 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5106 QEMUFile *f;
5108 f = qemu_mallocz(sizeof(QEMUFile));
5109 if (!f)
5110 return NULL;
5111 f->is_file = 0;
5112 f->bs = bs;
5113 f->is_writable = is_writable;
5114 f->base_offset = offset;
5115 return f;
5118 void qemu_fflush(QEMUFile *f)
5120 if (!f->is_writable)
5121 return;
5122 if (f->buf_index > 0) {
5123 if (f->is_file) {
5124 fseek(f->outfile, f->buf_offset, SEEK_SET);
5125 fwrite(f->buf, 1, f->buf_index, f->outfile);
5126 } else {
5127 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5128 f->buf, f->buf_index);
5130 f->buf_offset += f->buf_index;
5131 f->buf_index = 0;
5135 static void qemu_fill_buffer(QEMUFile *f)
5137 int len;
5139 if (f->is_writable)
5140 return;
5141 if (f->is_file) {
5142 fseek(f->outfile, f->buf_offset, SEEK_SET);
5143 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5144 if (len < 0)
5145 len = 0;
5146 } else {
5147 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5148 f->buf, IO_BUF_SIZE);
5149 if (len < 0)
5150 len = 0;
5152 f->buf_index = 0;
5153 f->buf_size = len;
5154 f->buf_offset += len;
5157 void qemu_fclose(QEMUFile *f)
5159 if (f->is_writable)
5160 qemu_fflush(f);
5161 if (f->is_file) {
5162 fclose(f->outfile);
5164 qemu_free(f);
5167 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5169 int l;
5170 while (size > 0) {
5171 l = IO_BUF_SIZE - f->buf_index;
5172 if (l > size)
5173 l = size;
5174 memcpy(f->buf + f->buf_index, buf, l);
5175 f->buf_index += l;
5176 buf += l;
5177 size -= l;
5178 if (f->buf_index >= IO_BUF_SIZE)
5179 qemu_fflush(f);
5183 void qemu_put_byte(QEMUFile *f, int v)
5185 f->buf[f->buf_index++] = v;
5186 if (f->buf_index >= IO_BUF_SIZE)
5187 qemu_fflush(f);
5190 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5192 int size, l;
5194 size = size1;
5195 while (size > 0) {
5196 l = f->buf_size - f->buf_index;
5197 if (l == 0) {
5198 qemu_fill_buffer(f);
5199 l = f->buf_size - f->buf_index;
5200 if (l == 0)
5201 break;
5203 if (l > size)
5204 l = size;
5205 memcpy(buf, f->buf + f->buf_index, l);
5206 f->buf_index += l;
5207 buf += l;
5208 size -= l;
5210 return size1 - size;
5213 int qemu_get_byte(QEMUFile *f)
5215 if (f->buf_index >= f->buf_size) {
5216 qemu_fill_buffer(f);
5217 if (f->buf_index >= f->buf_size)
5218 return 0;
5220 return f->buf[f->buf_index++];
5223 int64_t qemu_ftell(QEMUFile *f)
5225 return f->buf_offset - f->buf_size + f->buf_index;
5228 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5230 if (whence == SEEK_SET) {
5231 /* nothing to do */
5232 } else if (whence == SEEK_CUR) {
5233 pos += qemu_ftell(f);
5234 } else {
5235 /* SEEK_END not supported */
5236 return -1;
5238 if (f->is_writable) {
5239 qemu_fflush(f);
5240 f->buf_offset = pos;
5241 } else {
5242 f->buf_offset = pos;
5243 f->buf_index = 0;
5244 f->buf_size = 0;
5246 return pos;
5249 void qemu_put_be16(QEMUFile *f, unsigned int v)
5251 qemu_put_byte(f, v >> 8);
5252 qemu_put_byte(f, v);
5255 void qemu_put_be32(QEMUFile *f, unsigned int v)
5257 qemu_put_byte(f, v >> 24);
5258 qemu_put_byte(f, v >> 16);
5259 qemu_put_byte(f, v >> 8);
5260 qemu_put_byte(f, v);
5263 void qemu_put_be64(QEMUFile *f, uint64_t v)
5265 qemu_put_be32(f, v >> 32);
5266 qemu_put_be32(f, v);
5269 unsigned int qemu_get_be16(QEMUFile *f)
5271 unsigned int v;
5272 v = qemu_get_byte(f) << 8;
5273 v |= qemu_get_byte(f);
5274 return v;
5277 unsigned int qemu_get_be32(QEMUFile *f)
5279 unsigned int v;
5280 v = qemu_get_byte(f) << 24;
5281 v |= qemu_get_byte(f) << 16;
5282 v |= qemu_get_byte(f) << 8;
5283 v |= qemu_get_byte(f);
5284 return v;
5287 uint64_t qemu_get_be64(QEMUFile *f)
5289 uint64_t v;
5290 v = (uint64_t)qemu_get_be32(f) << 32;
5291 v |= qemu_get_be32(f);
5292 return v;
5295 typedef struct SaveStateEntry {
5296 char idstr[256];
5297 int instance_id;
5298 int version_id;
5299 SaveStateHandler *save_state;
5300 LoadStateHandler *load_state;
5301 void *opaque;
5302 struct SaveStateEntry *next;
5303 } SaveStateEntry;
5305 static SaveStateEntry *first_se;
5307 int register_savevm(const char *idstr,
5308 int instance_id,
5309 int version_id,
5310 SaveStateHandler *save_state,
5311 LoadStateHandler *load_state,
5312 void *opaque)
5314 SaveStateEntry *se, **pse;
5316 se = qemu_malloc(sizeof(SaveStateEntry));
5317 if (!se)
5318 return -1;
5319 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5320 se->instance_id = instance_id;
5321 se->version_id = version_id;
5322 se->save_state = save_state;
5323 se->load_state = load_state;
5324 se->opaque = opaque;
5325 se->next = NULL;
5327 /* add at the end of list */
5328 pse = &first_se;
5329 while (*pse != NULL)
5330 pse = &(*pse)->next;
5331 *pse = se;
5332 return 0;
5335 #define QEMU_VM_FILE_MAGIC 0x5145564d
5336 #define QEMU_VM_FILE_VERSION 0x00000002
5338 int qemu_savevm_state(QEMUFile *f)
5340 SaveStateEntry *se;
5341 int len, ret;
5342 int64_t cur_pos, len_pos, total_len_pos;
5344 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5345 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5346 total_len_pos = qemu_ftell(f);
5347 qemu_put_be64(f, 0); /* total size */
5349 for(se = first_se; se != NULL; se = se->next) {
5350 /* ID string */
5351 len = strlen(se->idstr);
5352 qemu_put_byte(f, len);
5353 qemu_put_buffer(f, se->idstr, len);
5355 qemu_put_be32(f, se->instance_id);
5356 qemu_put_be32(f, se->version_id);
5358 /* record size: filled later */
5359 len_pos = qemu_ftell(f);
5360 qemu_put_be32(f, 0);
5362 se->save_state(f, se->opaque);
5364 /* fill record size */
5365 cur_pos = qemu_ftell(f);
5366 len = cur_pos - len_pos - 4;
5367 qemu_fseek(f, len_pos, SEEK_SET);
5368 qemu_put_be32(f, len);
5369 qemu_fseek(f, cur_pos, SEEK_SET);
5371 cur_pos = qemu_ftell(f);
5372 qemu_fseek(f, total_len_pos, SEEK_SET);
5373 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5374 qemu_fseek(f, cur_pos, SEEK_SET);
5376 ret = 0;
5377 return ret;
5380 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5382 SaveStateEntry *se;
5384 for(se = first_se; se != NULL; se = se->next) {
5385 if (!strcmp(se->idstr, idstr) &&
5386 instance_id == se->instance_id)
5387 return se;
5389 return NULL;
5392 int qemu_loadvm_state(QEMUFile *f)
5394 SaveStateEntry *se;
5395 int len, ret, instance_id, record_len, version_id;
5396 int64_t total_len, end_pos, cur_pos;
5397 unsigned int v;
5398 char idstr[256];
5400 v = qemu_get_be32(f);
5401 if (v != QEMU_VM_FILE_MAGIC)
5402 goto fail;
5403 v = qemu_get_be32(f);
5404 if (v != QEMU_VM_FILE_VERSION) {
5405 fail:
5406 ret = -1;
5407 goto the_end;
5409 total_len = qemu_get_be64(f);
5410 end_pos = total_len + qemu_ftell(f);
5411 for(;;) {
5412 if (qemu_ftell(f) >= end_pos)
5413 break;
5414 len = qemu_get_byte(f);
5415 qemu_get_buffer(f, idstr, len);
5416 idstr[len] = '\0';
5417 instance_id = qemu_get_be32(f);
5418 version_id = qemu_get_be32(f);
5419 record_len = qemu_get_be32(f);
5420 #if 0
5421 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5422 idstr, instance_id, version_id, record_len);
5423 #endif
5424 cur_pos = qemu_ftell(f);
5425 se = find_se(idstr, instance_id);
5426 if (!se) {
5427 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5428 instance_id, idstr);
5429 } else {
5430 ret = se->load_state(f, se->opaque, version_id);
5431 if (ret < 0) {
5432 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5433 instance_id, idstr);
5436 /* always seek to exact end of record */
5437 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5439 ret = 0;
5440 the_end:
5441 return ret;
5444 /* device can contain snapshots */
5445 static int bdrv_can_snapshot(BlockDriverState *bs)
5447 return (bs &&
5448 !bdrv_is_removable(bs) &&
5449 !bdrv_is_read_only(bs));
5452 /* device must be snapshots in order to have a reliable snapshot */
5453 static int bdrv_has_snapshot(BlockDriverState *bs)
5455 return (bs &&
5456 !bdrv_is_removable(bs) &&
5457 !bdrv_is_read_only(bs));
5460 static BlockDriverState *get_bs_snapshots(void)
5462 BlockDriverState *bs;
5463 int i;
5465 if (bs_snapshots)
5466 return bs_snapshots;
5467 for(i = 0; i <= MAX_DISKS; i++) {
5468 bs = bs_table[i];
5469 if (bdrv_can_snapshot(bs))
5470 goto ok;
5472 return NULL;
5474 bs_snapshots = bs;
5475 return bs;
5478 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5479 const char *name)
5481 QEMUSnapshotInfo *sn_tab, *sn;
5482 int nb_sns, i, ret;
5484 ret = -ENOENT;
5485 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5486 if (nb_sns < 0)
5487 return ret;
5488 for(i = 0; i < nb_sns; i++) {
5489 sn = &sn_tab[i];
5490 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5491 *sn_info = *sn;
5492 ret = 0;
5493 break;
5496 qemu_free(sn_tab);
5497 return ret;
5500 void do_savevm(const char *name)
5502 BlockDriverState *bs, *bs1;
5503 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5504 int must_delete, ret, i;
5505 BlockDriverInfo bdi1, *bdi = &bdi1;
5506 QEMUFile *f;
5507 int saved_vm_running;
5508 #ifdef _WIN32
5509 struct _timeb tb;
5510 #else
5511 struct timeval tv;
5512 #endif
5514 bs = get_bs_snapshots();
5515 if (!bs) {
5516 term_printf("No block device can accept snapshots\n");
5517 return;
5520 /* ??? Should this occur after vm_stop? */
5521 qemu_aio_flush();
5523 saved_vm_running = vm_running;
5524 vm_stop(0);
5526 must_delete = 0;
5527 if (name) {
5528 ret = bdrv_snapshot_find(bs, old_sn, name);
5529 if (ret >= 0) {
5530 must_delete = 1;
5533 memset(sn, 0, sizeof(*sn));
5534 if (must_delete) {
5535 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5536 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5537 } else {
5538 if (name)
5539 pstrcpy(sn->name, sizeof(sn->name), name);
5542 /* fill auxiliary fields */
5543 #ifdef _WIN32
5544 _ftime(&tb);
5545 sn->date_sec = tb.time;
5546 sn->date_nsec = tb.millitm * 1000000;
5547 #else
5548 gettimeofday(&tv, NULL);
5549 sn->date_sec = tv.tv_sec;
5550 sn->date_nsec = tv.tv_usec * 1000;
5551 #endif
5552 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5554 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5555 term_printf("Device %s does not support VM state snapshots\n",
5556 bdrv_get_device_name(bs));
5557 goto the_end;
5560 /* save the VM state */
5561 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5562 if (!f) {
5563 term_printf("Could not open VM state file\n");
5564 goto the_end;
5566 ret = qemu_savevm_state(f);
5567 sn->vm_state_size = qemu_ftell(f);
5568 qemu_fclose(f);
5569 if (ret < 0) {
5570 term_printf("Error %d while writing VM\n", ret);
5571 goto the_end;
5574 /* create the snapshots */
5576 for(i = 0; i < MAX_DISKS; i++) {
5577 bs1 = bs_table[i];
5578 if (bdrv_has_snapshot(bs1)) {
5579 if (must_delete) {
5580 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5581 if (ret < 0) {
5582 term_printf("Error while deleting snapshot on '%s'\n",
5583 bdrv_get_device_name(bs1));
5586 ret = bdrv_snapshot_create(bs1, sn);
5587 if (ret < 0) {
5588 term_printf("Error while creating snapshot on '%s'\n",
5589 bdrv_get_device_name(bs1));
5594 the_end:
5595 if (saved_vm_running)
5596 vm_start();
5599 void do_loadvm(const char *name)
5601 BlockDriverState *bs, *bs1;
5602 BlockDriverInfo bdi1, *bdi = &bdi1;
5603 QEMUFile *f;
5604 int i, ret;
5605 int saved_vm_running;
5607 bs = get_bs_snapshots();
5608 if (!bs) {
5609 term_printf("No block device supports snapshots\n");
5610 return;
5613 /* Flush all IO requests so they don't interfere with the new state. */
5614 qemu_aio_flush();
5616 saved_vm_running = vm_running;
5617 vm_stop(0);
5619 for(i = 0; i <= MAX_DISKS; i++) {
5620 bs1 = bs_table[i];
5621 if (bdrv_has_snapshot(bs1)) {
5622 ret = bdrv_snapshot_goto(bs1, name);
5623 if (ret < 0) {
5624 if (bs != bs1)
5625 term_printf("Warning: ");
5626 switch(ret) {
5627 case -ENOTSUP:
5628 term_printf("Snapshots not supported on device '%s'\n",
5629 bdrv_get_device_name(bs1));
5630 break;
5631 case -ENOENT:
5632 term_printf("Could not find snapshot '%s' on device '%s'\n",
5633 name, bdrv_get_device_name(bs1));
5634 break;
5635 default:
5636 term_printf("Error %d while activating snapshot on '%s'\n",
5637 ret, bdrv_get_device_name(bs1));
5638 break;
5640 /* fatal on snapshot block device */
5641 if (bs == bs1)
5642 goto the_end;
5647 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5648 term_printf("Device %s does not support VM state snapshots\n",
5649 bdrv_get_device_name(bs));
5650 return;
5653 /* restore the VM state */
5654 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5655 if (!f) {
5656 term_printf("Could not open VM state file\n");
5657 goto the_end;
5659 ret = qemu_loadvm_state(f);
5660 qemu_fclose(f);
5661 if (ret < 0) {
5662 term_printf("Error %d while loading VM state\n", ret);
5664 the_end:
5665 if (saved_vm_running)
5666 vm_start();
5669 void do_delvm(const char *name)
5671 BlockDriverState *bs, *bs1;
5672 int i, ret;
5674 bs = get_bs_snapshots();
5675 if (!bs) {
5676 term_printf("No block device supports snapshots\n");
5677 return;
5680 for(i = 0; i <= MAX_DISKS; i++) {
5681 bs1 = bs_table[i];
5682 if (bdrv_has_snapshot(bs1)) {
5683 ret = bdrv_snapshot_delete(bs1, name);
5684 if (ret < 0) {
5685 if (ret == -ENOTSUP)
5686 term_printf("Snapshots not supported on device '%s'\n",
5687 bdrv_get_device_name(bs1));
5688 else
5689 term_printf("Error %d while deleting snapshot on '%s'\n",
5690 ret, bdrv_get_device_name(bs1));
5696 void do_info_snapshots(void)
5698 BlockDriverState *bs, *bs1;
5699 QEMUSnapshotInfo *sn_tab, *sn;
5700 int nb_sns, i;
5701 char buf[256];
5703 bs = get_bs_snapshots();
5704 if (!bs) {
5705 term_printf("No available block device supports snapshots\n");
5706 return;
5708 term_printf("Snapshot devices:");
5709 for(i = 0; i <= MAX_DISKS; i++) {
5710 bs1 = bs_table[i];
5711 if (bdrv_has_snapshot(bs1)) {
5712 if (bs == bs1)
5713 term_printf(" %s", bdrv_get_device_name(bs1));
5716 term_printf("\n");
5718 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5719 if (nb_sns < 0) {
5720 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5721 return;
5723 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5724 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5725 for(i = 0; i < nb_sns; i++) {
5726 sn = &sn_tab[i];
5727 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5729 qemu_free(sn_tab);
5732 /***********************************************************/
5733 /* cpu save/restore */
5735 #if defined(TARGET_I386)
5737 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5739 qemu_put_be32(f, dt->selector);
5740 qemu_put_betl(f, dt->base);
5741 qemu_put_be32(f, dt->limit);
5742 qemu_put_be32(f, dt->flags);
5745 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5747 dt->selector = qemu_get_be32(f);
5748 dt->base = qemu_get_betl(f);
5749 dt->limit = qemu_get_be32(f);
5750 dt->flags = qemu_get_be32(f);
5753 void cpu_save(QEMUFile *f, void *opaque)
5755 CPUState *env = opaque;
5756 uint16_t fptag, fpus, fpuc, fpregs_format;
5757 uint32_t hflags;
5758 int i;
5760 for(i = 0; i < CPU_NB_REGS; i++)
5761 qemu_put_betls(f, &env->regs[i]);
5762 qemu_put_betls(f, &env->eip);
5763 qemu_put_betls(f, &env->eflags);
5764 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5765 qemu_put_be32s(f, &hflags);
5767 /* FPU */
5768 fpuc = env->fpuc;
5769 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5770 fptag = 0;
5771 for(i = 0; i < 8; i++) {
5772 fptag |= ((!env->fptags[i]) << i);
5775 qemu_put_be16s(f, &fpuc);
5776 qemu_put_be16s(f, &fpus);
5777 qemu_put_be16s(f, &fptag);
5779 #ifdef USE_X86LDOUBLE
5780 fpregs_format = 0;
5781 #else
5782 fpregs_format = 1;
5783 #endif
5784 qemu_put_be16s(f, &fpregs_format);
5786 for(i = 0; i < 8; i++) {
5787 #ifdef USE_X86LDOUBLE
5789 uint64_t mant;
5790 uint16_t exp;
5791 /* we save the real CPU data (in case of MMX usage only 'mant'
5792 contains the MMX register */
5793 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5794 qemu_put_be64(f, mant);
5795 qemu_put_be16(f, exp);
5797 #else
5798 /* if we use doubles for float emulation, we save the doubles to
5799 avoid losing information in case of MMX usage. It can give
5800 problems if the image is restored on a CPU where long
5801 doubles are used instead. */
5802 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5803 #endif
5806 for(i = 0; i < 6; i++)
5807 cpu_put_seg(f, &env->segs[i]);
5808 cpu_put_seg(f, &env->ldt);
5809 cpu_put_seg(f, &env->tr);
5810 cpu_put_seg(f, &env->gdt);
5811 cpu_put_seg(f, &env->idt);
5813 qemu_put_be32s(f, &env->sysenter_cs);
5814 qemu_put_be32s(f, &env->sysenter_esp);
5815 qemu_put_be32s(f, &env->sysenter_eip);
5817 qemu_put_betls(f, &env->cr[0]);
5818 qemu_put_betls(f, &env->cr[2]);
5819 qemu_put_betls(f, &env->cr[3]);
5820 qemu_put_betls(f, &env->cr[4]);
5822 for(i = 0; i < 8; i++)
5823 qemu_put_betls(f, &env->dr[i]);
5825 /* MMU */
5826 qemu_put_be32s(f, &env->a20_mask);
5828 /* XMM */
5829 qemu_put_be32s(f, &env->mxcsr);
5830 for(i = 0; i < CPU_NB_REGS; i++) {
5831 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5832 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5835 #ifdef TARGET_X86_64
5836 qemu_put_be64s(f, &env->efer);
5837 qemu_put_be64s(f, &env->star);
5838 qemu_put_be64s(f, &env->lstar);
5839 qemu_put_be64s(f, &env->cstar);
5840 qemu_put_be64s(f, &env->fmask);
5841 qemu_put_be64s(f, &env->kernelgsbase);
5842 #endif
5843 qemu_put_be32s(f, &env->smbase);
5846 #ifdef USE_X86LDOUBLE
5847 /* XXX: add that in a FPU generic layer */
5848 union x86_longdouble {
5849 uint64_t mant;
5850 uint16_t exp;
5853 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5854 #define EXPBIAS1 1023
5855 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5856 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5858 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5860 int e;
5861 /* mantissa */
5862 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5863 /* exponent + sign */
5864 e = EXPD1(temp) - EXPBIAS1 + 16383;
5865 e |= SIGND1(temp) >> 16;
5866 p->exp = e;
5868 #endif
5870 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5872 CPUState *env = opaque;
5873 int i, guess_mmx;
5874 uint32_t hflags;
5875 uint16_t fpus, fpuc, fptag, fpregs_format;
5877 if (version_id != 3 && version_id != 4)
5878 return -EINVAL;
5879 for(i = 0; i < CPU_NB_REGS; i++)
5880 qemu_get_betls(f, &env->regs[i]);
5881 qemu_get_betls(f, &env->eip);
5882 qemu_get_betls(f, &env->eflags);
5883 qemu_get_be32s(f, &hflags);
5885 qemu_get_be16s(f, &fpuc);
5886 qemu_get_be16s(f, &fpus);
5887 qemu_get_be16s(f, &fptag);
5888 qemu_get_be16s(f, &fpregs_format);
5890 /* NOTE: we cannot always restore the FPU state if the image come
5891 from a host with a different 'USE_X86LDOUBLE' define. We guess
5892 if we are in an MMX state to restore correctly in that case. */
5893 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5894 for(i = 0; i < 8; i++) {
5895 uint64_t mant;
5896 uint16_t exp;
5898 switch(fpregs_format) {
5899 case 0:
5900 mant = qemu_get_be64(f);
5901 exp = qemu_get_be16(f);
5902 #ifdef USE_X86LDOUBLE
5903 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5904 #else
5905 /* difficult case */
5906 if (guess_mmx)
5907 env->fpregs[i].mmx.MMX_Q(0) = mant;
5908 else
5909 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5910 #endif
5911 break;
5912 case 1:
5913 mant = qemu_get_be64(f);
5914 #ifdef USE_X86LDOUBLE
5916 union x86_longdouble *p;
5917 /* difficult case */
5918 p = (void *)&env->fpregs[i];
5919 if (guess_mmx) {
5920 p->mant = mant;
5921 p->exp = 0xffff;
5922 } else {
5923 fp64_to_fp80(p, mant);
5926 #else
5927 env->fpregs[i].mmx.MMX_Q(0) = mant;
5928 #endif
5929 break;
5930 default:
5931 return -EINVAL;
5935 env->fpuc = fpuc;
5936 /* XXX: restore FPU round state */
5937 env->fpstt = (fpus >> 11) & 7;
5938 env->fpus = fpus & ~0x3800;
5939 fptag ^= 0xff;
5940 for(i = 0; i < 8; i++) {
5941 env->fptags[i] = (fptag >> i) & 1;
5944 for(i = 0; i < 6; i++)
5945 cpu_get_seg(f, &env->segs[i]);
5946 cpu_get_seg(f, &env->ldt);
5947 cpu_get_seg(f, &env->tr);
5948 cpu_get_seg(f, &env->gdt);
5949 cpu_get_seg(f, &env->idt);
5951 qemu_get_be32s(f, &env->sysenter_cs);
5952 qemu_get_be32s(f, &env->sysenter_esp);
5953 qemu_get_be32s(f, &env->sysenter_eip);
5955 qemu_get_betls(f, &env->cr[0]);
5956 qemu_get_betls(f, &env->cr[2]);
5957 qemu_get_betls(f, &env->cr[3]);
5958 qemu_get_betls(f, &env->cr[4]);
5960 for(i = 0; i < 8; i++)
5961 qemu_get_betls(f, &env->dr[i]);
5963 /* MMU */
5964 qemu_get_be32s(f, &env->a20_mask);
5966 qemu_get_be32s(f, &env->mxcsr);
5967 for(i = 0; i < CPU_NB_REGS; i++) {
5968 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5969 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5972 #ifdef TARGET_X86_64
5973 qemu_get_be64s(f, &env->efer);
5974 qemu_get_be64s(f, &env->star);
5975 qemu_get_be64s(f, &env->lstar);
5976 qemu_get_be64s(f, &env->cstar);
5977 qemu_get_be64s(f, &env->fmask);
5978 qemu_get_be64s(f, &env->kernelgsbase);
5979 #endif
5980 if (version_id >= 4)
5981 qemu_get_be32s(f, &env->smbase);
5983 /* XXX: compute hflags from scratch, except for CPL and IIF */
5984 env->hflags = hflags;
5985 tlb_flush(env, 1);
5986 return 0;
5989 #elif defined(TARGET_PPC)
5990 void cpu_save(QEMUFile *f, void *opaque)
5994 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5996 return 0;
5999 #elif defined(TARGET_MIPS)
6000 void cpu_save(QEMUFile *f, void *opaque)
6004 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6006 return 0;
6009 #elif defined(TARGET_SPARC)
6010 void cpu_save(QEMUFile *f, void *opaque)
6012 CPUState *env = opaque;
6013 int i;
6014 uint32_t tmp;
6016 for(i = 0; i < 8; i++)
6017 qemu_put_betls(f, &env->gregs[i]);
6018 for(i = 0; i < NWINDOWS * 16; i++)
6019 qemu_put_betls(f, &env->regbase[i]);
6021 /* FPU */
6022 for(i = 0; i < TARGET_FPREGS; i++) {
6023 union {
6024 float32 f;
6025 uint32_t i;
6026 } u;
6027 u.f = env->fpr[i];
6028 qemu_put_be32(f, u.i);
6031 qemu_put_betls(f, &env->pc);
6032 qemu_put_betls(f, &env->npc);
6033 qemu_put_betls(f, &env->y);
6034 tmp = GET_PSR(env);
6035 qemu_put_be32(f, tmp);
6036 qemu_put_betls(f, &env->fsr);
6037 qemu_put_betls(f, &env->tbr);
6038 #ifndef TARGET_SPARC64
6039 qemu_put_be32s(f, &env->wim);
6040 /* MMU */
6041 for(i = 0; i < 16; i++)
6042 qemu_put_be32s(f, &env->mmuregs[i]);
6043 #endif
6046 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6048 CPUState *env = opaque;
6049 int i;
6050 uint32_t tmp;
6052 for(i = 0; i < 8; i++)
6053 qemu_get_betls(f, &env->gregs[i]);
6054 for(i = 0; i < NWINDOWS * 16; i++)
6055 qemu_get_betls(f, &env->regbase[i]);
6057 /* FPU */
6058 for(i = 0; i < TARGET_FPREGS; i++) {
6059 union {
6060 float32 f;
6061 uint32_t i;
6062 } u;
6063 u.i = qemu_get_be32(f);
6064 env->fpr[i] = u.f;
6067 qemu_get_betls(f, &env->pc);
6068 qemu_get_betls(f, &env->npc);
6069 qemu_get_betls(f, &env->y);
6070 tmp = qemu_get_be32(f);
6071 env->cwp = 0; /* needed to ensure that the wrapping registers are
6072 correctly updated */
6073 PUT_PSR(env, tmp);
6074 qemu_get_betls(f, &env->fsr);
6075 qemu_get_betls(f, &env->tbr);
6076 #ifndef TARGET_SPARC64
6077 qemu_get_be32s(f, &env->wim);
6078 /* MMU */
6079 for(i = 0; i < 16; i++)
6080 qemu_get_be32s(f, &env->mmuregs[i]);
6081 #endif
6082 tlb_flush(env, 1);
6083 return 0;
6086 #elif defined(TARGET_ARM)
6088 void cpu_save(QEMUFile *f, void *opaque)
6090 int i;
6091 CPUARMState *env = (CPUARMState *)opaque;
6093 for (i = 0; i < 16; i++) {
6094 qemu_put_be32(f, env->regs[i]);
6096 qemu_put_be32(f, cpsr_read(env));
6097 qemu_put_be32(f, env->spsr);
6098 for (i = 0; i < 6; i++) {
6099 qemu_put_be32(f, env->banked_spsr[i]);
6100 qemu_put_be32(f, env->banked_r13[i]);
6101 qemu_put_be32(f, env->banked_r14[i]);
6103 for (i = 0; i < 5; i++) {
6104 qemu_put_be32(f, env->usr_regs[i]);
6105 qemu_put_be32(f, env->fiq_regs[i]);
6107 qemu_put_be32(f, env->cp15.c0_cpuid);
6108 qemu_put_be32(f, env->cp15.c0_cachetype);
6109 qemu_put_be32(f, env->cp15.c1_sys);
6110 qemu_put_be32(f, env->cp15.c1_coproc);
6111 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6112 qemu_put_be32(f, env->cp15.c2_base);
6113 qemu_put_be32(f, env->cp15.c2_data);
6114 qemu_put_be32(f, env->cp15.c2_insn);
6115 qemu_put_be32(f, env->cp15.c3);
6116 qemu_put_be32(f, env->cp15.c5_insn);
6117 qemu_put_be32(f, env->cp15.c5_data);
6118 for (i = 0; i < 8; i++) {
6119 qemu_put_be32(f, env->cp15.c6_region[i]);
6121 qemu_put_be32(f, env->cp15.c6_insn);
6122 qemu_put_be32(f, env->cp15.c6_data);
6123 qemu_put_be32(f, env->cp15.c9_insn);
6124 qemu_put_be32(f, env->cp15.c9_data);
6125 qemu_put_be32(f, env->cp15.c13_fcse);
6126 qemu_put_be32(f, env->cp15.c13_context);
6127 qemu_put_be32(f, env->cp15.c15_cpar);
6129 qemu_put_be32(f, env->features);
6131 if (arm_feature(env, ARM_FEATURE_VFP)) {
6132 for (i = 0; i < 16; i++) {
6133 CPU_DoubleU u;
6134 u.d = env->vfp.regs[i];
6135 qemu_put_be32(f, u.l.upper);
6136 qemu_put_be32(f, u.l.lower);
6138 for (i = 0; i < 16; i++) {
6139 qemu_put_be32(f, env->vfp.xregs[i]);
6142 /* TODO: Should use proper FPSCR access functions. */
6143 qemu_put_be32(f, env->vfp.vec_len);
6144 qemu_put_be32(f, env->vfp.vec_stride);
6147 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6148 for (i = 0; i < 16; i++) {
6149 qemu_put_be64(f, env->iwmmxt.regs[i]);
6151 for (i = 0; i < 16; i++) {
6152 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6157 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6159 CPUARMState *env = (CPUARMState *)opaque;
6160 int i;
6162 if (version_id != 0)
6163 return -EINVAL;
6165 for (i = 0; i < 16; i++) {
6166 env->regs[i] = qemu_get_be32(f);
6168 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6169 env->spsr = qemu_get_be32(f);
6170 for (i = 0; i < 6; i++) {
6171 env->banked_spsr[i] = qemu_get_be32(f);
6172 env->banked_r13[i] = qemu_get_be32(f);
6173 env->banked_r14[i] = qemu_get_be32(f);
6175 for (i = 0; i < 5; i++) {
6176 env->usr_regs[i] = qemu_get_be32(f);
6177 env->fiq_regs[i] = qemu_get_be32(f);
6179 env->cp15.c0_cpuid = qemu_get_be32(f);
6180 env->cp15.c0_cachetype = qemu_get_be32(f);
6181 env->cp15.c1_sys = qemu_get_be32(f);
6182 env->cp15.c1_coproc = qemu_get_be32(f);
6183 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6184 env->cp15.c2_base = qemu_get_be32(f);
6185 env->cp15.c2_data = qemu_get_be32(f);
6186 env->cp15.c2_insn = qemu_get_be32(f);
6187 env->cp15.c3 = qemu_get_be32(f);
6188 env->cp15.c5_insn = qemu_get_be32(f);
6189 env->cp15.c5_data = qemu_get_be32(f);
6190 for (i = 0; i < 8; i++) {
6191 env->cp15.c6_region[i] = qemu_get_be32(f);
6193 env->cp15.c6_insn = qemu_get_be32(f);
6194 env->cp15.c6_data = qemu_get_be32(f);
6195 env->cp15.c9_insn = qemu_get_be32(f);
6196 env->cp15.c9_data = qemu_get_be32(f);
6197 env->cp15.c13_fcse = qemu_get_be32(f);
6198 env->cp15.c13_context = qemu_get_be32(f);
6199 env->cp15.c15_cpar = qemu_get_be32(f);
6201 env->features = qemu_get_be32(f);
6203 if (arm_feature(env, ARM_FEATURE_VFP)) {
6204 for (i = 0; i < 16; i++) {
6205 CPU_DoubleU u;
6206 u.l.upper = qemu_get_be32(f);
6207 u.l.lower = qemu_get_be32(f);
6208 env->vfp.regs[i] = u.d;
6210 for (i = 0; i < 16; i++) {
6211 env->vfp.xregs[i] = qemu_get_be32(f);
6214 /* TODO: Should use proper FPSCR access functions. */
6215 env->vfp.vec_len = qemu_get_be32(f);
6216 env->vfp.vec_stride = qemu_get_be32(f);
6219 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6220 for (i = 0; i < 16; i++) {
6221 env->iwmmxt.regs[i] = qemu_get_be64(f);
6223 for (i = 0; i < 16; i++) {
6224 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6228 return 0;
6231 #else
6233 #warning No CPU save/restore functions
6235 #endif
6237 /***********************************************************/
6238 /* ram save/restore */
6240 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6242 int v;
6244 v = qemu_get_byte(f);
6245 switch(v) {
6246 case 0:
6247 if (qemu_get_buffer(f, buf, len) != len)
6248 return -EIO;
6249 break;
6250 case 1:
6251 v = qemu_get_byte(f);
6252 memset(buf, v, len);
6253 break;
6254 default:
6255 return -EINVAL;
6257 return 0;
6260 static int ram_load_v1(QEMUFile *f, void *opaque)
6262 int i, ret;
6264 if (qemu_get_be32(f) != phys_ram_size)
6265 return -EINVAL;
6266 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6267 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6268 if (ret)
6269 return ret;
6271 return 0;
6274 #define BDRV_HASH_BLOCK_SIZE 1024
6275 #define IOBUF_SIZE 4096
6276 #define RAM_CBLOCK_MAGIC 0xfabe
6278 typedef struct RamCompressState {
6279 z_stream zstream;
6280 QEMUFile *f;
6281 uint8_t buf[IOBUF_SIZE];
6282 } RamCompressState;
6284 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6286 int ret;
6287 memset(s, 0, sizeof(*s));
6288 s->f = f;
6289 ret = deflateInit2(&s->zstream, 1,
6290 Z_DEFLATED, 15,
6291 9, Z_DEFAULT_STRATEGY);
6292 if (ret != Z_OK)
6293 return -1;
6294 s->zstream.avail_out = IOBUF_SIZE;
6295 s->zstream.next_out = s->buf;
6296 return 0;
6299 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6301 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6302 qemu_put_be16(s->f, len);
6303 qemu_put_buffer(s->f, buf, len);
6306 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6308 int ret;
6310 s->zstream.avail_in = len;
6311 s->zstream.next_in = (uint8_t *)buf;
6312 while (s->zstream.avail_in > 0) {
6313 ret = deflate(&s->zstream, Z_NO_FLUSH);
6314 if (ret != Z_OK)
6315 return -1;
6316 if (s->zstream.avail_out == 0) {
6317 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6318 s->zstream.avail_out = IOBUF_SIZE;
6319 s->zstream.next_out = s->buf;
6322 return 0;
6325 static void ram_compress_close(RamCompressState *s)
6327 int len, ret;
6329 /* compress last bytes */
6330 for(;;) {
6331 ret = deflate(&s->zstream, Z_FINISH);
6332 if (ret == Z_OK || ret == Z_STREAM_END) {
6333 len = IOBUF_SIZE - s->zstream.avail_out;
6334 if (len > 0) {
6335 ram_put_cblock(s, s->buf, len);
6337 s->zstream.avail_out = IOBUF_SIZE;
6338 s->zstream.next_out = s->buf;
6339 if (ret == Z_STREAM_END)
6340 break;
6341 } else {
6342 goto fail;
6345 fail:
6346 deflateEnd(&s->zstream);
6349 typedef struct RamDecompressState {
6350 z_stream zstream;
6351 QEMUFile *f;
6352 uint8_t buf[IOBUF_SIZE];
6353 } RamDecompressState;
6355 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6357 int ret;
6358 memset(s, 0, sizeof(*s));
6359 s->f = f;
6360 ret = inflateInit(&s->zstream);
6361 if (ret != Z_OK)
6362 return -1;
6363 return 0;
6366 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6368 int ret, clen;
6370 s->zstream.avail_out = len;
6371 s->zstream.next_out = buf;
6372 while (s->zstream.avail_out > 0) {
6373 if (s->zstream.avail_in == 0) {
6374 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6375 return -1;
6376 clen = qemu_get_be16(s->f);
6377 if (clen > IOBUF_SIZE)
6378 return -1;
6379 qemu_get_buffer(s->f, s->buf, clen);
6380 s->zstream.avail_in = clen;
6381 s->zstream.next_in = s->buf;
6383 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6384 if (ret != Z_OK && ret != Z_STREAM_END) {
6385 return -1;
6388 return 0;
6391 static void ram_decompress_close(RamDecompressState *s)
6393 inflateEnd(&s->zstream);
6396 static void ram_save(QEMUFile *f, void *opaque)
6398 int i;
6399 RamCompressState s1, *s = &s1;
6400 uint8_t buf[10];
6402 qemu_put_be32(f, phys_ram_size);
6403 if (ram_compress_open(s, f) < 0)
6404 return;
6405 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6406 #if 0
6407 if (tight_savevm_enabled) {
6408 int64_t sector_num;
6409 int j;
6411 /* find if the memory block is available on a virtual
6412 block device */
6413 sector_num = -1;
6414 for(j = 0; j < MAX_DISKS; j++) {
6415 if (bs_table[j]) {
6416 sector_num = bdrv_hash_find(bs_table[j],
6417 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6418 if (sector_num >= 0)
6419 break;
6422 if (j == MAX_DISKS)
6423 goto normal_compress;
6424 buf[0] = 1;
6425 buf[1] = j;
6426 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6427 ram_compress_buf(s, buf, 10);
6428 } else
6429 #endif
6431 // normal_compress:
6432 buf[0] = 0;
6433 ram_compress_buf(s, buf, 1);
6434 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6437 ram_compress_close(s);
6440 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6442 RamDecompressState s1, *s = &s1;
6443 uint8_t buf[10];
6444 int i;
6446 if (version_id == 1)
6447 return ram_load_v1(f, opaque);
6448 if (version_id != 2)
6449 return -EINVAL;
6450 if (qemu_get_be32(f) != phys_ram_size)
6451 return -EINVAL;
6452 if (ram_decompress_open(s, f) < 0)
6453 return -EINVAL;
6454 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6455 if (ram_decompress_buf(s, buf, 1) < 0) {
6456 fprintf(stderr, "Error while reading ram block header\n");
6457 goto error;
6459 if (buf[0] == 0) {
6460 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6461 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6462 goto error;
6464 } else
6465 #if 0
6466 if (buf[0] == 1) {
6467 int bs_index;
6468 int64_t sector_num;
6470 ram_decompress_buf(s, buf + 1, 9);
6471 bs_index = buf[1];
6472 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6473 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6474 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6475 goto error;
6477 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6478 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6479 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6480 bs_index, sector_num);
6481 goto error;
6483 } else
6484 #endif
6486 error:
6487 printf("Error block header\n");
6488 return -EINVAL;
6491 ram_decompress_close(s);
6492 return 0;
6495 /***********************************************************/
6496 /* bottom halves (can be seen as timers which expire ASAP) */
6498 struct QEMUBH {
6499 QEMUBHFunc *cb;
6500 void *opaque;
6501 int scheduled;
6502 QEMUBH *next;
6505 static QEMUBH *first_bh = NULL;
6507 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6509 QEMUBH *bh;
6510 bh = qemu_mallocz(sizeof(QEMUBH));
6511 if (!bh)
6512 return NULL;
6513 bh->cb = cb;
6514 bh->opaque = opaque;
6515 return bh;
6518 int qemu_bh_poll(void)
6520 QEMUBH *bh, **pbh;
6521 int ret;
6523 ret = 0;
6524 for(;;) {
6525 pbh = &first_bh;
6526 bh = *pbh;
6527 if (!bh)
6528 break;
6529 ret = 1;
6530 *pbh = bh->next;
6531 bh->scheduled = 0;
6532 bh->cb(bh->opaque);
6534 return ret;
6537 void qemu_bh_schedule(QEMUBH *bh)
6539 CPUState *env = cpu_single_env;
6540 if (bh->scheduled)
6541 return;
6542 bh->scheduled = 1;
6543 bh->next = first_bh;
6544 first_bh = bh;
6546 /* stop the currently executing CPU to execute the BH ASAP */
6547 if (env) {
6548 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6552 void qemu_bh_cancel(QEMUBH *bh)
6554 QEMUBH **pbh;
6555 if (bh->scheduled) {
6556 pbh = &first_bh;
6557 while (*pbh != bh)
6558 pbh = &(*pbh)->next;
6559 *pbh = bh->next;
6560 bh->scheduled = 0;
6564 void qemu_bh_delete(QEMUBH *bh)
6566 qemu_bh_cancel(bh);
6567 qemu_free(bh);
6570 /***********************************************************/
6571 /* machine registration */
6573 QEMUMachine *first_machine = NULL;
6575 int qemu_register_machine(QEMUMachine *m)
6577 QEMUMachine **pm;
6578 pm = &first_machine;
6579 while (*pm != NULL)
6580 pm = &(*pm)->next;
6581 m->next = NULL;
6582 *pm = m;
6583 return 0;
6586 QEMUMachine *find_machine(const char *name)
6588 QEMUMachine *m;
6590 for(m = first_machine; m != NULL; m = m->next) {
6591 if (!strcmp(m->name, name))
6592 return m;
6594 return NULL;
6597 /***********************************************************/
6598 /* main execution loop */
6600 void gui_update(void *opaque)
6602 DisplayState *ds = opaque;
6603 ds->dpy_refresh(ds);
6604 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6607 struct vm_change_state_entry {
6608 VMChangeStateHandler *cb;
6609 void *opaque;
6610 LIST_ENTRY (vm_change_state_entry) entries;
6613 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6615 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6616 void *opaque)
6618 VMChangeStateEntry *e;
6620 e = qemu_mallocz(sizeof (*e));
6621 if (!e)
6622 return NULL;
6624 e->cb = cb;
6625 e->opaque = opaque;
6626 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6627 return e;
6630 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6632 LIST_REMOVE (e, entries);
6633 qemu_free (e);
6636 static void vm_state_notify(int running)
6638 VMChangeStateEntry *e;
6640 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6641 e->cb(e->opaque, running);
6645 /* XXX: support several handlers */
6646 static VMStopHandler *vm_stop_cb;
6647 static void *vm_stop_opaque;
6649 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6651 vm_stop_cb = cb;
6652 vm_stop_opaque = opaque;
6653 return 0;
6656 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6658 vm_stop_cb = NULL;
6661 void vm_start(void)
6663 if (!vm_running) {
6664 cpu_enable_ticks();
6665 vm_running = 1;
6666 vm_state_notify(1);
6667 qemu_rearm_alarm_timer(alarm_timer);
6671 void vm_stop(int reason)
6673 if (vm_running) {
6674 cpu_disable_ticks();
6675 vm_running = 0;
6676 if (reason != 0) {
6677 if (vm_stop_cb) {
6678 vm_stop_cb(vm_stop_opaque, reason);
6681 vm_state_notify(0);
6685 /* reset/shutdown handler */
6687 typedef struct QEMUResetEntry {
6688 QEMUResetHandler *func;
6689 void *opaque;
6690 struct QEMUResetEntry *next;
6691 } QEMUResetEntry;
6693 static QEMUResetEntry *first_reset_entry;
6694 static int reset_requested;
6695 static int shutdown_requested;
6696 static int powerdown_requested;
6698 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6700 QEMUResetEntry **pre, *re;
6702 pre = &first_reset_entry;
6703 while (*pre != NULL)
6704 pre = &(*pre)->next;
6705 re = qemu_mallocz(sizeof(QEMUResetEntry));
6706 re->func = func;
6707 re->opaque = opaque;
6708 re->next = NULL;
6709 *pre = re;
6712 static void qemu_system_reset(void)
6714 QEMUResetEntry *re;
6716 /* reset all devices */
6717 for(re = first_reset_entry; re != NULL; re = re->next) {
6718 re->func(re->opaque);
6722 void qemu_system_reset_request(void)
6724 if (no_reboot) {
6725 shutdown_requested = 1;
6726 } else {
6727 reset_requested = 1;
6729 if (cpu_single_env)
6730 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6733 void qemu_system_shutdown_request(void)
6735 shutdown_requested = 1;
6736 if (cpu_single_env)
6737 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6740 void qemu_system_powerdown_request(void)
6742 powerdown_requested = 1;
6743 if (cpu_single_env)
6744 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6747 void main_loop_wait(int timeout)
6749 IOHandlerRecord *ioh;
6750 fd_set rfds, wfds, xfds;
6751 int ret, nfds;
6752 #ifdef _WIN32
6753 int ret2, i;
6754 #endif
6755 struct timeval tv;
6756 PollingEntry *pe;
6759 /* XXX: need to suppress polling by better using win32 events */
6760 ret = 0;
6761 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6762 ret |= pe->func(pe->opaque);
6764 #ifdef _WIN32
6765 if (ret == 0) {
6766 int err;
6767 WaitObjects *w = &wait_objects;
6769 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6770 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6771 if (w->func[ret - WAIT_OBJECT_0])
6772 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6774 /* Check for additional signaled events */
6775 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6777 /* Check if event is signaled */
6778 ret2 = WaitForSingleObject(w->events[i], 0);
6779 if(ret2 == WAIT_OBJECT_0) {
6780 if (w->func[i])
6781 w->func[i](w->opaque[i]);
6782 } else if (ret2 == WAIT_TIMEOUT) {
6783 } else {
6784 err = GetLastError();
6785 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6788 } else if (ret == WAIT_TIMEOUT) {
6789 } else {
6790 err = GetLastError();
6791 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6794 #endif
6795 /* poll any events */
6796 /* XXX: separate device handlers from system ones */
6797 nfds = -1;
6798 FD_ZERO(&rfds);
6799 FD_ZERO(&wfds);
6800 FD_ZERO(&xfds);
6801 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6802 if (ioh->deleted)
6803 continue;
6804 if (ioh->fd_read &&
6805 (!ioh->fd_read_poll ||
6806 ioh->fd_read_poll(ioh->opaque) != 0)) {
6807 FD_SET(ioh->fd, &rfds);
6808 if (ioh->fd > nfds)
6809 nfds = ioh->fd;
6811 if (ioh->fd_write) {
6812 FD_SET(ioh->fd, &wfds);
6813 if (ioh->fd > nfds)
6814 nfds = ioh->fd;
6818 tv.tv_sec = 0;
6819 #ifdef _WIN32
6820 tv.tv_usec = 0;
6821 #else
6822 tv.tv_usec = timeout * 1000;
6823 #endif
6824 #if defined(CONFIG_SLIRP)
6825 if (slirp_inited) {
6826 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6828 #endif
6829 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6830 if (ret > 0) {
6831 IOHandlerRecord **pioh;
6833 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6834 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6835 ioh->fd_read(ioh->opaque);
6837 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6838 ioh->fd_write(ioh->opaque);
6842 /* remove deleted IO handlers */
6843 pioh = &first_io_handler;
6844 while (*pioh) {
6845 ioh = *pioh;
6846 if (ioh->deleted) {
6847 *pioh = ioh->next;
6848 qemu_free(ioh);
6849 } else
6850 pioh = &ioh->next;
6853 #if defined(CONFIG_SLIRP)
6854 if (slirp_inited) {
6855 if (ret < 0) {
6856 FD_ZERO(&rfds);
6857 FD_ZERO(&wfds);
6858 FD_ZERO(&xfds);
6860 slirp_select_poll(&rfds, &wfds, &xfds);
6862 #endif
6863 qemu_aio_poll();
6865 if (vm_running) {
6866 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6867 qemu_get_clock(vm_clock));
6868 /* run dma transfers, if any */
6869 DMA_run();
6872 /* real time timers */
6873 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6874 qemu_get_clock(rt_clock));
6876 /* Check bottom-halves last in case any of the earlier events triggered
6877 them. */
6878 qemu_bh_poll();
6882 static CPUState *cur_cpu;
6884 int main_loop(void)
6886 int ret, timeout;
6887 #ifdef CONFIG_PROFILER
6888 int64_t ti;
6889 #endif
6890 CPUState *env;
6892 cur_cpu = first_cpu;
6893 for(;;) {
6894 if (vm_running) {
6896 env = cur_cpu;
6897 for(;;) {
6898 /* get next cpu */
6899 env = env->next_cpu;
6900 if (!env)
6901 env = first_cpu;
6902 #ifdef CONFIG_PROFILER
6903 ti = profile_getclock();
6904 #endif
6905 ret = cpu_exec(env);
6906 #ifdef CONFIG_PROFILER
6907 qemu_time += profile_getclock() - ti;
6908 #endif
6909 if (ret == EXCP_HLT) {
6910 /* Give the next CPU a chance to run. */
6911 cur_cpu = env;
6912 continue;
6914 if (ret != EXCP_HALTED)
6915 break;
6916 /* all CPUs are halted ? */
6917 if (env == cur_cpu)
6918 break;
6920 cur_cpu = env;
6922 if (shutdown_requested) {
6923 ret = EXCP_INTERRUPT;
6924 break;
6926 if (reset_requested) {
6927 reset_requested = 0;
6928 qemu_system_reset();
6929 ret = EXCP_INTERRUPT;
6931 if (powerdown_requested) {
6932 powerdown_requested = 0;
6933 qemu_system_powerdown();
6934 ret = EXCP_INTERRUPT;
6936 if (ret == EXCP_DEBUG) {
6937 vm_stop(EXCP_DEBUG);
6939 /* If all cpus are halted then wait until the next IRQ */
6940 /* XXX: use timeout computed from timers */
6941 if (ret == EXCP_HALTED)
6942 timeout = 10;
6943 else
6944 timeout = 0;
6945 } else {
6946 timeout = 10;
6948 #ifdef CONFIG_PROFILER
6949 ti = profile_getclock();
6950 #endif
6951 main_loop_wait(timeout);
6952 #ifdef CONFIG_PROFILER
6953 dev_time += profile_getclock() - ti;
6954 #endif
6956 cpu_disable_ticks();
6957 return ret;
6960 static void help(int exitcode)
6962 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6963 "usage: %s [options] [disk_image]\n"
6964 "\n"
6965 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6966 "\n"
6967 "Standard options:\n"
6968 "-M machine select emulated machine (-M ? for list)\n"
6969 "-cpu cpu select CPU (-cpu ? for list)\n"
6970 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6971 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6972 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6973 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6974 "-mtdblock file use 'file' as on-board Flash memory image\n"
6975 "-sd file use 'file' as SecureDigital card image\n"
6976 "-pflash file use 'file' as a parallel flash image\n"
6977 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6978 "-snapshot write to temporary files instead of disk image files\n"
6979 #ifdef CONFIG_SDL
6980 "-no-frame open SDL window without a frame and window decorations\n"
6981 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6982 "-no-quit disable SDL window close capability\n"
6983 #endif
6984 #ifdef TARGET_I386
6985 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6986 #endif
6987 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6988 "-smp n set the number of CPUs to 'n' [default=1]\n"
6989 "-nographic disable graphical output and redirect serial I/Os to console\n"
6990 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6991 #ifndef _WIN32
6992 "-k language use keyboard layout (for example \"fr\" for French)\n"
6993 #endif
6994 #ifdef HAS_AUDIO
6995 "-audio-help print list of audio drivers and their options\n"
6996 "-soundhw c1,... enable audio support\n"
6997 " and only specified sound cards (comma separated list)\n"
6998 " use -soundhw ? to get the list of supported cards\n"
6999 " use -soundhw all to enable all of them\n"
7000 #endif
7001 "-localtime set the real time clock to local time [default=utc]\n"
7002 "-full-screen start in full screen\n"
7003 #ifdef TARGET_I386
7004 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7005 #endif
7006 "-usb enable the USB driver (will be the default soon)\n"
7007 "-usbdevice name add the host or guest USB device 'name'\n"
7008 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7009 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7010 #endif
7011 "-name string set the name of the guest\n"
7012 "\n"
7013 "Network options:\n"
7014 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7015 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7016 #ifdef CONFIG_SLIRP
7017 "-net user[,vlan=n][,hostname=host]\n"
7018 " connect the user mode network stack to VLAN 'n' and send\n"
7019 " hostname 'host' to DHCP clients\n"
7020 #endif
7021 #ifdef _WIN32
7022 "-net tap[,vlan=n],ifname=name\n"
7023 " connect the host TAP network interface to VLAN 'n'\n"
7024 #else
7025 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
7026 " connect the host TAP network interface to VLAN 'n' and use\n"
7027 " the network script 'file' (default=%s);\n"
7028 " use 'script=no' to disable script execution;\n"
7029 " use 'fd=h' to connect to an already opened TAP interface\n"
7030 #endif
7031 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7032 " connect the vlan 'n' to another VLAN using a socket connection\n"
7033 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7034 " connect the vlan 'n' to multicast maddr and port\n"
7035 "-net none use it alone to have zero network devices; if no -net option\n"
7036 " is provided, the default is '-net nic -net user'\n"
7037 "\n"
7038 #ifdef CONFIG_SLIRP
7039 "-tftp dir allow tftp access to files in dir [-net user]\n"
7040 "-bootp file advertise file in BOOTP replies\n"
7041 #ifndef _WIN32
7042 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7043 #endif
7044 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7045 " redirect TCP or UDP connections from host to guest [-net user]\n"
7046 #endif
7047 "\n"
7048 "Linux boot specific:\n"
7049 "-kernel bzImage use 'bzImage' as kernel image\n"
7050 "-append cmdline use 'cmdline' as kernel command line\n"
7051 "-initrd file use 'file' as initial ram disk\n"
7052 "\n"
7053 "Debug/Expert options:\n"
7054 "-monitor dev redirect the monitor to char device 'dev'\n"
7055 "-serial dev redirect the serial port to char device 'dev'\n"
7056 "-parallel dev redirect the parallel port to char device 'dev'\n"
7057 "-pidfile file Write PID to 'file'\n"
7058 "-S freeze CPU at startup (use 'c' to start execution)\n"
7059 "-s wait gdb connection to port\n"
7060 "-p port set gdb connection port [default=%s]\n"
7061 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7062 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7063 " translation (t=none or lba) (usually qemu can guess them)\n"
7064 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7065 #ifdef USE_KQEMU
7066 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7067 "-no-kqemu disable KQEMU kernel module usage\n"
7068 #endif
7069 #ifdef USE_CODE_COPY
7070 "-no-code-copy disable code copy acceleration\n"
7071 #endif
7072 #ifdef TARGET_I386
7073 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7074 " (default is CL-GD5446 PCI VGA)\n"
7075 "-no-acpi disable ACPI\n"
7076 #endif
7077 "-no-reboot exit instead of rebooting\n"
7078 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7079 "-vnc display start a VNC server on display\n"
7080 #ifndef _WIN32
7081 "-daemonize daemonize QEMU after initializing\n"
7082 #endif
7083 "-option-rom rom load a file, rom, into the option ROM space\n"
7084 #ifdef TARGET_SPARC
7085 "-prom-env variable=value set OpenBIOS nvram variables\n"
7086 #endif
7087 "-clock force the use of the given methods for timer alarm.\n"
7088 " To see what timers are available use -clock help\n"
7089 "\n"
7090 "During emulation, the following keys are useful:\n"
7091 "ctrl-alt-f toggle full screen\n"
7092 "ctrl-alt-n switch to virtual console 'n'\n"
7093 "ctrl-alt toggle mouse and keyboard grab\n"
7094 "\n"
7095 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7097 "qemu",
7098 DEFAULT_RAM_SIZE,
7099 #ifndef _WIN32
7100 DEFAULT_NETWORK_SCRIPT,
7101 #endif
7102 DEFAULT_GDBSTUB_PORT,
7103 "/tmp/qemu.log");
7104 exit(exitcode);
7107 #define HAS_ARG 0x0001
7109 enum {
7110 QEMU_OPTION_h,
7112 QEMU_OPTION_M,
7113 QEMU_OPTION_cpu,
7114 QEMU_OPTION_fda,
7115 QEMU_OPTION_fdb,
7116 QEMU_OPTION_hda,
7117 QEMU_OPTION_hdb,
7118 QEMU_OPTION_hdc,
7119 QEMU_OPTION_hdd,
7120 QEMU_OPTION_cdrom,
7121 QEMU_OPTION_mtdblock,
7122 QEMU_OPTION_sd,
7123 QEMU_OPTION_pflash,
7124 QEMU_OPTION_boot,
7125 QEMU_OPTION_snapshot,
7126 #ifdef TARGET_I386
7127 QEMU_OPTION_no_fd_bootchk,
7128 #endif
7129 QEMU_OPTION_m,
7130 QEMU_OPTION_nographic,
7131 QEMU_OPTION_portrait,
7132 #ifdef HAS_AUDIO
7133 QEMU_OPTION_audio_help,
7134 QEMU_OPTION_soundhw,
7135 #endif
7137 QEMU_OPTION_net,
7138 QEMU_OPTION_tftp,
7139 QEMU_OPTION_bootp,
7140 QEMU_OPTION_smb,
7141 QEMU_OPTION_redir,
7143 QEMU_OPTION_kernel,
7144 QEMU_OPTION_append,
7145 QEMU_OPTION_initrd,
7147 QEMU_OPTION_S,
7148 QEMU_OPTION_s,
7149 QEMU_OPTION_p,
7150 QEMU_OPTION_d,
7151 QEMU_OPTION_hdachs,
7152 QEMU_OPTION_L,
7153 QEMU_OPTION_bios,
7154 QEMU_OPTION_no_code_copy,
7155 QEMU_OPTION_k,
7156 QEMU_OPTION_localtime,
7157 QEMU_OPTION_cirrusvga,
7158 QEMU_OPTION_vmsvga,
7159 QEMU_OPTION_g,
7160 QEMU_OPTION_std_vga,
7161 QEMU_OPTION_echr,
7162 QEMU_OPTION_monitor,
7163 QEMU_OPTION_serial,
7164 QEMU_OPTION_parallel,
7165 QEMU_OPTION_loadvm,
7166 QEMU_OPTION_full_screen,
7167 QEMU_OPTION_no_frame,
7168 QEMU_OPTION_alt_grab,
7169 QEMU_OPTION_no_quit,
7170 QEMU_OPTION_pidfile,
7171 QEMU_OPTION_no_kqemu,
7172 QEMU_OPTION_kernel_kqemu,
7173 QEMU_OPTION_win2k_hack,
7174 QEMU_OPTION_usb,
7175 QEMU_OPTION_usbdevice,
7176 QEMU_OPTION_smp,
7177 QEMU_OPTION_vnc,
7178 QEMU_OPTION_no_acpi,
7179 QEMU_OPTION_no_reboot,
7180 QEMU_OPTION_show_cursor,
7181 QEMU_OPTION_daemonize,
7182 QEMU_OPTION_option_rom,
7183 QEMU_OPTION_semihosting,
7184 QEMU_OPTION_name,
7185 QEMU_OPTION_prom_env,
7186 QEMU_OPTION_old_param,
7187 QEMU_OPTION_clock,
7190 typedef struct QEMUOption {
7191 const char *name;
7192 int flags;
7193 int index;
7194 } QEMUOption;
7196 const QEMUOption qemu_options[] = {
7197 { "h", 0, QEMU_OPTION_h },
7198 { "help", 0, QEMU_OPTION_h },
7200 { "M", HAS_ARG, QEMU_OPTION_M },
7201 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7202 { "fda", HAS_ARG, QEMU_OPTION_fda },
7203 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7204 { "hda", HAS_ARG, QEMU_OPTION_hda },
7205 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7206 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7207 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7208 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7209 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7210 { "sd", HAS_ARG, QEMU_OPTION_sd },
7211 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7212 { "boot", HAS_ARG, QEMU_OPTION_boot },
7213 { "snapshot", 0, QEMU_OPTION_snapshot },
7214 #ifdef TARGET_I386
7215 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7216 #endif
7217 { "m", HAS_ARG, QEMU_OPTION_m },
7218 { "nographic", 0, QEMU_OPTION_nographic },
7219 { "portrait", 0, QEMU_OPTION_portrait },
7220 { "k", HAS_ARG, QEMU_OPTION_k },
7221 #ifdef HAS_AUDIO
7222 { "audio-help", 0, QEMU_OPTION_audio_help },
7223 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7224 #endif
7226 { "net", HAS_ARG, QEMU_OPTION_net},
7227 #ifdef CONFIG_SLIRP
7228 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7229 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7230 #ifndef _WIN32
7231 { "smb", HAS_ARG, QEMU_OPTION_smb },
7232 #endif
7233 { "redir", HAS_ARG, QEMU_OPTION_redir },
7234 #endif
7236 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7237 { "append", HAS_ARG, QEMU_OPTION_append },
7238 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7240 { "S", 0, QEMU_OPTION_S },
7241 { "s", 0, QEMU_OPTION_s },
7242 { "p", HAS_ARG, QEMU_OPTION_p },
7243 { "d", HAS_ARG, QEMU_OPTION_d },
7244 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7245 { "L", HAS_ARG, QEMU_OPTION_L },
7246 { "bios", HAS_ARG, QEMU_OPTION_bios },
7247 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7248 #ifdef USE_KQEMU
7249 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7250 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7251 #endif
7252 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7253 { "g", 1, QEMU_OPTION_g },
7254 #endif
7255 { "localtime", 0, QEMU_OPTION_localtime },
7256 { "std-vga", 0, QEMU_OPTION_std_vga },
7257 { "echr", HAS_ARG, QEMU_OPTION_echr },
7258 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7259 { "serial", HAS_ARG, QEMU_OPTION_serial },
7260 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7261 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7262 { "full-screen", 0, QEMU_OPTION_full_screen },
7263 #ifdef CONFIG_SDL
7264 { "no-frame", 0, QEMU_OPTION_no_frame },
7265 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7266 { "no-quit", 0, QEMU_OPTION_no_quit },
7267 #endif
7268 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7269 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7270 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7271 { "smp", HAS_ARG, QEMU_OPTION_smp },
7272 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7274 /* temporary options */
7275 { "usb", 0, QEMU_OPTION_usb },
7276 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7277 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7278 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7279 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7280 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7281 { "daemonize", 0, QEMU_OPTION_daemonize },
7282 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7283 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7284 { "semihosting", 0, QEMU_OPTION_semihosting },
7285 #endif
7286 { "name", HAS_ARG, QEMU_OPTION_name },
7287 #if defined(TARGET_SPARC)
7288 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7289 #endif
7290 #if defined(TARGET_ARM)
7291 { "old-param", 0, QEMU_OPTION_old_param },
7292 #endif
7293 { "clock", HAS_ARG, QEMU_OPTION_clock },
7294 { NULL },
7297 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7299 /* this stack is only used during signal handling */
7300 #define SIGNAL_STACK_SIZE 32768
7302 static uint8_t *signal_stack;
7304 #endif
7306 /* password input */
7308 int qemu_key_check(BlockDriverState *bs, const char *name)
7310 char password[256];
7311 int i;
7313 if (!bdrv_is_encrypted(bs))
7314 return 0;
7316 term_printf("%s is encrypted.\n", name);
7317 for(i = 0; i < 3; i++) {
7318 monitor_readline("Password: ", 1, password, sizeof(password));
7319 if (bdrv_set_key(bs, password) == 0)
7320 return 0;
7321 term_printf("invalid password\n");
7323 return -EPERM;
7326 static BlockDriverState *get_bdrv(int index)
7328 BlockDriverState *bs;
7330 if (index < 4) {
7331 bs = bs_table[index];
7332 } else if (index < 6) {
7333 bs = fd_table[index - 4];
7334 } else {
7335 bs = NULL;
7337 return bs;
7340 static void read_passwords(void)
7342 BlockDriverState *bs;
7343 int i;
7345 for(i = 0; i < 6; i++) {
7346 bs = get_bdrv(i);
7347 if (bs)
7348 qemu_key_check(bs, bdrv_get_device_name(bs));
7352 /* XXX: currently we cannot use simultaneously different CPUs */
7353 void register_machines(void)
7355 #if defined(TARGET_I386)
7356 qemu_register_machine(&pc_machine);
7357 qemu_register_machine(&isapc_machine);
7358 #elif defined(TARGET_PPC)
7359 qemu_register_machine(&heathrow_machine);
7360 qemu_register_machine(&core99_machine);
7361 qemu_register_machine(&prep_machine);
7362 qemu_register_machine(&ref405ep_machine);
7363 qemu_register_machine(&taihu_machine);
7364 #elif defined(TARGET_MIPS)
7365 qemu_register_machine(&mips_machine);
7366 qemu_register_machine(&mips_malta_machine);
7367 qemu_register_machine(&mips_pica61_machine);
7368 qemu_register_machine(&mips_mipssim_machine);
7369 #elif defined(TARGET_SPARC)
7370 #ifdef TARGET_SPARC64
7371 qemu_register_machine(&sun4u_machine);
7372 #else
7373 qemu_register_machine(&ss5_machine);
7374 qemu_register_machine(&ss10_machine);
7375 #endif
7376 #elif defined(TARGET_ARM)
7377 qemu_register_machine(&integratorcp_machine);
7378 qemu_register_machine(&versatilepb_machine);
7379 qemu_register_machine(&versatileab_machine);
7380 qemu_register_machine(&realview_machine);
7381 qemu_register_machine(&akitapda_machine);
7382 qemu_register_machine(&spitzpda_machine);
7383 qemu_register_machine(&borzoipda_machine);
7384 qemu_register_machine(&terrierpda_machine);
7385 qemu_register_machine(&palmte_machine);
7386 #elif defined(TARGET_SH4)
7387 qemu_register_machine(&shix_machine);
7388 qemu_register_machine(&r2d_machine);
7389 #elif defined(TARGET_ALPHA)
7390 /* XXX: TODO */
7391 #elif defined(TARGET_M68K)
7392 qemu_register_machine(&mcf5208evb_machine);
7393 qemu_register_machine(&an5206_machine);
7394 #elif defined(TARGET_CRIS)
7395 qemu_register_machine(&bareetraxfs_machine);
7396 #else
7397 #error unsupported CPU
7398 #endif
7401 #ifdef HAS_AUDIO
7402 struct soundhw soundhw[] = {
7403 #ifdef HAS_AUDIO_CHOICE
7404 #ifdef TARGET_I386
7406 "pcspk",
7407 "PC speaker",
7410 { .init_isa = pcspk_audio_init }
7412 #endif
7414 "sb16",
7415 "Creative Sound Blaster 16",
7418 { .init_isa = SB16_init }
7421 #ifdef CONFIG_ADLIB
7423 "adlib",
7424 #ifdef HAS_YMF262
7425 "Yamaha YMF262 (OPL3)",
7426 #else
7427 "Yamaha YM3812 (OPL2)",
7428 #endif
7431 { .init_isa = Adlib_init }
7433 #endif
7435 #ifdef CONFIG_GUS
7437 "gus",
7438 "Gravis Ultrasound GF1",
7441 { .init_isa = GUS_init }
7443 #endif
7446 "es1370",
7447 "ENSONIQ AudioPCI ES1370",
7450 { .init_pci = es1370_init }
7452 #endif
7454 { NULL, NULL, 0, 0, { NULL } }
7457 static void select_soundhw (const char *optarg)
7459 struct soundhw *c;
7461 if (*optarg == '?') {
7462 show_valid_cards:
7464 printf ("Valid sound card names (comma separated):\n");
7465 for (c = soundhw; c->name; ++c) {
7466 printf ("%-11s %s\n", c->name, c->descr);
7468 printf ("\n-soundhw all will enable all of the above\n");
7469 exit (*optarg != '?');
7471 else {
7472 size_t l;
7473 const char *p;
7474 char *e;
7475 int bad_card = 0;
7477 if (!strcmp (optarg, "all")) {
7478 for (c = soundhw; c->name; ++c) {
7479 c->enabled = 1;
7481 return;
7484 p = optarg;
7485 while (*p) {
7486 e = strchr (p, ',');
7487 l = !e ? strlen (p) : (size_t) (e - p);
7489 for (c = soundhw; c->name; ++c) {
7490 if (!strncmp (c->name, p, l)) {
7491 c->enabled = 1;
7492 break;
7496 if (!c->name) {
7497 if (l > 80) {
7498 fprintf (stderr,
7499 "Unknown sound card name (too big to show)\n");
7501 else {
7502 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7503 (int) l, p);
7505 bad_card = 1;
7507 p += l + (e != NULL);
7510 if (bad_card)
7511 goto show_valid_cards;
7514 #endif
7516 #ifdef _WIN32
7517 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7519 exit(STATUS_CONTROL_C_EXIT);
7520 return TRUE;
7522 #endif
7524 #define MAX_NET_CLIENTS 32
7526 int main(int argc, char **argv)
7528 #ifdef CONFIG_GDBSTUB
7529 int use_gdbstub;
7530 const char *gdbstub_port;
7531 #endif
7532 int i, cdrom_index, pflash_index;
7533 int snapshot, linux_boot;
7534 const char *initrd_filename;
7535 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7536 const char *pflash_filename[MAX_PFLASH];
7537 const char *sd_filename;
7538 const char *mtd_filename;
7539 const char *kernel_filename, *kernel_cmdline;
7540 DisplayState *ds = &display_state;
7541 int cyls, heads, secs, translation;
7542 char net_clients[MAX_NET_CLIENTS][256];
7543 int nb_net_clients;
7544 int optind;
7545 const char *r, *optarg;
7546 CharDriverState *monitor_hd;
7547 char monitor_device[128];
7548 char serial_devices[MAX_SERIAL_PORTS][128];
7549 int serial_device_index;
7550 char parallel_devices[MAX_PARALLEL_PORTS][128];
7551 int parallel_device_index;
7552 const char *loadvm = NULL;
7553 QEMUMachine *machine;
7554 const char *cpu_model;
7555 char usb_devices[MAX_USB_CMDLINE][128];
7556 int usb_devices_index;
7557 int fds[2];
7558 const char *pid_file = NULL;
7559 VLANState *vlan;
7561 LIST_INIT (&vm_change_state_head);
7562 #ifndef _WIN32
7564 struct sigaction act;
7565 sigfillset(&act.sa_mask);
7566 act.sa_flags = 0;
7567 act.sa_handler = SIG_IGN;
7568 sigaction(SIGPIPE, &act, NULL);
7570 #else
7571 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7572 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7573 QEMU to run on a single CPU */
7575 HANDLE h;
7576 DWORD mask, smask;
7577 int i;
7578 h = GetCurrentProcess();
7579 if (GetProcessAffinityMask(h, &mask, &smask)) {
7580 for(i = 0; i < 32; i++) {
7581 if (mask & (1 << i))
7582 break;
7584 if (i != 32) {
7585 mask = 1 << i;
7586 SetProcessAffinityMask(h, mask);
7590 #endif
7592 register_machines();
7593 machine = first_machine;
7594 cpu_model = NULL;
7595 initrd_filename = NULL;
7596 for(i = 0; i < MAX_FD; i++)
7597 fd_filename[i] = NULL;
7598 for(i = 0; i < MAX_DISKS; i++)
7599 hd_filename[i] = NULL;
7600 for(i = 0; i < MAX_PFLASH; i++)
7601 pflash_filename[i] = NULL;
7602 pflash_index = 0;
7603 sd_filename = NULL;
7604 mtd_filename = NULL;
7605 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7606 vga_ram_size = VGA_RAM_SIZE;
7607 #ifdef CONFIG_GDBSTUB
7608 use_gdbstub = 0;
7609 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7610 #endif
7611 snapshot = 0;
7612 nographic = 0;
7613 kernel_filename = NULL;
7614 kernel_cmdline = "";
7615 #ifdef TARGET_PPC
7616 cdrom_index = 1;
7617 #else
7618 cdrom_index = 2;
7619 #endif
7620 cyls = heads = secs = 0;
7621 translation = BIOS_ATA_TRANSLATION_AUTO;
7622 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7624 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7625 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7626 serial_devices[i][0] = '\0';
7627 serial_device_index = 0;
7629 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7630 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7631 parallel_devices[i][0] = '\0';
7632 parallel_device_index = 0;
7634 usb_devices_index = 0;
7636 nb_net_clients = 0;
7638 nb_nics = 0;
7639 /* default mac address of the first network interface */
7641 optind = 1;
7642 for(;;) {
7643 if (optind >= argc)
7644 break;
7645 r = argv[optind];
7646 if (r[0] != '-') {
7647 hd_filename[0] = argv[optind++];
7648 } else {
7649 const QEMUOption *popt;
7651 optind++;
7652 /* Treat --foo the same as -foo. */
7653 if (r[1] == '-')
7654 r++;
7655 popt = qemu_options;
7656 for(;;) {
7657 if (!popt->name) {
7658 fprintf(stderr, "%s: invalid option -- '%s'\n",
7659 argv[0], r);
7660 exit(1);
7662 if (!strcmp(popt->name, r + 1))
7663 break;
7664 popt++;
7666 if (popt->flags & HAS_ARG) {
7667 if (optind >= argc) {
7668 fprintf(stderr, "%s: option '%s' requires an argument\n",
7669 argv[0], r);
7670 exit(1);
7672 optarg = argv[optind++];
7673 } else {
7674 optarg = NULL;
7677 switch(popt->index) {
7678 case QEMU_OPTION_M:
7679 machine = find_machine(optarg);
7680 if (!machine) {
7681 QEMUMachine *m;
7682 printf("Supported machines are:\n");
7683 for(m = first_machine; m != NULL; m = m->next) {
7684 printf("%-10s %s%s\n",
7685 m->name, m->desc,
7686 m == first_machine ? " (default)" : "");
7688 exit(*optarg != '?');
7690 break;
7691 case QEMU_OPTION_cpu:
7692 /* hw initialization will check this */
7693 if (*optarg == '?') {
7694 /* XXX: implement xxx_cpu_list for targets that still miss it */
7695 #if defined(cpu_list)
7696 cpu_list(stdout, &fprintf);
7697 #endif
7698 exit(0);
7699 } else {
7700 cpu_model = optarg;
7702 break;
7703 case QEMU_OPTION_initrd:
7704 initrd_filename = optarg;
7705 break;
7706 case QEMU_OPTION_hda:
7707 case QEMU_OPTION_hdb:
7708 case QEMU_OPTION_hdc:
7709 case QEMU_OPTION_hdd:
7711 int hd_index;
7712 hd_index = popt->index - QEMU_OPTION_hda;
7713 hd_filename[hd_index] = optarg;
7714 if (hd_index == cdrom_index)
7715 cdrom_index = -1;
7717 break;
7718 case QEMU_OPTION_mtdblock:
7719 mtd_filename = optarg;
7720 break;
7721 case QEMU_OPTION_sd:
7722 sd_filename = optarg;
7723 break;
7724 case QEMU_OPTION_pflash:
7725 if (pflash_index >= MAX_PFLASH) {
7726 fprintf(stderr, "qemu: too many parallel flash images\n");
7727 exit(1);
7729 pflash_filename[pflash_index++] = optarg;
7730 break;
7731 case QEMU_OPTION_snapshot:
7732 snapshot = 1;
7733 break;
7734 case QEMU_OPTION_hdachs:
7736 const char *p;
7737 p = optarg;
7738 cyls = strtol(p, (char **)&p, 0);
7739 if (cyls < 1 || cyls > 16383)
7740 goto chs_fail;
7741 if (*p != ',')
7742 goto chs_fail;
7743 p++;
7744 heads = strtol(p, (char **)&p, 0);
7745 if (heads < 1 || heads > 16)
7746 goto chs_fail;
7747 if (*p != ',')
7748 goto chs_fail;
7749 p++;
7750 secs = strtol(p, (char **)&p, 0);
7751 if (secs < 1 || secs > 63)
7752 goto chs_fail;
7753 if (*p == ',') {
7754 p++;
7755 if (!strcmp(p, "none"))
7756 translation = BIOS_ATA_TRANSLATION_NONE;
7757 else if (!strcmp(p, "lba"))
7758 translation = BIOS_ATA_TRANSLATION_LBA;
7759 else if (!strcmp(p, "auto"))
7760 translation = BIOS_ATA_TRANSLATION_AUTO;
7761 else
7762 goto chs_fail;
7763 } else if (*p != '\0') {
7764 chs_fail:
7765 fprintf(stderr, "qemu: invalid physical CHS format\n");
7766 exit(1);
7769 break;
7770 case QEMU_OPTION_nographic:
7771 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7772 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7773 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7774 nographic = 1;
7775 break;
7776 case QEMU_OPTION_portrait:
7777 graphic_rotate = 1;
7778 break;
7779 case QEMU_OPTION_kernel:
7780 kernel_filename = optarg;
7781 break;
7782 case QEMU_OPTION_append:
7783 kernel_cmdline = optarg;
7784 break;
7785 case QEMU_OPTION_cdrom:
7786 if (cdrom_index >= 0) {
7787 hd_filename[cdrom_index] = optarg;
7789 break;
7790 case QEMU_OPTION_boot:
7791 boot_device = optarg[0];
7792 if (boot_device != 'a' &&
7793 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7794 // Network boot
7795 boot_device != 'n' &&
7796 #endif
7797 boot_device != 'c' && boot_device != 'd') {
7798 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7799 exit(1);
7801 break;
7802 case QEMU_OPTION_fda:
7803 fd_filename[0] = optarg;
7804 break;
7805 case QEMU_OPTION_fdb:
7806 fd_filename[1] = optarg;
7807 break;
7808 #ifdef TARGET_I386
7809 case QEMU_OPTION_no_fd_bootchk:
7810 fd_bootchk = 0;
7811 break;
7812 #endif
7813 case QEMU_OPTION_no_code_copy:
7814 code_copy_enabled = 0;
7815 break;
7816 case QEMU_OPTION_net:
7817 if (nb_net_clients >= MAX_NET_CLIENTS) {
7818 fprintf(stderr, "qemu: too many network clients\n");
7819 exit(1);
7821 pstrcpy(net_clients[nb_net_clients],
7822 sizeof(net_clients[0]),
7823 optarg);
7824 nb_net_clients++;
7825 break;
7826 #ifdef CONFIG_SLIRP
7827 case QEMU_OPTION_tftp:
7828 tftp_prefix = optarg;
7829 break;
7830 case QEMU_OPTION_bootp:
7831 bootp_filename = optarg;
7832 break;
7833 #ifndef _WIN32
7834 case QEMU_OPTION_smb:
7835 net_slirp_smb(optarg);
7836 break;
7837 #endif
7838 case QEMU_OPTION_redir:
7839 net_slirp_redir(optarg);
7840 break;
7841 #endif
7842 #ifdef HAS_AUDIO
7843 case QEMU_OPTION_audio_help:
7844 AUD_help ();
7845 exit (0);
7846 break;
7847 case QEMU_OPTION_soundhw:
7848 select_soundhw (optarg);
7849 break;
7850 #endif
7851 case QEMU_OPTION_h:
7852 help(0);
7853 break;
7854 case QEMU_OPTION_m:
7855 ram_size = atoi(optarg) * 1024 * 1024;
7856 if (ram_size <= 0)
7857 help(1);
7858 if (ram_size > PHYS_RAM_MAX_SIZE) {
7859 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7860 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7861 exit(1);
7863 break;
7864 case QEMU_OPTION_d:
7866 int mask;
7867 CPULogItem *item;
7869 mask = cpu_str_to_log_mask(optarg);
7870 if (!mask) {
7871 printf("Log items (comma separated):\n");
7872 for(item = cpu_log_items; item->mask != 0; item++) {
7873 printf("%-10s %s\n", item->name, item->help);
7875 exit(1);
7877 cpu_set_log(mask);
7879 break;
7880 #ifdef CONFIG_GDBSTUB
7881 case QEMU_OPTION_s:
7882 use_gdbstub = 1;
7883 break;
7884 case QEMU_OPTION_p:
7885 gdbstub_port = optarg;
7886 break;
7887 #endif
7888 case QEMU_OPTION_L:
7889 bios_dir = optarg;
7890 break;
7891 case QEMU_OPTION_bios:
7892 bios_name = optarg;
7893 break;
7894 case QEMU_OPTION_S:
7895 autostart = 0;
7896 break;
7897 case QEMU_OPTION_k:
7898 keyboard_layout = optarg;
7899 break;
7900 case QEMU_OPTION_localtime:
7901 rtc_utc = 0;
7902 break;
7903 case QEMU_OPTION_cirrusvga:
7904 cirrus_vga_enabled = 1;
7905 vmsvga_enabled = 0;
7906 break;
7907 case QEMU_OPTION_vmsvga:
7908 cirrus_vga_enabled = 0;
7909 vmsvga_enabled = 1;
7910 break;
7911 case QEMU_OPTION_std_vga:
7912 cirrus_vga_enabled = 0;
7913 vmsvga_enabled = 0;
7914 break;
7915 case QEMU_OPTION_g:
7917 const char *p;
7918 int w, h, depth;
7919 p = optarg;
7920 w = strtol(p, (char **)&p, 10);
7921 if (w <= 0) {
7922 graphic_error:
7923 fprintf(stderr, "qemu: invalid resolution or depth\n");
7924 exit(1);
7926 if (*p != 'x')
7927 goto graphic_error;
7928 p++;
7929 h = strtol(p, (char **)&p, 10);
7930 if (h <= 0)
7931 goto graphic_error;
7932 if (*p == 'x') {
7933 p++;
7934 depth = strtol(p, (char **)&p, 10);
7935 if (depth != 8 && depth != 15 && depth != 16 &&
7936 depth != 24 && depth != 32)
7937 goto graphic_error;
7938 } else if (*p == '\0') {
7939 depth = graphic_depth;
7940 } else {
7941 goto graphic_error;
7944 graphic_width = w;
7945 graphic_height = h;
7946 graphic_depth = depth;
7948 break;
7949 case QEMU_OPTION_echr:
7951 char *r;
7952 term_escape_char = strtol(optarg, &r, 0);
7953 if (r == optarg)
7954 printf("Bad argument to echr\n");
7955 break;
7957 case QEMU_OPTION_monitor:
7958 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7959 break;
7960 case QEMU_OPTION_serial:
7961 if (serial_device_index >= MAX_SERIAL_PORTS) {
7962 fprintf(stderr, "qemu: too many serial ports\n");
7963 exit(1);
7965 pstrcpy(serial_devices[serial_device_index],
7966 sizeof(serial_devices[0]), optarg);
7967 serial_device_index++;
7968 break;
7969 case QEMU_OPTION_parallel:
7970 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7971 fprintf(stderr, "qemu: too many parallel ports\n");
7972 exit(1);
7974 pstrcpy(parallel_devices[parallel_device_index],
7975 sizeof(parallel_devices[0]), optarg);
7976 parallel_device_index++;
7977 break;
7978 case QEMU_OPTION_loadvm:
7979 loadvm = optarg;
7980 break;
7981 case QEMU_OPTION_full_screen:
7982 full_screen = 1;
7983 break;
7984 #ifdef CONFIG_SDL
7985 case QEMU_OPTION_no_frame:
7986 no_frame = 1;
7987 break;
7988 case QEMU_OPTION_alt_grab:
7989 alt_grab = 1;
7990 break;
7991 case QEMU_OPTION_no_quit:
7992 no_quit = 1;
7993 break;
7994 #endif
7995 case QEMU_OPTION_pidfile:
7996 pid_file = optarg;
7997 break;
7998 #ifdef TARGET_I386
7999 case QEMU_OPTION_win2k_hack:
8000 win2k_install_hack = 1;
8001 break;
8002 #endif
8003 #ifdef USE_KQEMU
8004 case QEMU_OPTION_no_kqemu:
8005 kqemu_allowed = 0;
8006 break;
8007 case QEMU_OPTION_kernel_kqemu:
8008 kqemu_allowed = 2;
8009 break;
8010 #endif
8011 case QEMU_OPTION_usb:
8012 usb_enabled = 1;
8013 break;
8014 case QEMU_OPTION_usbdevice:
8015 usb_enabled = 1;
8016 if (usb_devices_index >= MAX_USB_CMDLINE) {
8017 fprintf(stderr, "Too many USB devices\n");
8018 exit(1);
8020 pstrcpy(usb_devices[usb_devices_index],
8021 sizeof(usb_devices[usb_devices_index]),
8022 optarg);
8023 usb_devices_index++;
8024 break;
8025 case QEMU_OPTION_smp:
8026 smp_cpus = atoi(optarg);
8027 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8028 fprintf(stderr, "Invalid number of CPUs\n");
8029 exit(1);
8031 break;
8032 case QEMU_OPTION_vnc:
8033 vnc_display = optarg;
8034 break;
8035 case QEMU_OPTION_no_acpi:
8036 acpi_enabled = 0;
8037 break;
8038 case QEMU_OPTION_no_reboot:
8039 no_reboot = 1;
8040 break;
8041 case QEMU_OPTION_show_cursor:
8042 cursor_hide = 0;
8043 break;
8044 case QEMU_OPTION_daemonize:
8045 daemonize = 1;
8046 break;
8047 case QEMU_OPTION_option_rom:
8048 if (nb_option_roms >= MAX_OPTION_ROMS) {
8049 fprintf(stderr, "Too many option ROMs\n");
8050 exit(1);
8052 option_rom[nb_option_roms] = optarg;
8053 nb_option_roms++;
8054 break;
8055 case QEMU_OPTION_semihosting:
8056 semihosting_enabled = 1;
8057 break;
8058 case QEMU_OPTION_name:
8059 qemu_name = optarg;
8060 break;
8061 #ifdef TARGET_SPARC
8062 case QEMU_OPTION_prom_env:
8063 if (nb_prom_envs >= MAX_PROM_ENVS) {
8064 fprintf(stderr, "Too many prom variables\n");
8065 exit(1);
8067 prom_envs[nb_prom_envs] = optarg;
8068 nb_prom_envs++;
8069 break;
8070 #endif
8071 #ifdef TARGET_ARM
8072 case QEMU_OPTION_old_param:
8073 old_param = 1;
8074 #endif
8075 case QEMU_OPTION_clock:
8076 configure_alarms(optarg);
8077 break;
8082 #ifndef _WIN32
8083 if (daemonize && !nographic && vnc_display == NULL) {
8084 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8085 daemonize = 0;
8088 if (daemonize) {
8089 pid_t pid;
8091 if (pipe(fds) == -1)
8092 exit(1);
8094 pid = fork();
8095 if (pid > 0) {
8096 uint8_t status;
8097 ssize_t len;
8099 close(fds[1]);
8101 again:
8102 len = read(fds[0], &status, 1);
8103 if (len == -1 && (errno == EINTR))
8104 goto again;
8106 if (len != 1)
8107 exit(1);
8108 else if (status == 1) {
8109 fprintf(stderr, "Could not acquire pidfile\n");
8110 exit(1);
8111 } else
8112 exit(0);
8113 } else if (pid < 0)
8114 exit(1);
8116 setsid();
8118 pid = fork();
8119 if (pid > 0)
8120 exit(0);
8121 else if (pid < 0)
8122 exit(1);
8124 umask(027);
8125 chdir("/");
8127 signal(SIGTSTP, SIG_IGN);
8128 signal(SIGTTOU, SIG_IGN);
8129 signal(SIGTTIN, SIG_IGN);
8131 #endif
8133 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8134 if (daemonize) {
8135 uint8_t status = 1;
8136 write(fds[1], &status, 1);
8137 } else
8138 fprintf(stderr, "Could not acquire pid file\n");
8139 exit(1);
8142 #ifdef USE_KQEMU
8143 if (smp_cpus > 1)
8144 kqemu_allowed = 0;
8145 #endif
8146 linux_boot = (kernel_filename != NULL);
8148 if (!linux_boot &&
8149 boot_device != 'n' &&
8150 hd_filename[0] == '\0' &&
8151 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8152 fd_filename[0] == '\0')
8153 help(1);
8155 /* boot to floppy or the default cd if no hard disk defined yet */
8156 if (hd_filename[0] == '\0' && boot_device == 'c') {
8157 if (fd_filename[0] != '\0')
8158 boot_device = 'a';
8159 else
8160 boot_device = 'd';
8163 setvbuf(stdout, NULL, _IOLBF, 0);
8165 init_timers();
8166 init_timer_alarm();
8167 qemu_aio_init();
8169 #ifdef _WIN32
8170 socket_init();
8171 #endif
8173 /* init network clients */
8174 if (nb_net_clients == 0) {
8175 /* if no clients, we use a default config */
8176 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8177 "nic");
8178 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8179 "user");
8180 nb_net_clients = 2;
8183 for(i = 0;i < nb_net_clients; i++) {
8184 if (net_client_init(net_clients[i]) < 0)
8185 exit(1);
8187 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8188 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8189 continue;
8190 if (vlan->nb_guest_devs == 0) {
8191 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8192 exit(1);
8194 if (vlan->nb_host_devs == 0)
8195 fprintf(stderr,
8196 "Warning: vlan %d is not connected to host network\n",
8197 vlan->id);
8200 #ifdef TARGET_I386
8201 if (boot_device == 'n') {
8202 for (i = 0; i < nb_nics; i++) {
8203 const char *model = nd_table[i].model;
8204 char buf[1024];
8205 if (model == NULL)
8206 model = "ne2k_pci";
8207 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8208 if (get_image_size(buf) > 0) {
8209 option_rom[nb_option_roms] = strdup(buf);
8210 nb_option_roms++;
8211 break;
8214 if (i == nb_nics) {
8215 fprintf(stderr, "No valid PXE rom found for network device\n");
8216 exit(1);
8219 #endif
8221 /* init the memory */
8222 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8224 phys_ram_base = qemu_vmalloc(phys_ram_size);
8225 if (!phys_ram_base) {
8226 fprintf(stderr, "Could not allocate physical memory\n");
8227 exit(1);
8230 /* we always create the cdrom drive, even if no disk is there */
8231 bdrv_init();
8232 if (cdrom_index >= 0) {
8233 bs_table[cdrom_index] = bdrv_new("cdrom");
8234 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8237 /* open the virtual block devices */
8238 for(i = 0; i < MAX_DISKS; i++) {
8239 if (hd_filename[i]) {
8240 if (!bs_table[i]) {
8241 char buf[64];
8242 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8243 bs_table[i] = bdrv_new(buf);
8245 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8246 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8247 hd_filename[i]);
8248 exit(1);
8250 if (i == 0 && cyls != 0) {
8251 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8252 bdrv_set_translation_hint(bs_table[i], translation);
8257 /* we always create at least one floppy disk */
8258 fd_table[0] = bdrv_new("fda");
8259 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8261 for(i = 0; i < MAX_FD; i++) {
8262 if (fd_filename[i]) {
8263 if (!fd_table[i]) {
8264 char buf[64];
8265 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8266 fd_table[i] = bdrv_new(buf);
8267 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8269 if (fd_filename[i][0] != '\0') {
8270 if (bdrv_open(fd_table[i], fd_filename[i],
8271 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8272 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8273 fd_filename[i]);
8274 exit(1);
8280 /* Open the virtual parallel flash block devices */
8281 for(i = 0; i < MAX_PFLASH; i++) {
8282 if (pflash_filename[i]) {
8283 if (!pflash_table[i]) {
8284 char buf[64];
8285 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8286 pflash_table[i] = bdrv_new(buf);
8288 if (bdrv_open(pflash_table[i], pflash_filename[i],
8289 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8290 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8291 pflash_filename[i]);
8292 exit(1);
8297 sd_bdrv = bdrv_new ("sd");
8298 /* FIXME: This isn't really a floppy, but it's a reasonable
8299 approximation. */
8300 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8301 if (sd_filename) {
8302 if (bdrv_open(sd_bdrv, sd_filename,
8303 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8304 fprintf(stderr, "qemu: could not open SD card image %s\n",
8305 sd_filename);
8306 } else
8307 qemu_key_check(sd_bdrv, sd_filename);
8310 if (mtd_filename) {
8311 mtd_bdrv = bdrv_new ("mtd");
8312 if (bdrv_open(mtd_bdrv, mtd_filename,
8313 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8314 qemu_key_check(mtd_bdrv, mtd_filename)) {
8315 fprintf(stderr, "qemu: could not open Flash image %s\n",
8316 mtd_filename);
8317 bdrv_delete(mtd_bdrv);
8318 mtd_bdrv = 0;
8322 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8323 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8325 init_ioports();
8327 /* terminal init */
8328 memset(&display_state, 0, sizeof(display_state));
8329 if (nographic) {
8330 /* nearly nothing to do */
8331 dumb_display_init(ds);
8332 } else if (vnc_display != NULL) {
8333 vnc_display_init(ds);
8334 if (vnc_display_open(ds, vnc_display) < 0)
8335 exit(1);
8336 } else {
8337 #if defined(CONFIG_SDL)
8338 sdl_display_init(ds, full_screen, no_frame);
8339 #elif defined(CONFIG_COCOA)
8340 cocoa_display_init(ds, full_screen);
8341 #endif
8344 /* Maintain compatibility with multiple stdio monitors */
8345 if (!strcmp(monitor_device,"stdio")) {
8346 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8347 if (!strcmp(serial_devices[i],"mon:stdio")) {
8348 monitor_device[0] = '\0';
8349 break;
8350 } else if (!strcmp(serial_devices[i],"stdio")) {
8351 monitor_device[0] = '\0';
8352 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8353 break;
8357 if (monitor_device[0] != '\0') {
8358 monitor_hd = qemu_chr_open(monitor_device);
8359 if (!monitor_hd) {
8360 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8361 exit(1);
8363 monitor_init(monitor_hd, !nographic);
8366 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8367 const char *devname = serial_devices[i];
8368 if (devname[0] != '\0' && strcmp(devname, "none")) {
8369 serial_hds[i] = qemu_chr_open(devname);
8370 if (!serial_hds[i]) {
8371 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8372 devname);
8373 exit(1);
8375 if (strstart(devname, "vc", 0))
8376 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8380 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8381 const char *devname = parallel_devices[i];
8382 if (devname[0] != '\0' && strcmp(devname, "none")) {
8383 parallel_hds[i] = qemu_chr_open(devname);
8384 if (!parallel_hds[i]) {
8385 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8386 devname);
8387 exit(1);
8389 if (strstart(devname, "vc", 0))
8390 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8394 machine->init(ram_size, vga_ram_size, boot_device,
8395 ds, fd_filename, snapshot,
8396 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8398 /* init USB devices */
8399 if (usb_enabled) {
8400 for(i = 0; i < usb_devices_index; i++) {
8401 if (usb_device_add(usb_devices[i]) < 0) {
8402 fprintf(stderr, "Warning: could not add USB device %s\n",
8403 usb_devices[i]);
8408 if (display_state.dpy_refresh) {
8409 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8410 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8413 #ifdef CONFIG_GDBSTUB
8414 if (use_gdbstub) {
8415 /* XXX: use standard host:port notation and modify options
8416 accordingly. */
8417 if (gdbserver_start(gdbstub_port) < 0) {
8418 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8419 gdbstub_port);
8420 exit(1);
8423 #endif
8425 if (loadvm)
8426 do_loadvm(loadvm);
8429 /* XXX: simplify init */
8430 read_passwords();
8431 if (autostart) {
8432 vm_start();
8436 if (daemonize) {
8437 uint8_t status = 0;
8438 ssize_t len;
8439 int fd;
8441 again1:
8442 len = write(fds[1], &status, 1);
8443 if (len == -1 && (errno == EINTR))
8444 goto again1;
8446 if (len != 1)
8447 exit(1);
8449 TFR(fd = open("/dev/null", O_RDWR));
8450 if (fd == -1)
8451 exit(1);
8453 dup2(fd, 0);
8454 dup2(fd, 1);
8455 dup2(fd, 2);
8457 close(fd);
8460 main_loop();
8461 quit_timers();
8462 return 0;