RAM usage information in machine definition.
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blob0825281ef938d535b8fbe922fbf3bdb3f61e1cd4
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 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 "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <sys/time.h>
47 #include <zlib.h>
49 #ifndef _WIN32
50 #include <sys/times.h>
51 #include <sys/wait.h>
52 #include <termios.h>
53 #include <sys/poll.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <dirent.h>
59 #include <netdb.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #ifndef __APPLE__
65 #include <libutil.h>
66 #endif
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
69 #else
70 #ifndef __sun__
71 #include <linux/if.h>
72 #include <linux/if_tun.h>
73 #include <pty.h>
74 #include <malloc.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
80 #include "hpet.h"
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
84 #else
85 #include <sys/stat.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
95 #include <net/if.h>
96 #include <syslog.h>
97 #include <stropts.h>
98 #endif
99 #endif
100 #else
101 #include <winsock2.h>
102 int inet_aton(const char *cp, struct in_addr *ia);
103 #endif
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
107 #endif
109 #ifdef _WIN32
110 #include <malloc.h>
111 #include <sys/timeb.h>
112 #include <mmsystem.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
115 #endif
117 #include "qemu_socket.h"
119 #ifdef CONFIG_SDL
120 #ifdef __APPLE__
121 #include <SDL/SDL.h>
122 #endif
123 #endif /* CONFIG_SDL */
125 #ifdef CONFIG_COCOA
126 #undef main
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
130 #include "disas.h"
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136 #ifdef __sun__
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138 #else
139 #define SMBD_COMMAND "/usr/sbin/smbd"
140 #endif
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
145 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
147 #ifdef TARGET_PPC
148 #define DEFAULT_RAM_SIZE 144
149 #else
150 #define DEFAULT_RAM_SIZE 128
151 #endif
152 /* in ms */
153 #define GUI_REFRESH_INTERVAL 30
155 /* Max number of USB devices that can be specified on the commandline. */
156 #define MAX_USB_CMDLINE 8
158 /* XXX: use a two level table to limit memory usage */
159 #define MAX_IOPORTS 65536
161 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162 const char *bios_name = NULL;
163 void *ioport_opaque[MAX_IOPORTS];
164 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
167 to store the VM snapshots */
168 DriveInfo drives_table[MAX_DRIVES+1];
169 int nb_drives;
170 /* point to the block driver where the snapshots are managed */
171 BlockDriverState *bs_snapshots;
172 int vga_ram_size;
173 static DisplayState display_state;
174 int nographic;
175 int curses;
176 const char* keyboard_layout = NULL;
177 int64_t ticks_per_sec;
178 int ram_size;
179 int pit_min_timer_count = 0;
180 int nb_nics;
181 NICInfo nd_table[MAX_NICS];
182 int vm_running;
183 static int rtc_utc = 1;
184 static int rtc_date_offset = -1; /* -1 means no change */
185 int cirrus_vga_enabled = 1;
186 int vmsvga_enabled = 0;
187 #ifdef TARGET_SPARC
188 int graphic_width = 1024;
189 int graphic_height = 768;
190 int graphic_depth = 8;
191 #else
192 int graphic_width = 800;
193 int graphic_height = 600;
194 int graphic_depth = 15;
195 #endif
196 int full_screen = 0;
197 int no_frame = 0;
198 int no_quit = 0;
199 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
200 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
201 #ifdef TARGET_I386
202 int win2k_install_hack = 0;
203 #endif
204 int usb_enabled = 0;
205 static VLANState *first_vlan;
206 int smp_cpus = 1;
207 const char *vnc_display;
208 #if defined(TARGET_SPARC)
209 #define MAX_CPUS 16
210 #elif defined(TARGET_I386)
211 #define MAX_CPUS 255
212 #else
213 #define MAX_CPUS 1
214 #endif
215 int acpi_enabled = 1;
216 int fd_bootchk = 1;
217 int no_reboot = 0;
218 int no_shutdown = 0;
219 int cursor_hide = 1;
220 int graphic_rotate = 0;
221 int daemonize = 0;
222 const char *option_rom[MAX_OPTION_ROMS];
223 int nb_option_roms;
224 int semihosting_enabled = 0;
225 int autostart = 1;
226 #ifdef TARGET_ARM
227 int old_param = 0;
228 #endif
229 const char *qemu_name;
230 int alt_grab = 0;
231 #ifdef TARGET_SPARC
232 unsigned int nb_prom_envs = 0;
233 const char *prom_envs[MAX_PROM_ENVS];
234 #endif
235 int nb_drives_opt;
236 struct drive_opt {
237 const char *file;
238 char opt[1024];
239 } drives_opt[MAX_DRIVES];
241 static CPUState *cur_cpu;
242 static CPUState *next_cpu;
243 static int event_pending = 1;
245 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
247 /***********************************************************/
248 /* x86 ISA bus support */
250 target_phys_addr_t isa_mem_base = 0;
251 PicState2 *isa_pic;
253 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
255 #ifdef DEBUG_UNUSED_IOPORT
256 fprintf(stderr, "unused inb: port=0x%04x\n", address);
257 #endif
258 return 0xff;
261 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
263 #ifdef DEBUG_UNUSED_IOPORT
264 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
265 #endif
268 /* default is to make two byte accesses */
269 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
271 uint32_t data;
272 data = ioport_read_table[0][address](ioport_opaque[address], address);
273 address = (address + 1) & (MAX_IOPORTS - 1);
274 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
275 return data;
278 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
280 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
281 address = (address + 1) & (MAX_IOPORTS - 1);
282 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
285 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
287 #ifdef DEBUG_UNUSED_IOPORT
288 fprintf(stderr, "unused inl: port=0x%04x\n", address);
289 #endif
290 return 0xffffffff;
293 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
295 #ifdef DEBUG_UNUSED_IOPORT
296 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
297 #endif
300 static void init_ioports(void)
302 int i;
304 for(i = 0; i < MAX_IOPORTS; i++) {
305 ioport_read_table[0][i] = default_ioport_readb;
306 ioport_write_table[0][i] = default_ioport_writeb;
307 ioport_read_table[1][i] = default_ioport_readw;
308 ioport_write_table[1][i] = default_ioport_writew;
309 ioport_read_table[2][i] = default_ioport_readl;
310 ioport_write_table[2][i] = default_ioport_writel;
314 /* size is the word size in byte */
315 int register_ioport_read(int start, int length, int size,
316 IOPortReadFunc *func, void *opaque)
318 int i, bsize;
320 if (size == 1) {
321 bsize = 0;
322 } else if (size == 2) {
323 bsize = 1;
324 } else if (size == 4) {
325 bsize = 2;
326 } else {
327 hw_error("register_ioport_read: invalid size");
328 return -1;
330 for(i = start; i < start + length; i += size) {
331 ioport_read_table[bsize][i] = func;
332 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
333 hw_error("register_ioport_read: invalid opaque");
334 ioport_opaque[i] = opaque;
336 return 0;
339 /* size is the word size in byte */
340 int register_ioport_write(int start, int length, int size,
341 IOPortWriteFunc *func, void *opaque)
343 int i, bsize;
345 if (size == 1) {
346 bsize = 0;
347 } else if (size == 2) {
348 bsize = 1;
349 } else if (size == 4) {
350 bsize = 2;
351 } else {
352 hw_error("register_ioport_write: invalid size");
353 return -1;
355 for(i = start; i < start + length; i += size) {
356 ioport_write_table[bsize][i] = func;
357 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
358 hw_error("register_ioport_write: invalid opaque");
359 ioport_opaque[i] = opaque;
361 return 0;
364 void isa_unassign_ioport(int start, int length)
366 int i;
368 for(i = start; i < start + length; i++) {
369 ioport_read_table[0][i] = default_ioport_readb;
370 ioport_read_table[1][i] = default_ioport_readw;
371 ioport_read_table[2][i] = default_ioport_readl;
373 ioport_write_table[0][i] = default_ioport_writeb;
374 ioport_write_table[1][i] = default_ioport_writew;
375 ioport_write_table[2][i] = default_ioport_writel;
379 /***********************************************************/
381 void cpu_outb(CPUState *env, int addr, int val)
383 #ifdef DEBUG_IOPORT
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "outb: %04x %02x\n", addr, val);
386 #endif
387 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
388 #ifdef USE_KQEMU
389 if (env)
390 env->last_io_time = cpu_get_time_fast();
391 #endif
394 void cpu_outw(CPUState *env, int addr, int val)
396 #ifdef DEBUG_IOPORT
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "outw: %04x %04x\n", addr, val);
399 #endif
400 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
401 #ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
404 #endif
407 void cpu_outl(CPUState *env, int addr, int val)
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "outl: %04x %08x\n", addr, val);
412 #endif
413 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
420 int cpu_inb(CPUState *env, int addr)
422 int val;
423 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
424 #ifdef DEBUG_IOPORT
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "inb : %04x %02x\n", addr, val);
427 #endif
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
432 return val;
435 int cpu_inw(CPUState *env, int addr)
437 int val;
438 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
439 #ifdef DEBUG_IOPORT
440 if (loglevel & CPU_LOG_IOPORT)
441 fprintf(logfile, "inw : %04x %04x\n", addr, val);
442 #endif
443 #ifdef USE_KQEMU
444 if (env)
445 env->last_io_time = cpu_get_time_fast();
446 #endif
447 return val;
450 int cpu_inl(CPUState *env, int addr)
452 int val;
453 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
454 #ifdef DEBUG_IOPORT
455 if (loglevel & CPU_LOG_IOPORT)
456 fprintf(logfile, "inl : %04x %08x\n", addr, val);
457 #endif
458 #ifdef USE_KQEMU
459 if (env)
460 env->last_io_time = cpu_get_time_fast();
461 #endif
462 return val;
465 /***********************************************************/
466 void hw_error(const char *fmt, ...)
468 va_list ap;
469 CPUState *env;
471 va_start(ap, fmt);
472 fprintf(stderr, "qemu: hardware error: ");
473 vfprintf(stderr, fmt, ap);
474 fprintf(stderr, "\n");
475 for(env = first_cpu; env != NULL; env = env->next_cpu) {
476 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
477 #ifdef TARGET_I386
478 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
479 #else
480 cpu_dump_state(env, stderr, fprintf, 0);
481 #endif
483 va_end(ap);
484 abort();
487 /***********************************************************/
488 /* keyboard/mouse */
490 static QEMUPutKBDEvent *qemu_put_kbd_event;
491 static void *qemu_put_kbd_event_opaque;
492 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
493 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
495 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
497 qemu_put_kbd_event_opaque = opaque;
498 qemu_put_kbd_event = func;
501 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
502 void *opaque, int absolute,
503 const char *name)
505 QEMUPutMouseEntry *s, *cursor;
507 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
508 if (!s)
509 return NULL;
511 s->qemu_put_mouse_event = func;
512 s->qemu_put_mouse_event_opaque = opaque;
513 s->qemu_put_mouse_event_absolute = absolute;
514 s->qemu_put_mouse_event_name = qemu_strdup(name);
515 s->next = NULL;
517 if (!qemu_put_mouse_event_head) {
518 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
519 return s;
522 cursor = qemu_put_mouse_event_head;
523 while (cursor->next != NULL)
524 cursor = cursor->next;
526 cursor->next = s;
527 qemu_put_mouse_event_current = s;
529 return s;
532 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
534 QEMUPutMouseEntry *prev = NULL, *cursor;
536 if (!qemu_put_mouse_event_head || entry == NULL)
537 return;
539 cursor = qemu_put_mouse_event_head;
540 while (cursor != NULL && cursor != entry) {
541 prev = cursor;
542 cursor = cursor->next;
545 if (cursor == NULL) // does not exist or list empty
546 return;
547 else if (prev == NULL) { // entry is head
548 qemu_put_mouse_event_head = cursor->next;
549 if (qemu_put_mouse_event_current == entry)
550 qemu_put_mouse_event_current = cursor->next;
551 qemu_free(entry->qemu_put_mouse_event_name);
552 qemu_free(entry);
553 return;
556 prev->next = entry->next;
558 if (qemu_put_mouse_event_current == entry)
559 qemu_put_mouse_event_current = prev;
561 qemu_free(entry->qemu_put_mouse_event_name);
562 qemu_free(entry);
565 void kbd_put_keycode(int keycode)
567 if (qemu_put_kbd_event) {
568 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
572 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
574 QEMUPutMouseEvent *mouse_event;
575 void *mouse_event_opaque;
576 int width;
578 if (!qemu_put_mouse_event_current) {
579 return;
582 mouse_event =
583 qemu_put_mouse_event_current->qemu_put_mouse_event;
584 mouse_event_opaque =
585 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
587 if (mouse_event) {
588 if (graphic_rotate) {
589 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
590 width = 0x7fff;
591 else
592 width = graphic_width - 1;
593 mouse_event(mouse_event_opaque,
594 width - dy, dx, dz, buttons_state);
595 } else
596 mouse_event(mouse_event_opaque,
597 dx, dy, dz, buttons_state);
601 int kbd_mouse_is_absolute(void)
603 if (!qemu_put_mouse_event_current)
604 return 0;
606 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
609 void do_info_mice(void)
611 QEMUPutMouseEntry *cursor;
612 int index = 0;
614 if (!qemu_put_mouse_event_head) {
615 term_printf("No mouse devices connected\n");
616 return;
619 term_printf("Mouse devices available:\n");
620 cursor = qemu_put_mouse_event_head;
621 while (cursor != NULL) {
622 term_printf("%c Mouse #%d: %s\n",
623 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
624 index, cursor->qemu_put_mouse_event_name);
625 index++;
626 cursor = cursor->next;
630 void do_mouse_set(int index)
632 QEMUPutMouseEntry *cursor;
633 int i = 0;
635 if (!qemu_put_mouse_event_head) {
636 term_printf("No mouse devices connected\n");
637 return;
640 cursor = qemu_put_mouse_event_head;
641 while (cursor != NULL && index != i) {
642 i++;
643 cursor = cursor->next;
646 if (cursor != NULL)
647 qemu_put_mouse_event_current = cursor;
648 else
649 term_printf("Mouse at given index not found\n");
652 /* compute with 96 bit intermediate result: (a*b)/c */
653 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
655 union {
656 uint64_t ll;
657 struct {
658 #ifdef WORDS_BIGENDIAN
659 uint32_t high, low;
660 #else
661 uint32_t low, high;
662 #endif
663 } l;
664 } u, res;
665 uint64_t rl, rh;
667 u.ll = a;
668 rl = (uint64_t)u.l.low * (uint64_t)b;
669 rh = (uint64_t)u.l.high * (uint64_t)b;
670 rh += (rl >> 32);
671 res.l.high = rh / c;
672 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
673 return res.ll;
676 /***********************************************************/
677 /* real time host monotonic timer */
679 #define QEMU_TIMER_BASE 1000000000LL
681 #ifdef WIN32
683 static int64_t clock_freq;
685 static void init_get_clock(void)
687 LARGE_INTEGER freq;
688 int ret;
689 ret = QueryPerformanceFrequency(&freq);
690 if (ret == 0) {
691 fprintf(stderr, "Could not calibrate ticks\n");
692 exit(1);
694 clock_freq = freq.QuadPart;
697 static int64_t get_clock(void)
699 LARGE_INTEGER ti;
700 QueryPerformanceCounter(&ti);
701 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
704 #else
706 static int use_rt_clock;
708 static void init_get_clock(void)
710 use_rt_clock = 0;
711 #if defined(__linux__)
713 struct timespec ts;
714 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
715 use_rt_clock = 1;
718 #endif
721 static int64_t get_clock(void)
723 #if defined(__linux__)
724 if (use_rt_clock) {
725 struct timespec ts;
726 clock_gettime(CLOCK_MONOTONIC, &ts);
727 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
728 } else
729 #endif
731 /* XXX: using gettimeofday leads to problems if the date
732 changes, so it should be avoided. */
733 struct timeval tv;
734 gettimeofday(&tv, NULL);
735 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
739 #endif
741 /***********************************************************/
742 /* guest cycle counter */
744 static int64_t cpu_ticks_prev;
745 static int64_t cpu_ticks_offset;
746 static int64_t cpu_clock_offset;
747 static int cpu_ticks_enabled;
749 /* return the host CPU cycle counter and handle stop/restart */
750 int64_t cpu_get_ticks(void)
752 if (!cpu_ticks_enabled) {
753 return cpu_ticks_offset;
754 } else {
755 int64_t ticks;
756 ticks = cpu_get_real_ticks();
757 if (cpu_ticks_prev > ticks) {
758 /* Note: non increasing ticks may happen if the host uses
759 software suspend */
760 cpu_ticks_offset += cpu_ticks_prev - ticks;
762 cpu_ticks_prev = ticks;
763 return ticks + cpu_ticks_offset;
767 /* return the host CPU monotonic timer and handle stop/restart */
768 static int64_t cpu_get_clock(void)
770 int64_t ti;
771 if (!cpu_ticks_enabled) {
772 return cpu_clock_offset;
773 } else {
774 ti = get_clock();
775 return ti + cpu_clock_offset;
779 /* enable cpu_get_ticks() */
780 void cpu_enable_ticks(void)
782 if (!cpu_ticks_enabled) {
783 cpu_ticks_offset -= cpu_get_real_ticks();
784 cpu_clock_offset -= get_clock();
785 cpu_ticks_enabled = 1;
789 /* disable cpu_get_ticks() : the clock is stopped. You must not call
790 cpu_get_ticks() after that. */
791 void cpu_disable_ticks(void)
793 if (cpu_ticks_enabled) {
794 cpu_ticks_offset = cpu_get_ticks();
795 cpu_clock_offset = cpu_get_clock();
796 cpu_ticks_enabled = 0;
800 /***********************************************************/
801 /* timers */
803 #define QEMU_TIMER_REALTIME 0
804 #define QEMU_TIMER_VIRTUAL 1
806 struct QEMUClock {
807 int type;
808 /* XXX: add frequency */
811 struct QEMUTimer {
812 QEMUClock *clock;
813 int64_t expire_time;
814 QEMUTimerCB *cb;
815 void *opaque;
816 struct QEMUTimer *next;
819 struct qemu_alarm_timer {
820 char const *name;
821 unsigned int flags;
823 int (*start)(struct qemu_alarm_timer *t);
824 void (*stop)(struct qemu_alarm_timer *t);
825 void (*rearm)(struct qemu_alarm_timer *t);
826 void *priv;
829 #define ALARM_FLAG_DYNTICKS 0x1
830 #define ALARM_FLAG_EXPIRED 0x2
832 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
834 return t->flags & ALARM_FLAG_DYNTICKS;
837 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
839 if (!alarm_has_dynticks(t))
840 return;
842 t->rearm(t);
845 /* TODO: MIN_TIMER_REARM_US should be optimized */
846 #define MIN_TIMER_REARM_US 250
848 static struct qemu_alarm_timer *alarm_timer;
850 #ifdef _WIN32
852 struct qemu_alarm_win32 {
853 MMRESULT timerId;
854 HANDLE host_alarm;
855 unsigned int period;
856 } alarm_win32_data = {0, NULL, -1};
858 static int win32_start_timer(struct qemu_alarm_timer *t);
859 static void win32_stop_timer(struct qemu_alarm_timer *t);
860 static void win32_rearm_timer(struct qemu_alarm_timer *t);
862 #else
864 static int unix_start_timer(struct qemu_alarm_timer *t);
865 static void unix_stop_timer(struct qemu_alarm_timer *t);
867 #ifdef __linux__
869 static int dynticks_start_timer(struct qemu_alarm_timer *t);
870 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
871 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
873 static int hpet_start_timer(struct qemu_alarm_timer *t);
874 static void hpet_stop_timer(struct qemu_alarm_timer *t);
876 static int rtc_start_timer(struct qemu_alarm_timer *t);
877 static void rtc_stop_timer(struct qemu_alarm_timer *t);
879 #endif /* __linux__ */
881 #endif /* _WIN32 */
883 static struct qemu_alarm_timer alarm_timers[] = {
884 #ifndef _WIN32
885 #ifdef __linux__
886 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
887 dynticks_stop_timer, dynticks_rearm_timer, NULL},
888 /* HPET - if available - is preferred */
889 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
890 /* ...otherwise try RTC */
891 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
892 #endif
893 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
894 #else
895 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
896 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
897 {"win32", 0, win32_start_timer,
898 win32_stop_timer, NULL, &alarm_win32_data},
899 #endif
900 {NULL, }
903 static void show_available_alarms(void)
905 int i;
907 printf("Available alarm timers, in order of precedence:\n");
908 for (i = 0; alarm_timers[i].name; i++)
909 printf("%s\n", alarm_timers[i].name);
912 static void configure_alarms(char const *opt)
914 int i;
915 int cur = 0;
916 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
917 char *arg;
918 char *name;
920 if (!strcmp(opt, "?")) {
921 show_available_alarms();
922 exit(0);
925 arg = strdup(opt);
927 /* Reorder the array */
928 name = strtok(arg, ",");
929 while (name) {
930 struct qemu_alarm_timer tmp;
932 for (i = 0; i < count && alarm_timers[i].name; i++) {
933 if (!strcmp(alarm_timers[i].name, name))
934 break;
937 if (i == count) {
938 fprintf(stderr, "Unknown clock %s\n", name);
939 goto next;
942 if (i < cur)
943 /* Ignore */
944 goto next;
946 /* Swap */
947 tmp = alarm_timers[i];
948 alarm_timers[i] = alarm_timers[cur];
949 alarm_timers[cur] = tmp;
951 cur++;
952 next:
953 name = strtok(NULL, ",");
956 free(arg);
958 if (cur) {
959 /* Disable remaining timers */
960 for (i = cur; i < count; i++)
961 alarm_timers[i].name = NULL;
962 } else {
963 show_available_alarms();
964 exit(1);
968 QEMUClock *rt_clock;
969 QEMUClock *vm_clock;
971 static QEMUTimer *active_timers[2];
973 static QEMUClock *qemu_new_clock(int type)
975 QEMUClock *clock;
976 clock = qemu_mallocz(sizeof(QEMUClock));
977 if (!clock)
978 return NULL;
979 clock->type = type;
980 return clock;
983 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
985 QEMUTimer *ts;
987 ts = qemu_mallocz(sizeof(QEMUTimer));
988 ts->clock = clock;
989 ts->cb = cb;
990 ts->opaque = opaque;
991 return ts;
994 void qemu_free_timer(QEMUTimer *ts)
996 qemu_free(ts);
999 /* stop a timer, but do not dealloc it */
1000 void qemu_del_timer(QEMUTimer *ts)
1002 QEMUTimer **pt, *t;
1004 /* NOTE: this code must be signal safe because
1005 qemu_timer_expired() can be called from a signal. */
1006 pt = &active_timers[ts->clock->type];
1007 for(;;) {
1008 t = *pt;
1009 if (!t)
1010 break;
1011 if (t == ts) {
1012 *pt = t->next;
1013 break;
1015 pt = &t->next;
1019 /* modify the current timer so that it will be fired when current_time
1020 >= expire_time. The corresponding callback will be called. */
1021 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1023 QEMUTimer **pt, *t;
1025 qemu_del_timer(ts);
1027 /* add the timer in the sorted list */
1028 /* NOTE: this code must be signal safe because
1029 qemu_timer_expired() can be called from a signal. */
1030 pt = &active_timers[ts->clock->type];
1031 for(;;) {
1032 t = *pt;
1033 if (!t)
1034 break;
1035 if (t->expire_time > expire_time)
1036 break;
1037 pt = &t->next;
1039 ts->expire_time = expire_time;
1040 ts->next = *pt;
1041 *pt = ts;
1043 /* Rearm if necessary */
1044 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1045 pt == &active_timers[ts->clock->type])
1046 qemu_rearm_alarm_timer(alarm_timer);
1049 int qemu_timer_pending(QEMUTimer *ts)
1051 QEMUTimer *t;
1052 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1053 if (t == ts)
1054 return 1;
1056 return 0;
1059 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1061 if (!timer_head)
1062 return 0;
1063 return (timer_head->expire_time <= current_time);
1066 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1068 QEMUTimer *ts;
1070 for(;;) {
1071 ts = *ptimer_head;
1072 if (!ts || ts->expire_time > current_time)
1073 break;
1074 /* remove timer from the list before calling the callback */
1075 *ptimer_head = ts->next;
1076 ts->next = NULL;
1078 /* run the callback (the timer list can be modified) */
1079 ts->cb(ts->opaque);
1083 int64_t qemu_get_clock(QEMUClock *clock)
1085 switch(clock->type) {
1086 case QEMU_TIMER_REALTIME:
1087 return get_clock() / 1000000;
1088 default:
1089 case QEMU_TIMER_VIRTUAL:
1090 return cpu_get_clock();
1094 static void init_timers(void)
1096 init_get_clock();
1097 ticks_per_sec = QEMU_TIMER_BASE;
1098 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1099 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1102 /* save a timer */
1103 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1105 uint64_t expire_time;
1107 if (qemu_timer_pending(ts)) {
1108 expire_time = ts->expire_time;
1109 } else {
1110 expire_time = -1;
1112 qemu_put_be64(f, expire_time);
1115 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1117 uint64_t expire_time;
1119 expire_time = qemu_get_be64(f);
1120 if (expire_time != -1) {
1121 qemu_mod_timer(ts, expire_time);
1122 } else {
1123 qemu_del_timer(ts);
1127 static void timer_save(QEMUFile *f, void *opaque)
1129 if (cpu_ticks_enabled) {
1130 hw_error("cannot save state if virtual timers are running");
1132 qemu_put_be64(f, cpu_ticks_offset);
1133 qemu_put_be64(f, ticks_per_sec);
1134 qemu_put_be64(f, cpu_clock_offset);
1137 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1139 if (version_id != 1 && version_id != 2)
1140 return -EINVAL;
1141 if (cpu_ticks_enabled) {
1142 return -EINVAL;
1144 cpu_ticks_offset=qemu_get_be64(f);
1145 ticks_per_sec=qemu_get_be64(f);
1146 if (version_id == 2) {
1147 cpu_clock_offset=qemu_get_be64(f);
1149 return 0;
1152 #ifdef _WIN32
1153 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1154 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1155 #else
1156 static void host_alarm_handler(int host_signum)
1157 #endif
1159 #if 0
1160 #define DISP_FREQ 1000
1162 static int64_t delta_min = INT64_MAX;
1163 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1164 static int count;
1165 ti = qemu_get_clock(vm_clock);
1166 if (last_clock != 0) {
1167 delta = ti - last_clock;
1168 if (delta < delta_min)
1169 delta_min = delta;
1170 if (delta > delta_max)
1171 delta_max = delta;
1172 delta_cum += delta;
1173 if (++count == DISP_FREQ) {
1174 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1175 muldiv64(delta_min, 1000000, ticks_per_sec),
1176 muldiv64(delta_max, 1000000, ticks_per_sec),
1177 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1178 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1179 count = 0;
1180 delta_min = INT64_MAX;
1181 delta_max = 0;
1182 delta_cum = 0;
1185 last_clock = ti;
1187 #endif
1188 if (alarm_has_dynticks(alarm_timer) ||
1189 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1190 qemu_get_clock(vm_clock)) ||
1191 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1192 qemu_get_clock(rt_clock))) {
1193 #ifdef _WIN32
1194 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1195 SetEvent(data->host_alarm);
1196 #endif
1197 CPUState *env = next_cpu;
1199 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1201 if (env) {
1202 /* stop the currently executing cpu because a timer occured */
1203 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1204 #ifdef USE_KQEMU
1205 if (env->kqemu_enabled) {
1206 kqemu_cpu_interrupt(env);
1208 #endif
1210 event_pending = 1;
1214 static uint64_t qemu_next_deadline(void)
1216 int64_t nearest_delta_us = INT64_MAX;
1217 int64_t vmdelta_us;
1219 if (active_timers[QEMU_TIMER_REALTIME])
1220 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1221 qemu_get_clock(rt_clock))*1000;
1223 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1224 /* round up */
1225 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1226 qemu_get_clock(vm_clock)+999)/1000;
1227 if (vmdelta_us < nearest_delta_us)
1228 nearest_delta_us = vmdelta_us;
1231 /* Avoid arming the timer to negative, zero, or too low values */
1232 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1233 nearest_delta_us = MIN_TIMER_REARM_US;
1235 return nearest_delta_us;
1238 #ifndef _WIN32
1240 #if defined(__linux__)
1242 #define RTC_FREQ 1024
1244 static void enable_sigio_timer(int fd)
1246 struct sigaction act;
1248 /* timer signal */
1249 sigfillset(&act.sa_mask);
1250 act.sa_flags = 0;
1251 act.sa_handler = host_alarm_handler;
1253 sigaction(SIGIO, &act, NULL);
1254 fcntl(fd, F_SETFL, O_ASYNC);
1255 fcntl(fd, F_SETOWN, getpid());
1258 static int hpet_start_timer(struct qemu_alarm_timer *t)
1260 struct hpet_info info;
1261 int r, fd;
1263 fd = open("/dev/hpet", O_RDONLY);
1264 if (fd < 0)
1265 return -1;
1267 /* Set frequency */
1268 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1269 if (r < 0) {
1270 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1271 "error, but for better emulation accuracy type:\n"
1272 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1273 goto fail;
1276 /* Check capabilities */
1277 r = ioctl(fd, HPET_INFO, &info);
1278 if (r < 0)
1279 goto fail;
1281 /* Enable periodic mode */
1282 r = ioctl(fd, HPET_EPI, 0);
1283 if (info.hi_flags && (r < 0))
1284 goto fail;
1286 /* Enable interrupt */
1287 r = ioctl(fd, HPET_IE_ON, 0);
1288 if (r < 0)
1289 goto fail;
1291 enable_sigio_timer(fd);
1292 t->priv = (void *)(long)fd;
1294 return 0;
1295 fail:
1296 close(fd);
1297 return -1;
1300 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1302 int fd = (long)t->priv;
1304 close(fd);
1307 static int rtc_start_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd;
1310 unsigned long current_rtc_freq = 0;
1312 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1313 if (rtc_fd < 0)
1314 return -1;
1315 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1316 if (current_rtc_freq != RTC_FREQ &&
1317 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1318 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1319 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1320 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1321 goto fail;
1323 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1324 fail:
1325 close(rtc_fd);
1326 return -1;
1329 enable_sigio_timer(rtc_fd);
1331 t->priv = (void *)(long)rtc_fd;
1333 return 0;
1336 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd = (long)t->priv;
1340 close(rtc_fd);
1343 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1345 struct sigevent ev;
1346 timer_t host_timer;
1347 struct sigaction act;
1349 sigfillset(&act.sa_mask);
1350 act.sa_flags = 0;
1351 act.sa_handler = host_alarm_handler;
1353 sigaction(SIGALRM, &act, NULL);
1355 ev.sigev_value.sival_int = 0;
1356 ev.sigev_notify = SIGEV_SIGNAL;
1357 ev.sigev_signo = SIGALRM;
1359 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1360 perror("timer_create");
1362 /* disable dynticks */
1363 fprintf(stderr, "Dynamic Ticks disabled\n");
1365 return -1;
1368 t->priv = (void *)host_timer;
1370 return 0;
1373 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1375 timer_t host_timer = (timer_t)t->priv;
1377 timer_delete(host_timer);
1380 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1382 timer_t host_timer = (timer_t)t->priv;
1383 struct itimerspec timeout;
1384 int64_t nearest_delta_us = INT64_MAX;
1385 int64_t current_us;
1387 if (!active_timers[QEMU_TIMER_REALTIME] &&
1388 !active_timers[QEMU_TIMER_VIRTUAL])
1389 return;
1391 nearest_delta_us = qemu_next_deadline();
1393 /* check whether a timer is already running */
1394 if (timer_gettime(host_timer, &timeout)) {
1395 perror("gettime");
1396 fprintf(stderr, "Internal timer error: aborting\n");
1397 exit(1);
1399 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1400 if (current_us && current_us <= nearest_delta_us)
1401 return;
1403 timeout.it_interval.tv_sec = 0;
1404 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1405 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1406 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1407 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1408 perror("settime");
1409 fprintf(stderr, "Internal timer error: aborting\n");
1410 exit(1);
1414 #endif /* defined(__linux__) */
1416 static int unix_start_timer(struct qemu_alarm_timer *t)
1418 struct sigaction act;
1419 struct itimerval itv;
1420 int err;
1422 /* timer signal */
1423 sigfillset(&act.sa_mask);
1424 act.sa_flags = 0;
1425 act.sa_handler = host_alarm_handler;
1427 sigaction(SIGALRM, &act, NULL);
1429 itv.it_interval.tv_sec = 0;
1430 /* for i386 kernel 2.6 to get 1 ms */
1431 itv.it_interval.tv_usec = 999;
1432 itv.it_value.tv_sec = 0;
1433 itv.it_value.tv_usec = 10 * 1000;
1435 err = setitimer(ITIMER_REAL, &itv, NULL);
1436 if (err)
1437 return -1;
1439 return 0;
1442 static void unix_stop_timer(struct qemu_alarm_timer *t)
1444 struct itimerval itv;
1446 memset(&itv, 0, sizeof(itv));
1447 setitimer(ITIMER_REAL, &itv, NULL);
1450 #endif /* !defined(_WIN32) */
1452 #ifdef _WIN32
1454 static int win32_start_timer(struct qemu_alarm_timer *t)
1456 TIMECAPS tc;
1457 struct qemu_alarm_win32 *data = t->priv;
1458 UINT flags;
1460 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1461 if (!data->host_alarm) {
1462 perror("Failed CreateEvent");
1463 return -1;
1466 memset(&tc, 0, sizeof(tc));
1467 timeGetDevCaps(&tc, sizeof(tc));
1469 if (data->period < tc.wPeriodMin)
1470 data->period = tc.wPeriodMin;
1472 timeBeginPeriod(data->period);
1474 flags = TIME_CALLBACK_FUNCTION;
1475 if (alarm_has_dynticks(t))
1476 flags |= TIME_ONESHOT;
1477 else
1478 flags |= TIME_PERIODIC;
1480 data->timerId = timeSetEvent(1, // interval (ms)
1481 data->period, // resolution
1482 host_alarm_handler, // function
1483 (DWORD)t, // parameter
1484 flags);
1486 if (!data->timerId) {
1487 perror("Failed to initialize win32 alarm timer");
1489 timeEndPeriod(data->period);
1490 CloseHandle(data->host_alarm);
1491 return -1;
1494 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1496 return 0;
1499 static void win32_stop_timer(struct qemu_alarm_timer *t)
1501 struct qemu_alarm_win32 *data = t->priv;
1503 timeKillEvent(data->timerId);
1504 timeEndPeriod(data->period);
1506 CloseHandle(data->host_alarm);
1509 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1511 struct qemu_alarm_win32 *data = t->priv;
1512 uint64_t nearest_delta_us;
1514 if (!active_timers[QEMU_TIMER_REALTIME] &&
1515 !active_timers[QEMU_TIMER_VIRTUAL])
1516 return;
1518 nearest_delta_us = qemu_next_deadline();
1519 nearest_delta_us /= 1000;
1521 timeKillEvent(data->timerId);
1523 data->timerId = timeSetEvent(1,
1524 data->period,
1525 host_alarm_handler,
1526 (DWORD)t,
1527 TIME_ONESHOT | TIME_PERIODIC);
1529 if (!data->timerId) {
1530 perror("Failed to re-arm win32 alarm timer");
1532 timeEndPeriod(data->period);
1533 CloseHandle(data->host_alarm);
1534 exit(1);
1538 #endif /* _WIN32 */
1540 static void init_timer_alarm(void)
1542 struct qemu_alarm_timer *t;
1543 int i, err = -1;
1545 for (i = 0; alarm_timers[i].name; i++) {
1546 t = &alarm_timers[i];
1548 err = t->start(t);
1549 if (!err)
1550 break;
1553 if (err) {
1554 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1555 fprintf(stderr, "Terminating\n");
1556 exit(1);
1559 alarm_timer = t;
1562 static void quit_timers(void)
1564 alarm_timer->stop(alarm_timer);
1565 alarm_timer = NULL;
1568 /***********************************************************/
1569 /* host time/date access */
1570 void qemu_get_timedate(struct tm *tm, int offset)
1572 time_t ti;
1573 struct tm *ret;
1575 time(&ti);
1576 ti += offset;
1577 if (rtc_date_offset == -1) {
1578 if (rtc_utc)
1579 ret = gmtime(&ti);
1580 else
1581 ret = localtime(&ti);
1582 } else {
1583 ti -= rtc_date_offset;
1584 ret = gmtime(&ti);
1587 memcpy(tm, ret, sizeof(struct tm));
1590 int qemu_timedate_diff(struct tm *tm)
1592 time_t seconds;
1594 if (rtc_date_offset == -1)
1595 if (rtc_utc)
1596 seconds = mktimegm(tm);
1597 else
1598 seconds = mktime(tm);
1599 else
1600 seconds = mktimegm(tm) + rtc_date_offset;
1602 return seconds - time(NULL);
1605 /***********************************************************/
1606 /* character device */
1608 static void qemu_chr_event(CharDriverState *s, int event)
1610 if (!s->chr_event)
1611 return;
1612 s->chr_event(s->handler_opaque, event);
1615 static void qemu_chr_reset_bh(void *opaque)
1617 CharDriverState *s = opaque;
1618 qemu_chr_event(s, CHR_EVENT_RESET);
1619 qemu_bh_delete(s->bh);
1620 s->bh = NULL;
1623 void qemu_chr_reset(CharDriverState *s)
1625 if (s->bh == NULL) {
1626 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1627 qemu_bh_schedule(s->bh);
1631 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1633 return s->chr_write(s, buf, len);
1636 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1638 if (!s->chr_ioctl)
1639 return -ENOTSUP;
1640 return s->chr_ioctl(s, cmd, arg);
1643 int qemu_chr_can_read(CharDriverState *s)
1645 if (!s->chr_can_read)
1646 return 0;
1647 return s->chr_can_read(s->handler_opaque);
1650 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1652 s->chr_read(s->handler_opaque, buf, len);
1655 void qemu_chr_accept_input(CharDriverState *s)
1657 if (s->chr_accept_input)
1658 s->chr_accept_input(s);
1661 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1663 char buf[4096];
1664 va_list ap;
1665 va_start(ap, fmt);
1666 vsnprintf(buf, sizeof(buf), fmt, ap);
1667 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1668 va_end(ap);
1671 void qemu_chr_send_event(CharDriverState *s, int event)
1673 if (s->chr_send_event)
1674 s->chr_send_event(s, event);
1677 void qemu_chr_add_handlers(CharDriverState *s,
1678 IOCanRWHandler *fd_can_read,
1679 IOReadHandler *fd_read,
1680 IOEventHandler *fd_event,
1681 void *opaque)
1683 s->chr_can_read = fd_can_read;
1684 s->chr_read = fd_read;
1685 s->chr_event = fd_event;
1686 s->handler_opaque = opaque;
1687 if (s->chr_update_read_handler)
1688 s->chr_update_read_handler(s);
1691 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1693 return len;
1696 static CharDriverState *qemu_chr_open_null(void)
1698 CharDriverState *chr;
1700 chr = qemu_mallocz(sizeof(CharDriverState));
1701 if (!chr)
1702 return NULL;
1703 chr->chr_write = null_chr_write;
1704 return chr;
1707 /* MUX driver for serial I/O splitting */
1708 static int term_timestamps;
1709 static int64_t term_timestamps_start;
1710 #define MAX_MUX 4
1711 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1712 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1713 typedef struct {
1714 IOCanRWHandler *chr_can_read[MAX_MUX];
1715 IOReadHandler *chr_read[MAX_MUX];
1716 IOEventHandler *chr_event[MAX_MUX];
1717 void *ext_opaque[MAX_MUX];
1718 CharDriverState *drv;
1719 unsigned char buffer[MUX_BUFFER_SIZE];
1720 int prod;
1721 int cons;
1722 int mux_cnt;
1723 int term_got_escape;
1724 int max_size;
1725 } MuxDriver;
1728 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1730 MuxDriver *d = chr->opaque;
1731 int ret;
1732 if (!term_timestamps) {
1733 ret = d->drv->chr_write(d->drv, buf, len);
1734 } else {
1735 int i;
1737 ret = 0;
1738 for(i = 0; i < len; i++) {
1739 ret += d->drv->chr_write(d->drv, buf+i, 1);
1740 if (buf[i] == '\n') {
1741 char buf1[64];
1742 int64_t ti;
1743 int secs;
1745 ti = get_clock();
1746 if (term_timestamps_start == -1)
1747 term_timestamps_start = ti;
1748 ti -= term_timestamps_start;
1749 secs = ti / 1000000000;
1750 snprintf(buf1, sizeof(buf1),
1751 "[%02d:%02d:%02d.%03d] ",
1752 secs / 3600,
1753 (secs / 60) % 60,
1754 secs % 60,
1755 (int)((ti / 1000000) % 1000));
1756 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1760 return ret;
1763 static char *mux_help[] = {
1764 "% h print this help\n\r",
1765 "% x exit emulator\n\r",
1766 "% s save disk data back to file (if -snapshot)\n\r",
1767 "% t toggle console timestamps\n\r"
1768 "% b send break (magic sysrq)\n\r",
1769 "% c switch between console and monitor\n\r",
1770 "% % sends %\n\r",
1771 NULL
1774 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1775 static void mux_print_help(CharDriverState *chr)
1777 int i, j;
1778 char ebuf[15] = "Escape-Char";
1779 char cbuf[50] = "\n\r";
1781 if (term_escape_char > 0 && term_escape_char < 26) {
1782 sprintf(cbuf,"\n\r");
1783 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1784 } else {
1785 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1786 term_escape_char);
1788 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1789 for (i = 0; mux_help[i] != NULL; i++) {
1790 for (j=0; mux_help[i][j] != '\0'; j++) {
1791 if (mux_help[i][j] == '%')
1792 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1793 else
1794 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1799 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1801 if (d->term_got_escape) {
1802 d->term_got_escape = 0;
1803 if (ch == term_escape_char)
1804 goto send_char;
1805 switch(ch) {
1806 case '?':
1807 case 'h':
1808 mux_print_help(chr);
1809 break;
1810 case 'x':
1812 char *term = "QEMU: Terminated\n\r";
1813 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1814 exit(0);
1815 break;
1817 case 's':
1819 int i;
1820 for (i = 0; i < nb_drives; i++) {
1821 bdrv_commit(drives_table[i].bdrv);
1824 break;
1825 case 'b':
1826 qemu_chr_event(chr, CHR_EVENT_BREAK);
1827 break;
1828 case 'c':
1829 /* Switch to the next registered device */
1830 chr->focus++;
1831 if (chr->focus >= d->mux_cnt)
1832 chr->focus = 0;
1833 break;
1834 case 't':
1835 term_timestamps = !term_timestamps;
1836 term_timestamps_start = -1;
1837 break;
1839 } else if (ch == term_escape_char) {
1840 d->term_got_escape = 1;
1841 } else {
1842 send_char:
1843 return 1;
1845 return 0;
1848 static void mux_chr_accept_input(CharDriverState *chr)
1850 int m = chr->focus;
1851 MuxDriver *d = chr->opaque;
1853 while (d->prod != d->cons &&
1854 d->chr_can_read[m] &&
1855 d->chr_can_read[m](d->ext_opaque[m])) {
1856 d->chr_read[m](d->ext_opaque[m],
1857 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1861 static int mux_chr_can_read(void *opaque)
1863 CharDriverState *chr = opaque;
1864 MuxDriver *d = chr->opaque;
1866 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1867 return 1;
1868 if (d->chr_can_read[chr->focus])
1869 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1870 return 0;
1873 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1875 CharDriverState *chr = opaque;
1876 MuxDriver *d = chr->opaque;
1877 int m = chr->focus;
1878 int i;
1880 mux_chr_accept_input (opaque);
1882 for(i = 0; i < size; i++)
1883 if (mux_proc_byte(chr, d, buf[i])) {
1884 if (d->prod == d->cons &&
1885 d->chr_can_read[m] &&
1886 d->chr_can_read[m](d->ext_opaque[m]))
1887 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1888 else
1889 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1893 static void mux_chr_event(void *opaque, int event)
1895 CharDriverState *chr = opaque;
1896 MuxDriver *d = chr->opaque;
1897 int i;
1899 /* Send the event to all registered listeners */
1900 for (i = 0; i < d->mux_cnt; i++)
1901 if (d->chr_event[i])
1902 d->chr_event[i](d->ext_opaque[i], event);
1905 static void mux_chr_update_read_handler(CharDriverState *chr)
1907 MuxDriver *d = chr->opaque;
1909 if (d->mux_cnt >= MAX_MUX) {
1910 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1911 return;
1913 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1914 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1915 d->chr_read[d->mux_cnt] = chr->chr_read;
1916 d->chr_event[d->mux_cnt] = chr->chr_event;
1917 /* Fix up the real driver with mux routines */
1918 if (d->mux_cnt == 0) {
1919 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1920 mux_chr_event, chr);
1922 chr->focus = d->mux_cnt;
1923 d->mux_cnt++;
1926 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1928 CharDriverState *chr;
1929 MuxDriver *d;
1931 chr = qemu_mallocz(sizeof(CharDriverState));
1932 if (!chr)
1933 return NULL;
1934 d = qemu_mallocz(sizeof(MuxDriver));
1935 if (!d) {
1936 free(chr);
1937 return NULL;
1940 chr->opaque = d;
1941 d->drv = drv;
1942 chr->focus = -1;
1943 chr->chr_write = mux_chr_write;
1944 chr->chr_update_read_handler = mux_chr_update_read_handler;
1945 chr->chr_accept_input = mux_chr_accept_input;
1946 return chr;
1950 #ifdef _WIN32
1952 static void socket_cleanup(void)
1954 WSACleanup();
1957 static int socket_init(void)
1959 WSADATA Data;
1960 int ret, err;
1962 ret = WSAStartup(MAKEWORD(2,2), &Data);
1963 if (ret != 0) {
1964 err = WSAGetLastError();
1965 fprintf(stderr, "WSAStartup: %d\n", err);
1966 return -1;
1968 atexit(socket_cleanup);
1969 return 0;
1972 static int send_all(int fd, const uint8_t *buf, int len1)
1974 int ret, len;
1976 len = len1;
1977 while (len > 0) {
1978 ret = send(fd, buf, len, 0);
1979 if (ret < 0) {
1980 int errno;
1981 errno = WSAGetLastError();
1982 if (errno != WSAEWOULDBLOCK) {
1983 return -1;
1985 } else if (ret == 0) {
1986 break;
1987 } else {
1988 buf += ret;
1989 len -= ret;
1992 return len1 - len;
1995 void socket_set_nonblock(int fd)
1997 unsigned long opt = 1;
1998 ioctlsocket(fd, FIONBIO, &opt);
2001 #else
2003 static int unix_write(int fd, const uint8_t *buf, int len1)
2005 int ret, len;
2007 len = len1;
2008 while (len > 0) {
2009 ret = write(fd, buf, len);
2010 if (ret < 0) {
2011 if (errno != EINTR && errno != EAGAIN)
2012 return -1;
2013 } else if (ret == 0) {
2014 break;
2015 } else {
2016 buf += ret;
2017 len -= ret;
2020 return len1 - len;
2023 static inline int send_all(int fd, const uint8_t *buf, int len1)
2025 return unix_write(fd, buf, len1);
2028 void socket_set_nonblock(int fd)
2030 fcntl(fd, F_SETFL, O_NONBLOCK);
2032 #endif /* !_WIN32 */
2034 #ifndef _WIN32
2036 typedef struct {
2037 int fd_in, fd_out;
2038 int max_size;
2039 } FDCharDriver;
2041 #define STDIO_MAX_CLIENTS 1
2042 static int stdio_nb_clients = 0;
2044 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2046 FDCharDriver *s = chr->opaque;
2047 return unix_write(s->fd_out, buf, len);
2050 static int fd_chr_read_poll(void *opaque)
2052 CharDriverState *chr = opaque;
2053 FDCharDriver *s = chr->opaque;
2055 s->max_size = qemu_chr_can_read(chr);
2056 return s->max_size;
2059 static void fd_chr_read(void *opaque)
2061 CharDriverState *chr = opaque;
2062 FDCharDriver *s = chr->opaque;
2063 int size, len;
2064 uint8_t buf[1024];
2066 len = sizeof(buf);
2067 if (len > s->max_size)
2068 len = s->max_size;
2069 if (len == 0)
2070 return;
2071 size = read(s->fd_in, buf, len);
2072 if (size == 0) {
2073 /* FD has been closed. Remove it from the active list. */
2074 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2075 return;
2077 if (size > 0) {
2078 qemu_chr_read(chr, buf, size);
2082 static void fd_chr_update_read_handler(CharDriverState *chr)
2084 FDCharDriver *s = chr->opaque;
2086 if (s->fd_in >= 0) {
2087 if (nographic && s->fd_in == 0) {
2088 } else {
2089 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2090 fd_chr_read, NULL, chr);
2095 static void fd_chr_close(struct CharDriverState *chr)
2097 FDCharDriver *s = chr->opaque;
2099 if (s->fd_in >= 0) {
2100 if (nographic && s->fd_in == 0) {
2101 } else {
2102 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2106 qemu_free(s);
2109 /* open a character device to a unix fd */
2110 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2112 CharDriverState *chr;
2113 FDCharDriver *s;
2115 chr = qemu_mallocz(sizeof(CharDriverState));
2116 if (!chr)
2117 return NULL;
2118 s = qemu_mallocz(sizeof(FDCharDriver));
2119 if (!s) {
2120 free(chr);
2121 return NULL;
2123 s->fd_in = fd_in;
2124 s->fd_out = fd_out;
2125 chr->opaque = s;
2126 chr->chr_write = fd_chr_write;
2127 chr->chr_update_read_handler = fd_chr_update_read_handler;
2128 chr->chr_close = fd_chr_close;
2130 qemu_chr_reset(chr);
2132 return chr;
2135 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2137 int fd_out;
2139 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2140 if (fd_out < 0)
2141 return NULL;
2142 return qemu_chr_open_fd(-1, fd_out);
2145 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2147 int fd_in, fd_out;
2148 char filename_in[256], filename_out[256];
2150 snprintf(filename_in, 256, "%s.in", filename);
2151 snprintf(filename_out, 256, "%s.out", filename);
2152 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2153 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2154 if (fd_in < 0 || fd_out < 0) {
2155 if (fd_in >= 0)
2156 close(fd_in);
2157 if (fd_out >= 0)
2158 close(fd_out);
2159 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2160 if (fd_in < 0)
2161 return NULL;
2163 return qemu_chr_open_fd(fd_in, fd_out);
2167 /* for STDIO, we handle the case where several clients use it
2168 (nographic mode) */
2170 #define TERM_FIFO_MAX_SIZE 1
2172 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2173 static int term_fifo_size;
2175 static int stdio_read_poll(void *opaque)
2177 CharDriverState *chr = opaque;
2179 /* try to flush the queue if needed */
2180 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2181 qemu_chr_read(chr, term_fifo, 1);
2182 term_fifo_size = 0;
2184 /* see if we can absorb more chars */
2185 if (term_fifo_size == 0)
2186 return 1;
2187 else
2188 return 0;
2191 static void stdio_read(void *opaque)
2193 int size;
2194 uint8_t buf[1];
2195 CharDriverState *chr = opaque;
2197 size = read(0, buf, 1);
2198 if (size == 0) {
2199 /* stdin has been closed. Remove it from the active list. */
2200 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2201 return;
2203 if (size > 0) {
2204 if (qemu_chr_can_read(chr) > 0) {
2205 qemu_chr_read(chr, buf, 1);
2206 } else if (term_fifo_size == 0) {
2207 term_fifo[term_fifo_size++] = buf[0];
2212 /* init terminal so that we can grab keys */
2213 static struct termios oldtty;
2214 static int old_fd0_flags;
2215 static int term_atexit_done;
2217 static void term_exit(void)
2219 tcsetattr (0, TCSANOW, &oldtty);
2220 fcntl(0, F_SETFL, old_fd0_flags);
2223 static void term_init(void)
2225 struct termios tty;
2227 tcgetattr (0, &tty);
2228 oldtty = tty;
2229 old_fd0_flags = fcntl(0, F_GETFL);
2231 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2232 |INLCR|IGNCR|ICRNL|IXON);
2233 tty.c_oflag |= OPOST;
2234 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2235 /* if graphical mode, we allow Ctrl-C handling */
2236 if (nographic)
2237 tty.c_lflag &= ~ISIG;
2238 tty.c_cflag &= ~(CSIZE|PARENB);
2239 tty.c_cflag |= CS8;
2240 tty.c_cc[VMIN] = 1;
2241 tty.c_cc[VTIME] = 0;
2243 tcsetattr (0, TCSANOW, &tty);
2245 if (!term_atexit_done++)
2246 atexit(term_exit);
2248 fcntl(0, F_SETFL, O_NONBLOCK);
2251 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2253 term_exit();
2254 stdio_nb_clients--;
2255 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2256 fd_chr_close(chr);
2259 static CharDriverState *qemu_chr_open_stdio(void)
2261 CharDriverState *chr;
2263 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2264 return NULL;
2265 chr = qemu_chr_open_fd(0, 1);
2266 chr->chr_close = qemu_chr_close_stdio;
2267 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2268 stdio_nb_clients++;
2269 term_init();
2271 return chr;
2274 #if defined(__linux__) || defined(__sun__)
2275 static CharDriverState *qemu_chr_open_pty(void)
2277 struct termios tty;
2278 char slave_name[1024];
2279 int master_fd, slave_fd;
2281 #if defined(__linux__)
2282 /* Not satisfying */
2283 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2284 return NULL;
2286 #endif
2288 /* Disabling local echo and line-buffered output */
2289 tcgetattr (master_fd, &tty);
2290 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2291 tty.c_cc[VMIN] = 1;
2292 tty.c_cc[VTIME] = 0;
2293 tcsetattr (master_fd, TCSAFLUSH, &tty);
2295 fprintf(stderr, "char device redirected to %s\n", slave_name);
2296 return qemu_chr_open_fd(master_fd, master_fd);
2299 static void tty_serial_init(int fd, int speed,
2300 int parity, int data_bits, int stop_bits)
2302 struct termios tty;
2303 speed_t spd;
2305 #if 0
2306 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2307 speed, parity, data_bits, stop_bits);
2308 #endif
2309 tcgetattr (fd, &tty);
2311 #define MARGIN 1.1
2312 if (speed <= 50 * MARGIN)
2313 spd = B50;
2314 else if (speed <= 75 * MARGIN)
2315 spd = B75;
2316 else if (speed <= 300 * MARGIN)
2317 spd = B300;
2318 else if (speed <= 600 * MARGIN)
2319 spd = B600;
2320 else if (speed <= 1200 * MARGIN)
2321 spd = B1200;
2322 else if (speed <= 2400 * MARGIN)
2323 spd = B2400;
2324 else if (speed <= 4800 * MARGIN)
2325 spd = B4800;
2326 else if (speed <= 9600 * MARGIN)
2327 spd = B9600;
2328 else if (speed <= 19200 * MARGIN)
2329 spd = B19200;
2330 else if (speed <= 38400 * MARGIN)
2331 spd = B38400;
2332 else if (speed <= 57600 * MARGIN)
2333 spd = B57600;
2334 else if (speed <= 115200 * MARGIN)
2335 spd = B115200;
2336 else
2337 spd = B115200;
2339 cfsetispeed(&tty, spd);
2340 cfsetospeed(&tty, spd);
2342 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2343 |INLCR|IGNCR|ICRNL|IXON);
2344 tty.c_oflag |= OPOST;
2345 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2346 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2347 switch(data_bits) {
2348 default:
2349 case 8:
2350 tty.c_cflag |= CS8;
2351 break;
2352 case 7:
2353 tty.c_cflag |= CS7;
2354 break;
2355 case 6:
2356 tty.c_cflag |= CS6;
2357 break;
2358 case 5:
2359 tty.c_cflag |= CS5;
2360 break;
2362 switch(parity) {
2363 default:
2364 case 'N':
2365 break;
2366 case 'E':
2367 tty.c_cflag |= PARENB;
2368 break;
2369 case 'O':
2370 tty.c_cflag |= PARENB | PARODD;
2371 break;
2373 if (stop_bits == 2)
2374 tty.c_cflag |= CSTOPB;
2376 tcsetattr (fd, TCSANOW, &tty);
2379 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2381 FDCharDriver *s = chr->opaque;
2383 switch(cmd) {
2384 case CHR_IOCTL_SERIAL_SET_PARAMS:
2386 QEMUSerialSetParams *ssp = arg;
2387 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2388 ssp->data_bits, ssp->stop_bits);
2390 break;
2391 case CHR_IOCTL_SERIAL_SET_BREAK:
2393 int enable = *(int *)arg;
2394 if (enable)
2395 tcsendbreak(s->fd_in, 1);
2397 break;
2398 default:
2399 return -ENOTSUP;
2401 return 0;
2404 static CharDriverState *qemu_chr_open_tty(const char *filename)
2406 CharDriverState *chr;
2407 int fd;
2409 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2410 fcntl(fd, F_SETFL, O_NONBLOCK);
2411 tty_serial_init(fd, 115200, 'N', 8, 1);
2412 chr = qemu_chr_open_fd(fd, fd);
2413 if (!chr) {
2414 close(fd);
2415 return NULL;
2417 chr->chr_ioctl = tty_serial_ioctl;
2418 qemu_chr_reset(chr);
2419 return chr;
2421 #else /* ! __linux__ && ! __sun__ */
2422 static CharDriverState *qemu_chr_open_pty(void)
2424 return NULL;
2426 #endif /* __linux__ || __sun__ */
2428 #if defined(__linux__)
2429 typedef struct {
2430 int fd;
2431 int mode;
2432 } ParallelCharDriver;
2434 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2436 if (s->mode != mode) {
2437 int m = mode;
2438 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2439 return 0;
2440 s->mode = mode;
2442 return 1;
2445 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2447 ParallelCharDriver *drv = chr->opaque;
2448 int fd = drv->fd;
2449 uint8_t b;
2451 switch(cmd) {
2452 case CHR_IOCTL_PP_READ_DATA:
2453 if (ioctl(fd, PPRDATA, &b) < 0)
2454 return -ENOTSUP;
2455 *(uint8_t *)arg = b;
2456 break;
2457 case CHR_IOCTL_PP_WRITE_DATA:
2458 b = *(uint8_t *)arg;
2459 if (ioctl(fd, PPWDATA, &b) < 0)
2460 return -ENOTSUP;
2461 break;
2462 case CHR_IOCTL_PP_READ_CONTROL:
2463 if (ioctl(fd, PPRCONTROL, &b) < 0)
2464 return -ENOTSUP;
2465 /* Linux gives only the lowest bits, and no way to know data
2466 direction! For better compatibility set the fixed upper
2467 bits. */
2468 *(uint8_t *)arg = b | 0xc0;
2469 break;
2470 case CHR_IOCTL_PP_WRITE_CONTROL:
2471 b = *(uint8_t *)arg;
2472 if (ioctl(fd, PPWCONTROL, &b) < 0)
2473 return -ENOTSUP;
2474 break;
2475 case CHR_IOCTL_PP_READ_STATUS:
2476 if (ioctl(fd, PPRSTATUS, &b) < 0)
2477 return -ENOTSUP;
2478 *(uint8_t *)arg = b;
2479 break;
2480 case CHR_IOCTL_PP_EPP_READ_ADDR:
2481 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2482 struct ParallelIOArg *parg = arg;
2483 int n = read(fd, parg->buffer, parg->count);
2484 if (n != parg->count) {
2485 return -EIO;
2488 break;
2489 case CHR_IOCTL_PP_EPP_READ:
2490 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2491 struct ParallelIOArg *parg = arg;
2492 int n = read(fd, parg->buffer, parg->count);
2493 if (n != parg->count) {
2494 return -EIO;
2497 break;
2498 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2499 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2500 struct ParallelIOArg *parg = arg;
2501 int n = write(fd, parg->buffer, parg->count);
2502 if (n != parg->count) {
2503 return -EIO;
2506 break;
2507 case CHR_IOCTL_PP_EPP_WRITE:
2508 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2509 struct ParallelIOArg *parg = arg;
2510 int n = write(fd, parg->buffer, parg->count);
2511 if (n != parg->count) {
2512 return -EIO;
2515 break;
2516 default:
2517 return -ENOTSUP;
2519 return 0;
2522 static void pp_close(CharDriverState *chr)
2524 ParallelCharDriver *drv = chr->opaque;
2525 int fd = drv->fd;
2527 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2528 ioctl(fd, PPRELEASE);
2529 close(fd);
2530 qemu_free(drv);
2533 static CharDriverState *qemu_chr_open_pp(const char *filename)
2535 CharDriverState *chr;
2536 ParallelCharDriver *drv;
2537 int fd;
2539 TFR(fd = open(filename, O_RDWR));
2540 if (fd < 0)
2541 return NULL;
2543 if (ioctl(fd, PPCLAIM) < 0) {
2544 close(fd);
2545 return NULL;
2548 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2549 if (!drv) {
2550 close(fd);
2551 return NULL;
2553 drv->fd = fd;
2554 drv->mode = IEEE1284_MODE_COMPAT;
2556 chr = qemu_mallocz(sizeof(CharDriverState));
2557 if (!chr) {
2558 qemu_free(drv);
2559 close(fd);
2560 return NULL;
2562 chr->chr_write = null_chr_write;
2563 chr->chr_ioctl = pp_ioctl;
2564 chr->chr_close = pp_close;
2565 chr->opaque = drv;
2567 qemu_chr_reset(chr);
2569 return chr;
2571 #endif /* __linux__ */
2573 #else /* _WIN32 */
2575 typedef struct {
2576 int max_size;
2577 HANDLE hcom, hrecv, hsend;
2578 OVERLAPPED orecv, osend;
2579 BOOL fpipe;
2580 DWORD len;
2581 } WinCharState;
2583 #define NSENDBUF 2048
2584 #define NRECVBUF 2048
2585 #define MAXCONNECT 1
2586 #define NTIMEOUT 5000
2588 static int win_chr_poll(void *opaque);
2589 static int win_chr_pipe_poll(void *opaque);
2591 static void win_chr_close(CharDriverState *chr)
2593 WinCharState *s = chr->opaque;
2595 if (s->hsend) {
2596 CloseHandle(s->hsend);
2597 s->hsend = NULL;
2599 if (s->hrecv) {
2600 CloseHandle(s->hrecv);
2601 s->hrecv = NULL;
2603 if (s->hcom) {
2604 CloseHandle(s->hcom);
2605 s->hcom = NULL;
2607 if (s->fpipe)
2608 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2609 else
2610 qemu_del_polling_cb(win_chr_poll, chr);
2613 static int win_chr_init(CharDriverState *chr, const char *filename)
2615 WinCharState *s = chr->opaque;
2616 COMMCONFIG comcfg;
2617 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2618 COMSTAT comstat;
2619 DWORD size;
2620 DWORD err;
2622 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2623 if (!s->hsend) {
2624 fprintf(stderr, "Failed CreateEvent\n");
2625 goto fail;
2627 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2628 if (!s->hrecv) {
2629 fprintf(stderr, "Failed CreateEvent\n");
2630 goto fail;
2633 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2634 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2635 if (s->hcom == INVALID_HANDLE_VALUE) {
2636 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2637 s->hcom = NULL;
2638 goto fail;
2641 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2642 fprintf(stderr, "Failed SetupComm\n");
2643 goto fail;
2646 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2647 size = sizeof(COMMCONFIG);
2648 GetDefaultCommConfig(filename, &comcfg, &size);
2649 comcfg.dcb.DCBlength = sizeof(DCB);
2650 CommConfigDialog(filename, NULL, &comcfg);
2652 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2653 fprintf(stderr, "Failed SetCommState\n");
2654 goto fail;
2657 if (!SetCommMask(s->hcom, EV_ERR)) {
2658 fprintf(stderr, "Failed SetCommMask\n");
2659 goto fail;
2662 cto.ReadIntervalTimeout = MAXDWORD;
2663 if (!SetCommTimeouts(s->hcom, &cto)) {
2664 fprintf(stderr, "Failed SetCommTimeouts\n");
2665 goto fail;
2668 if (!ClearCommError(s->hcom, &err, &comstat)) {
2669 fprintf(stderr, "Failed ClearCommError\n");
2670 goto fail;
2672 qemu_add_polling_cb(win_chr_poll, chr);
2673 return 0;
2675 fail:
2676 win_chr_close(chr);
2677 return -1;
2680 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2682 WinCharState *s = chr->opaque;
2683 DWORD len, ret, size, err;
2685 len = len1;
2686 ZeroMemory(&s->osend, sizeof(s->osend));
2687 s->osend.hEvent = s->hsend;
2688 while (len > 0) {
2689 if (s->hsend)
2690 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2691 else
2692 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2693 if (!ret) {
2694 err = GetLastError();
2695 if (err == ERROR_IO_PENDING) {
2696 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2697 if (ret) {
2698 buf += size;
2699 len -= size;
2700 } else {
2701 break;
2703 } else {
2704 break;
2706 } else {
2707 buf += size;
2708 len -= size;
2711 return len1 - len;
2714 static int win_chr_read_poll(CharDriverState *chr)
2716 WinCharState *s = chr->opaque;
2718 s->max_size = qemu_chr_can_read(chr);
2719 return s->max_size;
2722 static void win_chr_readfile(CharDriverState *chr)
2724 WinCharState *s = chr->opaque;
2725 int ret, err;
2726 uint8_t buf[1024];
2727 DWORD size;
2729 ZeroMemory(&s->orecv, sizeof(s->orecv));
2730 s->orecv.hEvent = s->hrecv;
2731 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2732 if (!ret) {
2733 err = GetLastError();
2734 if (err == ERROR_IO_PENDING) {
2735 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2739 if (size > 0) {
2740 qemu_chr_read(chr, buf, size);
2744 static void win_chr_read(CharDriverState *chr)
2746 WinCharState *s = chr->opaque;
2748 if (s->len > s->max_size)
2749 s->len = s->max_size;
2750 if (s->len == 0)
2751 return;
2753 win_chr_readfile(chr);
2756 static int win_chr_poll(void *opaque)
2758 CharDriverState *chr = opaque;
2759 WinCharState *s = chr->opaque;
2760 COMSTAT status;
2761 DWORD comerr;
2763 ClearCommError(s->hcom, &comerr, &status);
2764 if (status.cbInQue > 0) {
2765 s->len = status.cbInQue;
2766 win_chr_read_poll(chr);
2767 win_chr_read(chr);
2768 return 1;
2770 return 0;
2773 static CharDriverState *qemu_chr_open_win(const char *filename)
2775 CharDriverState *chr;
2776 WinCharState *s;
2778 chr = qemu_mallocz(sizeof(CharDriverState));
2779 if (!chr)
2780 return NULL;
2781 s = qemu_mallocz(sizeof(WinCharState));
2782 if (!s) {
2783 free(chr);
2784 return NULL;
2786 chr->opaque = s;
2787 chr->chr_write = win_chr_write;
2788 chr->chr_close = win_chr_close;
2790 if (win_chr_init(chr, filename) < 0) {
2791 free(s);
2792 free(chr);
2793 return NULL;
2795 qemu_chr_reset(chr);
2796 return chr;
2799 static int win_chr_pipe_poll(void *opaque)
2801 CharDriverState *chr = opaque;
2802 WinCharState *s = chr->opaque;
2803 DWORD size;
2805 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2806 if (size > 0) {
2807 s->len = size;
2808 win_chr_read_poll(chr);
2809 win_chr_read(chr);
2810 return 1;
2812 return 0;
2815 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2817 WinCharState *s = chr->opaque;
2818 OVERLAPPED ov;
2819 int ret;
2820 DWORD size;
2821 char openname[256];
2823 s->fpipe = TRUE;
2825 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2826 if (!s->hsend) {
2827 fprintf(stderr, "Failed CreateEvent\n");
2828 goto fail;
2830 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2831 if (!s->hrecv) {
2832 fprintf(stderr, "Failed CreateEvent\n");
2833 goto fail;
2836 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2837 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2838 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2839 PIPE_WAIT,
2840 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2841 if (s->hcom == INVALID_HANDLE_VALUE) {
2842 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2843 s->hcom = NULL;
2844 goto fail;
2847 ZeroMemory(&ov, sizeof(ov));
2848 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2849 ret = ConnectNamedPipe(s->hcom, &ov);
2850 if (ret) {
2851 fprintf(stderr, "Failed ConnectNamedPipe\n");
2852 goto fail;
2855 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2856 if (!ret) {
2857 fprintf(stderr, "Failed GetOverlappedResult\n");
2858 if (ov.hEvent) {
2859 CloseHandle(ov.hEvent);
2860 ov.hEvent = NULL;
2862 goto fail;
2865 if (ov.hEvent) {
2866 CloseHandle(ov.hEvent);
2867 ov.hEvent = NULL;
2869 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2870 return 0;
2872 fail:
2873 win_chr_close(chr);
2874 return -1;
2878 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2880 CharDriverState *chr;
2881 WinCharState *s;
2883 chr = qemu_mallocz(sizeof(CharDriverState));
2884 if (!chr)
2885 return NULL;
2886 s = qemu_mallocz(sizeof(WinCharState));
2887 if (!s) {
2888 free(chr);
2889 return NULL;
2891 chr->opaque = s;
2892 chr->chr_write = win_chr_write;
2893 chr->chr_close = win_chr_close;
2895 if (win_chr_pipe_init(chr, filename) < 0) {
2896 free(s);
2897 free(chr);
2898 return NULL;
2900 qemu_chr_reset(chr);
2901 return chr;
2904 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2906 CharDriverState *chr;
2907 WinCharState *s;
2909 chr = qemu_mallocz(sizeof(CharDriverState));
2910 if (!chr)
2911 return NULL;
2912 s = qemu_mallocz(sizeof(WinCharState));
2913 if (!s) {
2914 free(chr);
2915 return NULL;
2917 s->hcom = fd_out;
2918 chr->opaque = s;
2919 chr->chr_write = win_chr_write;
2920 qemu_chr_reset(chr);
2921 return chr;
2924 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2926 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2929 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2931 HANDLE fd_out;
2933 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2934 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2935 if (fd_out == INVALID_HANDLE_VALUE)
2936 return NULL;
2938 return qemu_chr_open_win_file(fd_out);
2940 #endif /* !_WIN32 */
2942 /***********************************************************/
2943 /* UDP Net console */
2945 typedef struct {
2946 int fd;
2947 struct sockaddr_in daddr;
2948 uint8_t buf[1024];
2949 int bufcnt;
2950 int bufptr;
2951 int max_size;
2952 } NetCharDriver;
2954 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2956 NetCharDriver *s = chr->opaque;
2958 return sendto(s->fd, buf, len, 0,
2959 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2962 static int udp_chr_read_poll(void *opaque)
2964 CharDriverState *chr = opaque;
2965 NetCharDriver *s = chr->opaque;
2967 s->max_size = qemu_chr_can_read(chr);
2969 /* If there were any stray characters in the queue process them
2970 * first
2972 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2973 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2974 s->bufptr++;
2975 s->max_size = qemu_chr_can_read(chr);
2977 return s->max_size;
2980 static void udp_chr_read(void *opaque)
2982 CharDriverState *chr = opaque;
2983 NetCharDriver *s = chr->opaque;
2985 if (s->max_size == 0)
2986 return;
2987 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2988 s->bufptr = s->bufcnt;
2989 if (s->bufcnt <= 0)
2990 return;
2992 s->bufptr = 0;
2993 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2994 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2995 s->bufptr++;
2996 s->max_size = qemu_chr_can_read(chr);
3000 static void udp_chr_update_read_handler(CharDriverState *chr)
3002 NetCharDriver *s = chr->opaque;
3004 if (s->fd >= 0) {
3005 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3006 udp_chr_read, NULL, chr);
3010 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3011 #ifndef _WIN32
3012 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3013 #endif
3014 int parse_host_src_port(struct sockaddr_in *haddr,
3015 struct sockaddr_in *saddr,
3016 const char *str);
3018 static CharDriverState *qemu_chr_open_udp(const char *def)
3020 CharDriverState *chr = NULL;
3021 NetCharDriver *s = NULL;
3022 int fd = -1;
3023 struct sockaddr_in saddr;
3025 chr = qemu_mallocz(sizeof(CharDriverState));
3026 if (!chr)
3027 goto return_err;
3028 s = qemu_mallocz(sizeof(NetCharDriver));
3029 if (!s)
3030 goto return_err;
3032 fd = socket(PF_INET, SOCK_DGRAM, 0);
3033 if (fd < 0) {
3034 perror("socket(PF_INET, SOCK_DGRAM)");
3035 goto return_err;
3038 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3039 printf("Could not parse: %s\n", def);
3040 goto return_err;
3043 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3045 perror("bind");
3046 goto return_err;
3049 s->fd = fd;
3050 s->bufcnt = 0;
3051 s->bufptr = 0;
3052 chr->opaque = s;
3053 chr->chr_write = udp_chr_write;
3054 chr->chr_update_read_handler = udp_chr_update_read_handler;
3055 return chr;
3057 return_err:
3058 if (chr)
3059 free(chr);
3060 if (s)
3061 free(s);
3062 if (fd >= 0)
3063 closesocket(fd);
3064 return NULL;
3067 /***********************************************************/
3068 /* TCP Net console */
3070 typedef struct {
3071 int fd, listen_fd;
3072 int connected;
3073 int max_size;
3074 int do_telnetopt;
3075 int do_nodelay;
3076 int is_unix;
3077 } TCPCharDriver;
3079 static void tcp_chr_accept(void *opaque);
3081 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3083 TCPCharDriver *s = chr->opaque;
3084 if (s->connected) {
3085 return send_all(s->fd, buf, len);
3086 } else {
3087 /* XXX: indicate an error ? */
3088 return len;
3092 static int tcp_chr_read_poll(void *opaque)
3094 CharDriverState *chr = opaque;
3095 TCPCharDriver *s = chr->opaque;
3096 if (!s->connected)
3097 return 0;
3098 s->max_size = qemu_chr_can_read(chr);
3099 return s->max_size;
3102 #define IAC 255
3103 #define IAC_BREAK 243
3104 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3105 TCPCharDriver *s,
3106 uint8_t *buf, int *size)
3108 /* Handle any telnet client's basic IAC options to satisfy char by
3109 * char mode with no echo. All IAC options will be removed from
3110 * the buf and the do_telnetopt variable will be used to track the
3111 * state of the width of the IAC information.
3113 * IAC commands come in sets of 3 bytes with the exception of the
3114 * "IAC BREAK" command and the double IAC.
3117 int i;
3118 int j = 0;
3120 for (i = 0; i < *size; i++) {
3121 if (s->do_telnetopt > 1) {
3122 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3123 /* Double IAC means send an IAC */
3124 if (j != i)
3125 buf[j] = buf[i];
3126 j++;
3127 s->do_telnetopt = 1;
3128 } else {
3129 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3130 /* Handle IAC break commands by sending a serial break */
3131 qemu_chr_event(chr, CHR_EVENT_BREAK);
3132 s->do_telnetopt++;
3134 s->do_telnetopt++;
3136 if (s->do_telnetopt >= 4) {
3137 s->do_telnetopt = 1;
3139 } else {
3140 if ((unsigned char)buf[i] == IAC) {
3141 s->do_telnetopt = 2;
3142 } else {
3143 if (j != i)
3144 buf[j] = buf[i];
3145 j++;
3149 *size = j;
3152 static void tcp_chr_read(void *opaque)
3154 CharDriverState *chr = opaque;
3155 TCPCharDriver *s = chr->opaque;
3156 uint8_t buf[1024];
3157 int len, size;
3159 if (!s->connected || s->max_size <= 0)
3160 return;
3161 len = sizeof(buf);
3162 if (len > s->max_size)
3163 len = s->max_size;
3164 size = recv(s->fd, buf, len, 0);
3165 if (size == 0) {
3166 /* connection closed */
3167 s->connected = 0;
3168 if (s->listen_fd >= 0) {
3169 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3171 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3172 closesocket(s->fd);
3173 s->fd = -1;
3174 } else if (size > 0) {
3175 if (s->do_telnetopt)
3176 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3177 if (size > 0)
3178 qemu_chr_read(chr, buf, size);
3182 static void tcp_chr_connect(void *opaque)
3184 CharDriverState *chr = opaque;
3185 TCPCharDriver *s = chr->opaque;
3187 s->connected = 1;
3188 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3189 tcp_chr_read, NULL, chr);
3190 qemu_chr_reset(chr);
3193 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3194 static void tcp_chr_telnet_init(int fd)
3196 char buf[3];
3197 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3198 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3199 send(fd, (char *)buf, 3, 0);
3200 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3201 send(fd, (char *)buf, 3, 0);
3202 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3203 send(fd, (char *)buf, 3, 0);
3204 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3205 send(fd, (char *)buf, 3, 0);
3208 static void socket_set_nodelay(int fd)
3210 int val = 1;
3211 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3214 static void tcp_chr_accept(void *opaque)
3216 CharDriverState *chr = opaque;
3217 TCPCharDriver *s = chr->opaque;
3218 struct sockaddr_in saddr;
3219 #ifndef _WIN32
3220 struct sockaddr_un uaddr;
3221 #endif
3222 struct sockaddr *addr;
3223 socklen_t len;
3224 int fd;
3226 for(;;) {
3227 #ifndef _WIN32
3228 if (s->is_unix) {
3229 len = sizeof(uaddr);
3230 addr = (struct sockaddr *)&uaddr;
3231 } else
3232 #endif
3234 len = sizeof(saddr);
3235 addr = (struct sockaddr *)&saddr;
3237 fd = accept(s->listen_fd, addr, &len);
3238 if (fd < 0 && errno != EINTR) {
3239 return;
3240 } else if (fd >= 0) {
3241 if (s->do_telnetopt)
3242 tcp_chr_telnet_init(fd);
3243 break;
3246 socket_set_nonblock(fd);
3247 if (s->do_nodelay)
3248 socket_set_nodelay(fd);
3249 s->fd = fd;
3250 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3251 tcp_chr_connect(chr);
3254 static void tcp_chr_close(CharDriverState *chr)
3256 TCPCharDriver *s = chr->opaque;
3257 if (s->fd >= 0)
3258 closesocket(s->fd);
3259 if (s->listen_fd >= 0)
3260 closesocket(s->listen_fd);
3261 qemu_free(s);
3264 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3265 int is_telnet,
3266 int is_unix)
3268 CharDriverState *chr = NULL;
3269 TCPCharDriver *s = NULL;
3270 int fd = -1, ret, err, val;
3271 int is_listen = 0;
3272 int is_waitconnect = 1;
3273 int do_nodelay = 0;
3274 const char *ptr;
3275 struct sockaddr_in saddr;
3276 #ifndef _WIN32
3277 struct sockaddr_un uaddr;
3278 #endif
3279 struct sockaddr *addr;
3280 socklen_t addrlen;
3282 #ifndef _WIN32
3283 if (is_unix) {
3284 addr = (struct sockaddr *)&uaddr;
3285 addrlen = sizeof(uaddr);
3286 if (parse_unix_path(&uaddr, host_str) < 0)
3287 goto fail;
3288 } else
3289 #endif
3291 addr = (struct sockaddr *)&saddr;
3292 addrlen = sizeof(saddr);
3293 if (parse_host_port(&saddr, host_str) < 0)
3294 goto fail;
3297 ptr = host_str;
3298 while((ptr = strchr(ptr,','))) {
3299 ptr++;
3300 if (!strncmp(ptr,"server",6)) {
3301 is_listen = 1;
3302 } else if (!strncmp(ptr,"nowait",6)) {
3303 is_waitconnect = 0;
3304 } else if (!strncmp(ptr,"nodelay",6)) {
3305 do_nodelay = 1;
3306 } else {
3307 printf("Unknown option: %s\n", ptr);
3308 goto fail;
3311 if (!is_listen)
3312 is_waitconnect = 0;
3314 chr = qemu_mallocz(sizeof(CharDriverState));
3315 if (!chr)
3316 goto fail;
3317 s = qemu_mallocz(sizeof(TCPCharDriver));
3318 if (!s)
3319 goto fail;
3321 #ifndef _WIN32
3322 if (is_unix)
3323 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3324 else
3325 #endif
3326 fd = socket(PF_INET, SOCK_STREAM, 0);
3328 if (fd < 0)
3329 goto fail;
3331 if (!is_waitconnect)
3332 socket_set_nonblock(fd);
3334 s->connected = 0;
3335 s->fd = -1;
3336 s->listen_fd = -1;
3337 s->is_unix = is_unix;
3338 s->do_nodelay = do_nodelay && !is_unix;
3340 chr->opaque = s;
3341 chr->chr_write = tcp_chr_write;
3342 chr->chr_close = tcp_chr_close;
3344 if (is_listen) {
3345 /* allow fast reuse */
3346 #ifndef _WIN32
3347 if (is_unix) {
3348 char path[109];
3349 strncpy(path, uaddr.sun_path, 108);
3350 path[108] = 0;
3351 unlink(path);
3352 } else
3353 #endif
3355 val = 1;
3356 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3359 ret = bind(fd, addr, addrlen);
3360 if (ret < 0)
3361 goto fail;
3363 ret = listen(fd, 0);
3364 if (ret < 0)
3365 goto fail;
3367 s->listen_fd = fd;
3368 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3369 if (is_telnet)
3370 s->do_telnetopt = 1;
3371 } else {
3372 for(;;) {
3373 ret = connect(fd, addr, addrlen);
3374 if (ret < 0) {
3375 err = socket_error();
3376 if (err == EINTR || err == EWOULDBLOCK) {
3377 } else if (err == EINPROGRESS) {
3378 break;
3379 #ifdef _WIN32
3380 } else if (err == WSAEALREADY) {
3381 break;
3382 #endif
3383 } else {
3384 goto fail;
3386 } else {
3387 s->connected = 1;
3388 break;
3391 s->fd = fd;
3392 socket_set_nodelay(fd);
3393 if (s->connected)
3394 tcp_chr_connect(chr);
3395 else
3396 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3399 if (is_listen && is_waitconnect) {
3400 printf("QEMU waiting for connection on: %s\n", host_str);
3401 tcp_chr_accept(chr);
3402 socket_set_nonblock(s->listen_fd);
3405 return chr;
3406 fail:
3407 if (fd >= 0)
3408 closesocket(fd);
3409 qemu_free(s);
3410 qemu_free(chr);
3411 return NULL;
3414 CharDriverState *qemu_chr_open(const char *filename)
3416 const char *p;
3418 if (!strcmp(filename, "vc")) {
3419 return text_console_init(&display_state, 0);
3420 } else if (strstart(filename, "vc:", &p)) {
3421 return text_console_init(&display_state, p);
3422 } else if (!strcmp(filename, "null")) {
3423 return qemu_chr_open_null();
3424 } else
3425 if (strstart(filename, "tcp:", &p)) {
3426 return qemu_chr_open_tcp(p, 0, 0);
3427 } else
3428 if (strstart(filename, "telnet:", &p)) {
3429 return qemu_chr_open_tcp(p, 1, 0);
3430 } else
3431 if (strstart(filename, "udp:", &p)) {
3432 return qemu_chr_open_udp(p);
3433 } else
3434 if (strstart(filename, "mon:", &p)) {
3435 CharDriverState *drv = qemu_chr_open(p);
3436 if (drv) {
3437 drv = qemu_chr_open_mux(drv);
3438 monitor_init(drv, !nographic);
3439 return drv;
3441 printf("Unable to open driver: %s\n", p);
3442 return 0;
3443 } else
3444 #ifndef _WIN32
3445 if (strstart(filename, "unix:", &p)) {
3446 return qemu_chr_open_tcp(p, 0, 1);
3447 } else if (strstart(filename, "file:", &p)) {
3448 return qemu_chr_open_file_out(p);
3449 } else if (strstart(filename, "pipe:", &p)) {
3450 return qemu_chr_open_pipe(p);
3451 } else if (!strcmp(filename, "pty")) {
3452 return qemu_chr_open_pty();
3453 } else if (!strcmp(filename, "stdio")) {
3454 return qemu_chr_open_stdio();
3455 } else
3456 #if defined(__linux__)
3457 if (strstart(filename, "/dev/parport", NULL)) {
3458 return qemu_chr_open_pp(filename);
3459 } else
3460 #endif
3461 #if defined(__linux__) || defined(__sun__)
3462 if (strstart(filename, "/dev/", NULL)) {
3463 return qemu_chr_open_tty(filename);
3464 } else
3465 #endif
3466 #else /* !_WIN32 */
3467 if (strstart(filename, "COM", NULL)) {
3468 return qemu_chr_open_win(filename);
3469 } else
3470 if (strstart(filename, "pipe:", &p)) {
3471 return qemu_chr_open_win_pipe(p);
3472 } else
3473 if (strstart(filename, "con:", NULL)) {
3474 return qemu_chr_open_win_con(filename);
3475 } else
3476 if (strstart(filename, "file:", &p)) {
3477 return qemu_chr_open_win_file_out(p);
3478 } else
3479 #endif
3480 #ifdef CONFIG_BRLAPI
3481 if (!strcmp(filename, "braille")) {
3482 return chr_baum_init();
3483 } else
3484 #endif
3486 return NULL;
3490 void qemu_chr_close(CharDriverState *chr)
3492 if (chr->chr_close)
3493 chr->chr_close(chr);
3494 qemu_free(chr);
3497 /***********************************************************/
3498 /* network device redirectors */
3500 __attribute__ (( unused ))
3501 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3503 int len, i, j, c;
3505 for(i=0;i<size;i+=16) {
3506 len = size - i;
3507 if (len > 16)
3508 len = 16;
3509 fprintf(f, "%08x ", i);
3510 for(j=0;j<16;j++) {
3511 if (j < len)
3512 fprintf(f, " %02x", buf[i+j]);
3513 else
3514 fprintf(f, " ");
3516 fprintf(f, " ");
3517 for(j=0;j<len;j++) {
3518 c = buf[i+j];
3519 if (c < ' ' || c > '~')
3520 c = '.';
3521 fprintf(f, "%c", c);
3523 fprintf(f, "\n");
3527 static int parse_macaddr(uint8_t *macaddr, const char *p)
3529 int i;
3530 char *last_char;
3531 long int offset;
3533 errno = 0;
3534 offset = strtol(p, &last_char, 0);
3535 if (0 == errno && '\0' == *last_char &&
3536 offset >= 0 && offset <= 0xFFFFFF) {
3537 macaddr[3] = (offset & 0xFF0000) >> 16;
3538 macaddr[4] = (offset & 0xFF00) >> 8;
3539 macaddr[5] = offset & 0xFF;
3540 return 0;
3541 } else {
3542 for(i = 0; i < 6; i++) {
3543 macaddr[i] = strtol(p, (char **)&p, 16);
3544 if (i == 5) {
3545 if (*p != '\0')
3546 return -1;
3547 } else {
3548 if (*p != ':' && *p != '-')
3549 return -1;
3550 p++;
3553 return 0;
3556 return -1;
3559 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3561 const char *p, *p1;
3562 int len;
3563 p = *pp;
3564 p1 = strchr(p, sep);
3565 if (!p1)
3566 return -1;
3567 len = p1 - p;
3568 p1++;
3569 if (buf_size > 0) {
3570 if (len > buf_size - 1)
3571 len = buf_size - 1;
3572 memcpy(buf, p, len);
3573 buf[len] = '\0';
3575 *pp = p1;
3576 return 0;
3579 int parse_host_src_port(struct sockaddr_in *haddr,
3580 struct sockaddr_in *saddr,
3581 const char *input_str)
3583 char *str = strdup(input_str);
3584 char *host_str = str;
3585 char *src_str;
3586 char *ptr;
3589 * Chop off any extra arguments at the end of the string which
3590 * would start with a comma, then fill in the src port information
3591 * if it was provided else use the "any address" and "any port".
3593 if ((ptr = strchr(str,',')))
3594 *ptr = '\0';
3596 if ((src_str = strchr(input_str,'@'))) {
3597 *src_str = '\0';
3598 src_str++;
3601 if (parse_host_port(haddr, host_str) < 0)
3602 goto fail;
3604 if (!src_str || *src_str == '\0')
3605 src_str = ":0";
3607 if (parse_host_port(saddr, src_str) < 0)
3608 goto fail;
3610 free(str);
3611 return(0);
3613 fail:
3614 free(str);
3615 return -1;
3618 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3620 char buf[512];
3621 struct hostent *he;
3622 const char *p, *r;
3623 int port;
3625 p = str;
3626 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3627 return -1;
3628 saddr->sin_family = AF_INET;
3629 if (buf[0] == '\0') {
3630 saddr->sin_addr.s_addr = 0;
3631 } else {
3632 if (isdigit(buf[0])) {
3633 if (!inet_aton(buf, &saddr->sin_addr))
3634 return -1;
3635 } else {
3636 if ((he = gethostbyname(buf)) == NULL)
3637 return - 1;
3638 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3641 port = strtol(p, (char **)&r, 0);
3642 if (r == p)
3643 return -1;
3644 saddr->sin_port = htons(port);
3645 return 0;
3648 #ifndef _WIN32
3649 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3651 const char *p;
3652 int len;
3654 len = MIN(108, strlen(str));
3655 p = strchr(str, ',');
3656 if (p)
3657 len = MIN(len, p - str);
3659 memset(uaddr, 0, sizeof(*uaddr));
3661 uaddr->sun_family = AF_UNIX;
3662 memcpy(uaddr->sun_path, str, len);
3664 return 0;
3666 #endif
3668 /* find or alloc a new VLAN */
3669 VLANState *qemu_find_vlan(int id)
3671 VLANState **pvlan, *vlan;
3672 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3673 if (vlan->id == id)
3674 return vlan;
3676 vlan = qemu_mallocz(sizeof(VLANState));
3677 if (!vlan)
3678 return NULL;
3679 vlan->id = id;
3680 vlan->next = NULL;
3681 pvlan = &first_vlan;
3682 while (*pvlan != NULL)
3683 pvlan = &(*pvlan)->next;
3684 *pvlan = vlan;
3685 return vlan;
3688 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3689 IOReadHandler *fd_read,
3690 IOCanRWHandler *fd_can_read,
3691 void *opaque)
3693 VLANClientState *vc, **pvc;
3694 vc = qemu_mallocz(sizeof(VLANClientState));
3695 if (!vc)
3696 return NULL;
3697 vc->fd_read = fd_read;
3698 vc->fd_can_read = fd_can_read;
3699 vc->opaque = opaque;
3700 vc->vlan = vlan;
3702 vc->next = NULL;
3703 pvc = &vlan->first_client;
3704 while (*pvc != NULL)
3705 pvc = &(*pvc)->next;
3706 *pvc = vc;
3707 return vc;
3710 int qemu_can_send_packet(VLANClientState *vc1)
3712 VLANState *vlan = vc1->vlan;
3713 VLANClientState *vc;
3715 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3716 if (vc != vc1) {
3717 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3718 return 1;
3721 return 0;
3724 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3726 VLANState *vlan = vc1->vlan;
3727 VLANClientState *vc;
3729 #if 0
3730 printf("vlan %d send:\n", vlan->id);
3731 hex_dump(stdout, buf, size);
3732 #endif
3733 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3734 if (vc != vc1) {
3735 vc->fd_read(vc->opaque, buf, size);
3740 #if defined(CONFIG_SLIRP)
3742 /* slirp network adapter */
3744 static int slirp_inited;
3745 static VLANClientState *slirp_vc;
3747 int slirp_can_output(void)
3749 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3752 void slirp_output(const uint8_t *pkt, int pkt_len)
3754 #if 0
3755 printf("slirp output:\n");
3756 hex_dump(stdout, pkt, pkt_len);
3757 #endif
3758 if (!slirp_vc)
3759 return;
3760 qemu_send_packet(slirp_vc, pkt, pkt_len);
3763 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3765 #if 0
3766 printf("slirp input:\n");
3767 hex_dump(stdout, buf, size);
3768 #endif
3769 slirp_input(buf, size);
3772 static int net_slirp_init(VLANState *vlan)
3774 if (!slirp_inited) {
3775 slirp_inited = 1;
3776 slirp_init();
3778 slirp_vc = qemu_new_vlan_client(vlan,
3779 slirp_receive, NULL, NULL);
3780 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3781 return 0;
3784 static void net_slirp_redir(const char *redir_str)
3786 int is_udp;
3787 char buf[256], *r;
3788 const char *p;
3789 struct in_addr guest_addr;
3790 int host_port, guest_port;
3792 if (!slirp_inited) {
3793 slirp_inited = 1;
3794 slirp_init();
3797 p = redir_str;
3798 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3799 goto fail;
3800 if (!strcmp(buf, "tcp")) {
3801 is_udp = 0;
3802 } else if (!strcmp(buf, "udp")) {
3803 is_udp = 1;
3804 } else {
3805 goto fail;
3808 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3809 goto fail;
3810 host_port = strtol(buf, &r, 0);
3811 if (r == buf)
3812 goto fail;
3814 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3815 goto fail;
3816 if (buf[0] == '\0') {
3817 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3819 if (!inet_aton(buf, &guest_addr))
3820 goto fail;
3822 guest_port = strtol(p, &r, 0);
3823 if (r == p)
3824 goto fail;
3826 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3827 fprintf(stderr, "qemu: could not set up redirection\n");
3828 exit(1);
3830 return;
3831 fail:
3832 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3833 exit(1);
3836 #ifndef _WIN32
3838 char smb_dir[1024];
3840 static void erase_dir(char *dir_name)
3842 DIR *d;
3843 struct dirent *de;
3844 char filename[1024];
3846 /* erase all the files in the directory */
3847 if ((d = opendir(dir_name)) != 0) {
3848 for(;;) {
3849 de = readdir(d);
3850 if (!de)
3851 break;
3852 if (strcmp(de->d_name, ".") != 0 &&
3853 strcmp(de->d_name, "..") != 0) {
3854 snprintf(filename, sizeof(filename), "%s/%s",
3855 smb_dir, de->d_name);
3856 if (unlink(filename) != 0) /* is it a directory? */
3857 erase_dir(filename);
3860 closedir(d);
3861 rmdir(dir_name);
3865 /* automatic user mode samba server configuration */
3866 static void smb_exit(void)
3868 erase_dir(smb_dir);
3871 /* automatic user mode samba server configuration */
3872 static void net_slirp_smb(const char *exported_dir)
3874 char smb_conf[1024];
3875 char smb_cmdline[1024];
3876 FILE *f;
3878 if (!slirp_inited) {
3879 slirp_inited = 1;
3880 slirp_init();
3883 /* XXX: better tmp dir construction */
3884 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3885 if (mkdir(smb_dir, 0700) < 0) {
3886 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3887 exit(1);
3889 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3891 f = fopen(smb_conf, "w");
3892 if (!f) {
3893 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3894 exit(1);
3896 fprintf(f,
3897 "[global]\n"
3898 "private dir=%s\n"
3899 "smb ports=0\n"
3900 "socket address=127.0.0.1\n"
3901 "pid directory=%s\n"
3902 "lock directory=%s\n"
3903 "log file=%s/log.smbd\n"
3904 "smb passwd file=%s/smbpasswd\n"
3905 "security = share\n"
3906 "[qemu]\n"
3907 "path=%s\n"
3908 "read only=no\n"
3909 "guest ok=yes\n",
3910 smb_dir,
3911 smb_dir,
3912 smb_dir,
3913 smb_dir,
3914 smb_dir,
3915 exported_dir
3917 fclose(f);
3918 atexit(smb_exit);
3920 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3921 SMBD_COMMAND, smb_conf);
3923 slirp_add_exec(0, smb_cmdline, 4, 139);
3926 #endif /* !defined(_WIN32) */
3927 void do_info_slirp(void)
3929 slirp_stats();
3932 #endif /* CONFIG_SLIRP */
3934 #if !defined(_WIN32)
3936 typedef struct TAPState {
3937 VLANClientState *vc;
3938 int fd;
3939 char down_script[1024];
3940 } TAPState;
3942 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3944 TAPState *s = opaque;
3945 int ret;
3946 for(;;) {
3947 ret = write(s->fd, buf, size);
3948 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3949 } else {
3950 break;
3955 static void tap_send(void *opaque)
3957 TAPState *s = opaque;
3958 uint8_t buf[4096];
3959 int size;
3961 #ifdef __sun__
3962 struct strbuf sbuf;
3963 int f = 0;
3964 sbuf.maxlen = sizeof(buf);
3965 sbuf.buf = buf;
3966 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3967 #else
3968 size = read(s->fd, buf, sizeof(buf));
3969 #endif
3970 if (size > 0) {
3971 qemu_send_packet(s->vc, buf, size);
3975 /* fd support */
3977 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3979 TAPState *s;
3981 s = qemu_mallocz(sizeof(TAPState));
3982 if (!s)
3983 return NULL;
3984 s->fd = fd;
3985 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3986 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3987 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3988 return s;
3991 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3992 static int tap_open(char *ifname, int ifname_size)
3994 int fd;
3995 char *dev;
3996 struct stat s;
3998 TFR(fd = open("/dev/tap", O_RDWR));
3999 if (fd < 0) {
4000 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4001 return -1;
4004 fstat(fd, &s);
4005 dev = devname(s.st_rdev, S_IFCHR);
4006 pstrcpy(ifname, ifname_size, dev);
4008 fcntl(fd, F_SETFL, O_NONBLOCK);
4009 return fd;
4011 #elif defined(__sun__)
4012 #define TUNNEWPPA (('T'<<16) | 0x0001)
4014 * Allocate TAP device, returns opened fd.
4015 * Stores dev name in the first arg(must be large enough).
4017 int tap_alloc(char *dev)
4019 int tap_fd, if_fd, ppa = -1;
4020 static int ip_fd = 0;
4021 char *ptr;
4023 static int arp_fd = 0;
4024 int ip_muxid, arp_muxid;
4025 struct strioctl strioc_if, strioc_ppa;
4026 int link_type = I_PLINK;;
4027 struct lifreq ifr;
4028 char actual_name[32] = "";
4030 memset(&ifr, 0x0, sizeof(ifr));
4032 if( *dev ){
4033 ptr = dev;
4034 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4035 ppa = atoi(ptr);
4038 /* Check if IP device was opened */
4039 if( ip_fd )
4040 close(ip_fd);
4042 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4043 if (ip_fd < 0) {
4044 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4045 return -1;
4048 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4049 if (tap_fd < 0) {
4050 syslog(LOG_ERR, "Can't open /dev/tap");
4051 return -1;
4054 /* Assign a new PPA and get its unit number. */
4055 strioc_ppa.ic_cmd = TUNNEWPPA;
4056 strioc_ppa.ic_timout = 0;
4057 strioc_ppa.ic_len = sizeof(ppa);
4058 strioc_ppa.ic_dp = (char *)&ppa;
4059 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4060 syslog (LOG_ERR, "Can't assign new interface");
4062 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4063 if (if_fd < 0) {
4064 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4065 return -1;
4067 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4068 syslog(LOG_ERR, "Can't push IP module");
4069 return -1;
4072 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4073 syslog(LOG_ERR, "Can't get flags\n");
4075 snprintf (actual_name, 32, "tap%d", ppa);
4076 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4078 ifr.lifr_ppa = ppa;
4079 /* Assign ppa according to the unit number returned by tun device */
4081 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4082 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4083 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4084 syslog (LOG_ERR, "Can't get flags\n");
4085 /* Push arp module to if_fd */
4086 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4087 syslog (LOG_ERR, "Can't push ARP module (2)");
4089 /* Push arp module to ip_fd */
4090 if (ioctl (ip_fd, I_POP, NULL) < 0)
4091 syslog (LOG_ERR, "I_POP failed\n");
4092 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4093 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4094 /* Open arp_fd */
4095 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4096 if (arp_fd < 0)
4097 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4099 /* Set ifname to arp */
4100 strioc_if.ic_cmd = SIOCSLIFNAME;
4101 strioc_if.ic_timout = 0;
4102 strioc_if.ic_len = sizeof(ifr);
4103 strioc_if.ic_dp = (char *)&ifr;
4104 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4105 syslog (LOG_ERR, "Can't set ifname to arp\n");
4108 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4109 syslog(LOG_ERR, "Can't link TAP device to IP");
4110 return -1;
4113 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4114 syslog (LOG_ERR, "Can't link TAP device to ARP");
4116 close (if_fd);
4118 memset(&ifr, 0x0, sizeof(ifr));
4119 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4120 ifr.lifr_ip_muxid = ip_muxid;
4121 ifr.lifr_arp_muxid = arp_muxid;
4123 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4125 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4126 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4127 syslog (LOG_ERR, "Can't set multiplexor id");
4130 sprintf(dev, "tap%d", ppa);
4131 return tap_fd;
4134 static int tap_open(char *ifname, int ifname_size)
4136 char dev[10]="";
4137 int fd;
4138 if( (fd = tap_alloc(dev)) < 0 ){
4139 fprintf(stderr, "Cannot allocate TAP device\n");
4140 return -1;
4142 pstrcpy(ifname, ifname_size, dev);
4143 fcntl(fd, F_SETFL, O_NONBLOCK);
4144 return fd;
4146 #else
4147 static int tap_open(char *ifname, int ifname_size)
4149 struct ifreq ifr;
4150 int fd, ret;
4152 TFR(fd = open("/dev/net/tun", O_RDWR));
4153 if (fd < 0) {
4154 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4155 return -1;
4157 memset(&ifr, 0, sizeof(ifr));
4158 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4159 if (ifname[0] != '\0')
4160 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4161 else
4162 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4163 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4164 if (ret != 0) {
4165 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4166 close(fd);
4167 return -1;
4169 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4170 fcntl(fd, F_SETFL, O_NONBLOCK);
4171 return fd;
4173 #endif
4175 static int launch_script(const char *setup_script, const char *ifname, int fd)
4177 int pid, status;
4178 char *args[3];
4179 char **parg;
4181 /* try to launch network script */
4182 pid = fork();
4183 if (pid >= 0) {
4184 if (pid == 0) {
4185 int open_max = sysconf (_SC_OPEN_MAX), i;
4186 for (i = 0; i < open_max; i++)
4187 if (i != STDIN_FILENO &&
4188 i != STDOUT_FILENO &&
4189 i != STDERR_FILENO &&
4190 i != fd)
4191 close(i);
4193 parg = args;
4194 *parg++ = (char *)setup_script;
4195 *parg++ = (char *)ifname;
4196 *parg++ = NULL;
4197 execv(setup_script, args);
4198 _exit(1);
4200 while (waitpid(pid, &status, 0) != pid);
4201 if (!WIFEXITED(status) ||
4202 WEXITSTATUS(status) != 0) {
4203 fprintf(stderr, "%s: could not launch network script\n",
4204 setup_script);
4205 return -1;
4208 return 0;
4211 static int net_tap_init(VLANState *vlan, const char *ifname1,
4212 const char *setup_script, const char *down_script)
4214 TAPState *s;
4215 int fd;
4216 char ifname[128];
4218 if (ifname1 != NULL)
4219 pstrcpy(ifname, sizeof(ifname), ifname1);
4220 else
4221 ifname[0] = '\0';
4222 TFR(fd = tap_open(ifname, sizeof(ifname)));
4223 if (fd < 0)
4224 return -1;
4226 if (!setup_script || !strcmp(setup_script, "no"))
4227 setup_script = "";
4228 if (setup_script[0] != '\0') {
4229 if (launch_script(setup_script, ifname, fd))
4230 return -1;
4232 s = net_tap_fd_init(vlan, fd);
4233 if (!s)
4234 return -1;
4235 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4236 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4237 if (down_script && strcmp(down_script, "no"))
4238 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4239 return 0;
4242 #endif /* !_WIN32 */
4244 /* network connection */
4245 typedef struct NetSocketState {
4246 VLANClientState *vc;
4247 int fd;
4248 int state; /* 0 = getting length, 1 = getting data */
4249 int index;
4250 int packet_len;
4251 uint8_t buf[4096];
4252 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4253 } NetSocketState;
4255 typedef struct NetSocketListenState {
4256 VLANState *vlan;
4257 int fd;
4258 } NetSocketListenState;
4260 /* XXX: we consider we can send the whole packet without blocking */
4261 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4263 NetSocketState *s = opaque;
4264 uint32_t len;
4265 len = htonl(size);
4267 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4268 send_all(s->fd, buf, size);
4271 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4273 NetSocketState *s = opaque;
4274 sendto(s->fd, buf, size, 0,
4275 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4278 static void net_socket_send(void *opaque)
4280 NetSocketState *s = opaque;
4281 int l, size, err;
4282 uint8_t buf1[4096];
4283 const uint8_t *buf;
4285 size = recv(s->fd, buf1, sizeof(buf1), 0);
4286 if (size < 0) {
4287 err = socket_error();
4288 if (err != EWOULDBLOCK)
4289 goto eoc;
4290 } else if (size == 0) {
4291 /* end of connection */
4292 eoc:
4293 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4294 closesocket(s->fd);
4295 return;
4297 buf = buf1;
4298 while (size > 0) {
4299 /* reassemble a packet from the network */
4300 switch(s->state) {
4301 case 0:
4302 l = 4 - s->index;
4303 if (l > size)
4304 l = size;
4305 memcpy(s->buf + s->index, buf, l);
4306 buf += l;
4307 size -= l;
4308 s->index += l;
4309 if (s->index == 4) {
4310 /* got length */
4311 s->packet_len = ntohl(*(uint32_t *)s->buf);
4312 s->index = 0;
4313 s->state = 1;
4315 break;
4316 case 1:
4317 l = s->packet_len - s->index;
4318 if (l > size)
4319 l = size;
4320 memcpy(s->buf + s->index, buf, l);
4321 s->index += l;
4322 buf += l;
4323 size -= l;
4324 if (s->index >= s->packet_len) {
4325 qemu_send_packet(s->vc, s->buf, s->packet_len);
4326 s->index = 0;
4327 s->state = 0;
4329 break;
4334 static void net_socket_send_dgram(void *opaque)
4336 NetSocketState *s = opaque;
4337 int size;
4339 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4340 if (size < 0)
4341 return;
4342 if (size == 0) {
4343 /* end of connection */
4344 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4345 return;
4347 qemu_send_packet(s->vc, s->buf, size);
4350 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4352 struct ip_mreq imr;
4353 int fd;
4354 int val, ret;
4355 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4356 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4357 inet_ntoa(mcastaddr->sin_addr),
4358 (int)ntohl(mcastaddr->sin_addr.s_addr));
4359 return -1;
4362 fd = socket(PF_INET, SOCK_DGRAM, 0);
4363 if (fd < 0) {
4364 perror("socket(PF_INET, SOCK_DGRAM)");
4365 return -1;
4368 val = 1;
4369 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4370 (const char *)&val, sizeof(val));
4371 if (ret < 0) {
4372 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4373 goto fail;
4376 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4377 if (ret < 0) {
4378 perror("bind");
4379 goto fail;
4382 /* Add host to multicast group */
4383 imr.imr_multiaddr = mcastaddr->sin_addr;
4384 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4386 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4387 (const char *)&imr, sizeof(struct ip_mreq));
4388 if (ret < 0) {
4389 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4390 goto fail;
4393 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4394 val = 1;
4395 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4396 (const char *)&val, sizeof(val));
4397 if (ret < 0) {
4398 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4399 goto fail;
4402 socket_set_nonblock(fd);
4403 return fd;
4404 fail:
4405 if (fd >= 0)
4406 closesocket(fd);
4407 return -1;
4410 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4411 int is_connected)
4413 struct sockaddr_in saddr;
4414 int newfd;
4415 socklen_t saddr_len;
4416 NetSocketState *s;
4418 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4419 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4420 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4423 if (is_connected) {
4424 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4425 /* must be bound */
4426 if (saddr.sin_addr.s_addr==0) {
4427 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4428 fd);
4429 return NULL;
4431 /* clone dgram socket */
4432 newfd = net_socket_mcast_create(&saddr);
4433 if (newfd < 0) {
4434 /* error already reported by net_socket_mcast_create() */
4435 close(fd);
4436 return NULL;
4438 /* clone newfd to fd, close newfd */
4439 dup2(newfd, fd);
4440 close(newfd);
4442 } else {
4443 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4444 fd, strerror(errno));
4445 return NULL;
4449 s = qemu_mallocz(sizeof(NetSocketState));
4450 if (!s)
4451 return NULL;
4452 s->fd = fd;
4454 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4455 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4457 /* mcast: save bound address as dst */
4458 if (is_connected) s->dgram_dst=saddr;
4460 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4461 "socket: fd=%d (%s mcast=%s:%d)",
4462 fd, is_connected? "cloned" : "",
4463 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4464 return s;
4467 static void net_socket_connect(void *opaque)
4469 NetSocketState *s = opaque;
4470 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4473 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4474 int is_connected)
4476 NetSocketState *s;
4477 s = qemu_mallocz(sizeof(NetSocketState));
4478 if (!s)
4479 return NULL;
4480 s->fd = fd;
4481 s->vc = qemu_new_vlan_client(vlan,
4482 net_socket_receive, NULL, s);
4483 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4484 "socket: fd=%d", fd);
4485 if (is_connected) {
4486 net_socket_connect(s);
4487 } else {
4488 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4490 return s;
4493 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4494 int is_connected)
4496 int so_type=-1, optlen=sizeof(so_type);
4498 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4499 (socklen_t *)&optlen)< 0) {
4500 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4501 return NULL;
4503 switch(so_type) {
4504 case SOCK_DGRAM:
4505 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4506 case SOCK_STREAM:
4507 return net_socket_fd_init_stream(vlan, fd, is_connected);
4508 default:
4509 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4510 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4511 return net_socket_fd_init_stream(vlan, fd, is_connected);
4513 return NULL;
4516 static void net_socket_accept(void *opaque)
4518 NetSocketListenState *s = opaque;
4519 NetSocketState *s1;
4520 struct sockaddr_in saddr;
4521 socklen_t len;
4522 int fd;
4524 for(;;) {
4525 len = sizeof(saddr);
4526 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4527 if (fd < 0 && errno != EINTR) {
4528 return;
4529 } else if (fd >= 0) {
4530 break;
4533 s1 = net_socket_fd_init(s->vlan, fd, 1);
4534 if (!s1) {
4535 closesocket(fd);
4536 } else {
4537 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4538 "socket: connection from %s:%d",
4539 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4543 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4545 NetSocketListenState *s;
4546 int fd, val, ret;
4547 struct sockaddr_in saddr;
4549 if (parse_host_port(&saddr, host_str) < 0)
4550 return -1;
4552 s = qemu_mallocz(sizeof(NetSocketListenState));
4553 if (!s)
4554 return -1;
4556 fd = socket(PF_INET, SOCK_STREAM, 0);
4557 if (fd < 0) {
4558 perror("socket");
4559 return -1;
4561 socket_set_nonblock(fd);
4563 /* allow fast reuse */
4564 val = 1;
4565 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4567 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4568 if (ret < 0) {
4569 perror("bind");
4570 return -1;
4572 ret = listen(fd, 0);
4573 if (ret < 0) {
4574 perror("listen");
4575 return -1;
4577 s->vlan = vlan;
4578 s->fd = fd;
4579 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4580 return 0;
4583 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4585 NetSocketState *s;
4586 int fd, connected, ret, err;
4587 struct sockaddr_in saddr;
4589 if (parse_host_port(&saddr, host_str) < 0)
4590 return -1;
4592 fd = socket(PF_INET, SOCK_STREAM, 0);
4593 if (fd < 0) {
4594 perror("socket");
4595 return -1;
4597 socket_set_nonblock(fd);
4599 connected = 0;
4600 for(;;) {
4601 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4602 if (ret < 0) {
4603 err = socket_error();
4604 if (err == EINTR || err == EWOULDBLOCK) {
4605 } else if (err == EINPROGRESS) {
4606 break;
4607 #ifdef _WIN32
4608 } else if (err == WSAEALREADY) {
4609 break;
4610 #endif
4611 } else {
4612 perror("connect");
4613 closesocket(fd);
4614 return -1;
4616 } else {
4617 connected = 1;
4618 break;
4621 s = net_socket_fd_init(vlan, fd, connected);
4622 if (!s)
4623 return -1;
4624 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4625 "socket: connect to %s:%d",
4626 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4627 return 0;
4630 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4632 NetSocketState *s;
4633 int fd;
4634 struct sockaddr_in saddr;
4636 if (parse_host_port(&saddr, host_str) < 0)
4637 return -1;
4640 fd = net_socket_mcast_create(&saddr);
4641 if (fd < 0)
4642 return -1;
4644 s = net_socket_fd_init(vlan, fd, 0);
4645 if (!s)
4646 return -1;
4648 s->dgram_dst = saddr;
4650 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4651 "socket: mcast=%s:%d",
4652 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4653 return 0;
4657 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4659 char *q;
4661 q = buf;
4662 while (*p != '\0' && *p != '=') {
4663 if (q && (q - buf) < buf_size - 1)
4664 *q++ = *p;
4665 p++;
4667 if (q)
4668 *q = '\0';
4670 return p;
4673 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4675 char *q;
4677 q = buf;
4678 while (*p != '\0') {
4679 if (*p == ',') {
4680 if (*(p + 1) != ',')
4681 break;
4682 p++;
4684 if (q && (q - buf) < buf_size - 1)
4685 *q++ = *p;
4686 p++;
4688 if (q)
4689 *q = '\0';
4691 return p;
4694 static int get_param_value(char *buf, int buf_size,
4695 const char *tag, const char *str)
4697 const char *p;
4698 char option[128];
4700 p = str;
4701 for(;;) {
4702 p = get_opt_name(option, sizeof(option), p);
4703 if (*p != '=')
4704 break;
4705 p++;
4706 if (!strcmp(tag, option)) {
4707 (void)get_opt_value(buf, buf_size, p);
4708 return strlen(buf);
4709 } else {
4710 p = get_opt_value(NULL, 0, p);
4712 if (*p != ',')
4713 break;
4714 p++;
4716 return 0;
4719 static int check_params(char *buf, int buf_size,
4720 char **params, const char *str)
4722 const char *p;
4723 int i;
4725 p = str;
4726 for(;;) {
4727 p = get_opt_name(buf, buf_size, p);
4728 if (*p != '=')
4729 return -1;
4730 p++;
4731 for(i = 0; params[i] != NULL; i++)
4732 if (!strcmp(params[i], buf))
4733 break;
4734 if (params[i] == NULL)
4735 return -1;
4736 p = get_opt_value(NULL, 0, p);
4737 if (*p != ',')
4738 break;
4739 p++;
4741 return 0;
4745 static int net_client_init(const char *str)
4747 const char *p;
4748 char *q;
4749 char device[64];
4750 char buf[1024];
4751 int vlan_id, ret;
4752 VLANState *vlan;
4754 p = str;
4755 q = device;
4756 while (*p != '\0' && *p != ',') {
4757 if ((q - device) < sizeof(device) - 1)
4758 *q++ = *p;
4759 p++;
4761 *q = '\0';
4762 if (*p == ',')
4763 p++;
4764 vlan_id = 0;
4765 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4766 vlan_id = strtol(buf, NULL, 0);
4768 vlan = qemu_find_vlan(vlan_id);
4769 if (!vlan) {
4770 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4771 return -1;
4773 if (!strcmp(device, "nic")) {
4774 NICInfo *nd;
4775 uint8_t *macaddr;
4777 if (nb_nics >= MAX_NICS) {
4778 fprintf(stderr, "Too Many NICs\n");
4779 return -1;
4781 nd = &nd_table[nb_nics];
4782 macaddr = nd->macaddr;
4783 macaddr[0] = 0x52;
4784 macaddr[1] = 0x54;
4785 macaddr[2] = 0x00;
4786 macaddr[3] = 0x12;
4787 macaddr[4] = 0x34;
4788 macaddr[5] = 0x56 + nb_nics;
4790 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4791 if (parse_macaddr(macaddr, buf) < 0) {
4792 fprintf(stderr, "invalid syntax for ethernet address\n");
4793 return -1;
4796 if (get_param_value(buf, sizeof(buf), "model", p)) {
4797 nd->model = strdup(buf);
4799 nd->vlan = vlan;
4800 nb_nics++;
4801 vlan->nb_guest_devs++;
4802 ret = 0;
4803 } else
4804 if (!strcmp(device, "none")) {
4805 /* does nothing. It is needed to signal that no network cards
4806 are wanted */
4807 ret = 0;
4808 } else
4809 #ifdef CONFIG_SLIRP
4810 if (!strcmp(device, "user")) {
4811 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4812 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4814 vlan->nb_host_devs++;
4815 ret = net_slirp_init(vlan);
4816 } else
4817 #endif
4818 #ifdef _WIN32
4819 if (!strcmp(device, "tap")) {
4820 char ifname[64];
4821 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4822 fprintf(stderr, "tap: no interface name\n");
4823 return -1;
4825 vlan->nb_host_devs++;
4826 ret = tap_win32_init(vlan, ifname);
4827 } else
4828 #else
4829 if (!strcmp(device, "tap")) {
4830 char ifname[64];
4831 char setup_script[1024], down_script[1024];
4832 int fd;
4833 vlan->nb_host_devs++;
4834 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4835 fd = strtol(buf, NULL, 0);
4836 fcntl(fd, F_SETFL, O_NONBLOCK);
4837 ret = -1;
4838 if (net_tap_fd_init(vlan, fd))
4839 ret = 0;
4840 } else {
4841 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4842 ifname[0] = '\0';
4844 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4845 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4847 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4848 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4850 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4852 } else
4853 #endif
4854 if (!strcmp(device, "socket")) {
4855 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4856 int fd;
4857 fd = strtol(buf, NULL, 0);
4858 ret = -1;
4859 if (net_socket_fd_init(vlan, fd, 1))
4860 ret = 0;
4861 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4862 ret = net_socket_listen_init(vlan, buf);
4863 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4864 ret = net_socket_connect_init(vlan, buf);
4865 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4866 ret = net_socket_mcast_init(vlan, buf);
4867 } else {
4868 fprintf(stderr, "Unknown socket options: %s\n", p);
4869 return -1;
4871 vlan->nb_host_devs++;
4872 } else
4874 fprintf(stderr, "Unknown network device: %s\n", device);
4875 return -1;
4877 if (ret < 0) {
4878 fprintf(stderr, "Could not initialize device '%s'\n", device);
4881 return ret;
4884 void do_info_network(void)
4886 VLANState *vlan;
4887 VLANClientState *vc;
4889 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4890 term_printf("VLAN %d devices:\n", vlan->id);
4891 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4892 term_printf(" %s\n", vc->info_str);
4896 #define HD_ALIAS "index=%d,media=disk"
4897 #ifdef TARGET_PPC
4898 #define CDROM_ALIAS "index=1,media=cdrom"
4899 #else
4900 #define CDROM_ALIAS "index=2,media=cdrom"
4901 #endif
4902 #define FD_ALIAS "index=%d,if=floppy"
4903 #define PFLASH_ALIAS "if=pflash"
4904 #define MTD_ALIAS "if=mtd"
4905 #define SD_ALIAS "index=0,if=sd"
4907 static int drive_add(const char *file, const char *fmt, ...)
4909 va_list ap;
4911 if (nb_drives_opt >= MAX_DRIVES) {
4912 fprintf(stderr, "qemu: too many drives\n");
4913 exit(1);
4916 drives_opt[nb_drives_opt].file = file;
4917 va_start(ap, fmt);
4918 vsnprintf(drives_opt[nb_drives_opt].opt,
4919 sizeof(drives_opt[0].opt), fmt, ap);
4920 va_end(ap);
4922 return nb_drives_opt++;
4925 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4927 int index;
4929 /* seek interface, bus and unit */
4931 for (index = 0; index < nb_drives; index++)
4932 if (drives_table[index].type == type &&
4933 drives_table[index].bus == bus &&
4934 drives_table[index].unit == unit)
4935 return index;
4937 return -1;
4940 int drive_get_max_bus(BlockInterfaceType type)
4942 int max_bus;
4943 int index;
4945 max_bus = -1;
4946 for (index = 0; index < nb_drives; index++) {
4947 if(drives_table[index].type == type &&
4948 drives_table[index].bus > max_bus)
4949 max_bus = drives_table[index].bus;
4951 return max_bus;
4954 static int drive_init(struct drive_opt *arg, int snapshot,
4955 QEMUMachine *machine)
4957 char buf[128];
4958 char file[1024];
4959 char devname[128];
4960 const char *mediastr = "";
4961 BlockInterfaceType type;
4962 enum { MEDIA_DISK, MEDIA_CDROM } media;
4963 int bus_id, unit_id;
4964 int cyls, heads, secs, translation;
4965 BlockDriverState *bdrv;
4966 int max_devs;
4967 int index;
4968 int cache;
4969 int bdrv_flags;
4970 char *str = arg->opt;
4971 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4972 "secs", "trans", "media", "snapshot", "file",
4973 "cache", NULL };
4975 if (check_params(buf, sizeof(buf), params, str) < 0) {
4976 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
4977 buf, str);
4978 return -1;
4981 file[0] = 0;
4982 cyls = heads = secs = 0;
4983 bus_id = 0;
4984 unit_id = -1;
4985 translation = BIOS_ATA_TRANSLATION_AUTO;
4986 index = -1;
4987 cache = 1;
4989 if (!strcmp(machine->name, "realview") ||
4990 !strcmp(machine->name, "SS-5") ||
4991 !strcmp(machine->name, "SS-10") ||
4992 !strcmp(machine->name, "SS-600MP") ||
4993 !strcmp(machine->name, "versatilepb") ||
4994 !strcmp(machine->name, "versatileab")) {
4995 type = IF_SCSI;
4996 max_devs = MAX_SCSI_DEVS;
4997 strcpy(devname, "scsi");
4998 } else {
4999 type = IF_IDE;
5000 max_devs = MAX_IDE_DEVS;
5001 strcpy(devname, "ide");
5003 media = MEDIA_DISK;
5005 /* extract parameters */
5007 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5008 bus_id = strtol(buf, NULL, 0);
5009 if (bus_id < 0) {
5010 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5011 return -1;
5015 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5016 unit_id = strtol(buf, NULL, 0);
5017 if (unit_id < 0) {
5018 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5019 return -1;
5023 if (get_param_value(buf, sizeof(buf), "if", str)) {
5024 strncpy(devname, buf, sizeof(devname));
5025 if (!strcmp(buf, "ide")) {
5026 type = IF_IDE;
5027 max_devs = MAX_IDE_DEVS;
5028 } else if (!strcmp(buf, "scsi")) {
5029 type = IF_SCSI;
5030 max_devs = MAX_SCSI_DEVS;
5031 } else if (!strcmp(buf, "floppy")) {
5032 type = IF_FLOPPY;
5033 max_devs = 0;
5034 } else if (!strcmp(buf, "pflash")) {
5035 type = IF_PFLASH;
5036 max_devs = 0;
5037 } else if (!strcmp(buf, "mtd")) {
5038 type = IF_MTD;
5039 max_devs = 0;
5040 } else if (!strcmp(buf, "sd")) {
5041 type = IF_SD;
5042 max_devs = 0;
5043 } else {
5044 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5045 return -1;
5049 if (get_param_value(buf, sizeof(buf), "index", str)) {
5050 index = strtol(buf, NULL, 0);
5051 if (index < 0) {
5052 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5053 return -1;
5057 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5058 cyls = strtol(buf, NULL, 0);
5061 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5062 heads = strtol(buf, NULL, 0);
5065 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5066 secs = strtol(buf, NULL, 0);
5069 if (cyls || heads || secs) {
5070 if (cyls < 1 || cyls > 16383) {
5071 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5072 return -1;
5074 if (heads < 1 || heads > 16) {
5075 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5076 return -1;
5078 if (secs < 1 || secs > 63) {
5079 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5080 return -1;
5084 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5085 if (!cyls) {
5086 fprintf(stderr,
5087 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5088 str);
5089 return -1;
5091 if (!strcmp(buf, "none"))
5092 translation = BIOS_ATA_TRANSLATION_NONE;
5093 else if (!strcmp(buf, "lba"))
5094 translation = BIOS_ATA_TRANSLATION_LBA;
5095 else if (!strcmp(buf, "auto"))
5096 translation = BIOS_ATA_TRANSLATION_AUTO;
5097 else {
5098 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5099 return -1;
5103 if (get_param_value(buf, sizeof(buf), "media", str)) {
5104 if (!strcmp(buf, "disk")) {
5105 media = MEDIA_DISK;
5106 } else if (!strcmp(buf, "cdrom")) {
5107 if (cyls || secs || heads) {
5108 fprintf(stderr,
5109 "qemu: '%s' invalid physical CHS format\n", str);
5110 return -1;
5112 media = MEDIA_CDROM;
5113 } else {
5114 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5115 return -1;
5119 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5120 if (!strcmp(buf, "on"))
5121 snapshot = 1;
5122 else if (!strcmp(buf, "off"))
5123 snapshot = 0;
5124 else {
5125 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5126 return -1;
5130 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5131 if (!strcmp(buf, "off"))
5132 cache = 0;
5133 else if (!strcmp(buf, "on"))
5134 cache = 1;
5135 else {
5136 fprintf(stderr, "qemu: invalid cache option\n");
5137 return -1;
5141 if (arg->file == NULL)
5142 get_param_value(file, sizeof(file), "file", str);
5143 else
5144 pstrcpy(file, sizeof(file), arg->file);
5146 /* compute bus and unit according index */
5148 if (index != -1) {
5149 if (bus_id != 0 || unit_id != -1) {
5150 fprintf(stderr,
5151 "qemu: '%s' index cannot be used with bus and unit\n", str);
5152 return -1;
5154 if (max_devs == 0)
5156 unit_id = index;
5157 bus_id = 0;
5158 } else {
5159 unit_id = index % max_devs;
5160 bus_id = index / max_devs;
5164 /* if user doesn't specify a unit_id,
5165 * try to find the first free
5168 if (unit_id == -1) {
5169 unit_id = 0;
5170 while (drive_get_index(type, bus_id, unit_id) != -1) {
5171 unit_id++;
5172 if (max_devs && unit_id >= max_devs) {
5173 unit_id -= max_devs;
5174 bus_id++;
5179 /* check unit id */
5181 if (max_devs && unit_id >= max_devs) {
5182 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5183 str, unit_id, max_devs - 1);
5184 return -1;
5188 * ignore multiple definitions
5191 if (drive_get_index(type, bus_id, unit_id) != -1)
5192 return 0;
5194 /* init */
5196 if (type == IF_IDE || type == IF_SCSI)
5197 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5198 if (max_devs)
5199 snprintf(buf, sizeof(buf), "%s%i%s%i",
5200 devname, bus_id, mediastr, unit_id);
5201 else
5202 snprintf(buf, sizeof(buf), "%s%s%i",
5203 devname, mediastr, unit_id);
5204 bdrv = bdrv_new(buf);
5205 drives_table[nb_drives].bdrv = bdrv;
5206 drives_table[nb_drives].type = type;
5207 drives_table[nb_drives].bus = bus_id;
5208 drives_table[nb_drives].unit = unit_id;
5209 nb_drives++;
5211 switch(type) {
5212 case IF_IDE:
5213 case IF_SCSI:
5214 switch(media) {
5215 case MEDIA_DISK:
5216 if (cyls != 0) {
5217 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5218 bdrv_set_translation_hint(bdrv, translation);
5220 break;
5221 case MEDIA_CDROM:
5222 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5223 break;
5225 break;
5226 case IF_SD:
5227 /* FIXME: This isn't really a floppy, but it's a reasonable
5228 approximation. */
5229 case IF_FLOPPY:
5230 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5231 break;
5232 case IF_PFLASH:
5233 case IF_MTD:
5234 break;
5236 if (!file[0])
5237 return 0;
5238 bdrv_flags = 0;
5239 if (snapshot)
5240 bdrv_flags |= BDRV_O_SNAPSHOT;
5241 if (!cache)
5242 bdrv_flags |= BDRV_O_DIRECT;
5243 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5244 fprintf(stderr, "qemu: could not open disk image %s\n",
5245 file);
5246 return -1;
5248 return 0;
5251 /***********************************************************/
5252 /* USB devices */
5254 static USBPort *used_usb_ports;
5255 static USBPort *free_usb_ports;
5257 /* ??? Maybe change this to register a hub to keep track of the topology. */
5258 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5259 usb_attachfn attach)
5261 port->opaque = opaque;
5262 port->index = index;
5263 port->attach = attach;
5264 port->next = free_usb_ports;
5265 free_usb_ports = port;
5268 static int usb_device_add(const char *devname)
5270 const char *p;
5271 USBDevice *dev;
5272 USBPort *port;
5274 if (!free_usb_ports)
5275 return -1;
5277 if (strstart(devname, "host:", &p)) {
5278 dev = usb_host_device_open(p);
5279 } else if (!strcmp(devname, "mouse")) {
5280 dev = usb_mouse_init();
5281 } else if (!strcmp(devname, "tablet")) {
5282 dev = usb_tablet_init();
5283 } else if (!strcmp(devname, "keyboard")) {
5284 dev = usb_keyboard_init();
5285 } else if (strstart(devname, "disk:", &p)) {
5286 dev = usb_msd_init(p);
5287 } else if (!strcmp(devname, "wacom-tablet")) {
5288 dev = usb_wacom_init();
5289 } else if (strstart(devname, "serial:", &p)) {
5290 dev = usb_serial_init(p);
5291 #ifdef CONFIG_BRLAPI
5292 } else if (!strcmp(devname, "braille")) {
5293 dev = usb_baum_init();
5294 #endif
5295 } else {
5296 return -1;
5298 if (!dev)
5299 return -1;
5301 /* Find a USB port to add the device to. */
5302 port = free_usb_ports;
5303 if (!port->next) {
5304 USBDevice *hub;
5306 /* Create a new hub and chain it on. */
5307 free_usb_ports = NULL;
5308 port->next = used_usb_ports;
5309 used_usb_ports = port;
5311 hub = usb_hub_init(VM_USB_HUB_SIZE);
5312 usb_attach(port, hub);
5313 port = free_usb_ports;
5316 free_usb_ports = port->next;
5317 port->next = used_usb_ports;
5318 used_usb_ports = port;
5319 usb_attach(port, dev);
5320 return 0;
5323 static int usb_device_del(const char *devname)
5325 USBPort *port;
5326 USBPort **lastp;
5327 USBDevice *dev;
5328 int bus_num, addr;
5329 const char *p;
5331 if (!used_usb_ports)
5332 return -1;
5334 p = strchr(devname, '.');
5335 if (!p)
5336 return -1;
5337 bus_num = strtoul(devname, NULL, 0);
5338 addr = strtoul(p + 1, NULL, 0);
5339 if (bus_num != 0)
5340 return -1;
5342 lastp = &used_usb_ports;
5343 port = used_usb_ports;
5344 while (port && port->dev->addr != addr) {
5345 lastp = &port->next;
5346 port = port->next;
5349 if (!port)
5350 return -1;
5352 dev = port->dev;
5353 *lastp = port->next;
5354 usb_attach(port, NULL);
5355 dev->handle_destroy(dev);
5356 port->next = free_usb_ports;
5357 free_usb_ports = port;
5358 return 0;
5361 void do_usb_add(const char *devname)
5363 int ret;
5364 ret = usb_device_add(devname);
5365 if (ret < 0)
5366 term_printf("Could not add USB device '%s'\n", devname);
5369 void do_usb_del(const char *devname)
5371 int ret;
5372 ret = usb_device_del(devname);
5373 if (ret < 0)
5374 term_printf("Could not remove USB device '%s'\n", devname);
5377 void usb_info(void)
5379 USBDevice *dev;
5380 USBPort *port;
5381 const char *speed_str;
5383 if (!usb_enabled) {
5384 term_printf("USB support not enabled\n");
5385 return;
5388 for (port = used_usb_ports; port; port = port->next) {
5389 dev = port->dev;
5390 if (!dev)
5391 continue;
5392 switch(dev->speed) {
5393 case USB_SPEED_LOW:
5394 speed_str = "1.5";
5395 break;
5396 case USB_SPEED_FULL:
5397 speed_str = "12";
5398 break;
5399 case USB_SPEED_HIGH:
5400 speed_str = "480";
5401 break;
5402 default:
5403 speed_str = "?";
5404 break;
5406 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5407 0, dev->addr, speed_str, dev->devname);
5411 /***********************************************************/
5412 /* PCMCIA/Cardbus */
5414 static struct pcmcia_socket_entry_s {
5415 struct pcmcia_socket_s *socket;
5416 struct pcmcia_socket_entry_s *next;
5417 } *pcmcia_sockets = 0;
5419 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5421 struct pcmcia_socket_entry_s *entry;
5423 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5424 entry->socket = socket;
5425 entry->next = pcmcia_sockets;
5426 pcmcia_sockets = entry;
5429 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5431 struct pcmcia_socket_entry_s *entry, **ptr;
5433 ptr = &pcmcia_sockets;
5434 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5435 if (entry->socket == socket) {
5436 *ptr = entry->next;
5437 qemu_free(entry);
5441 void pcmcia_info(void)
5443 struct pcmcia_socket_entry_s *iter;
5444 if (!pcmcia_sockets)
5445 term_printf("No PCMCIA sockets\n");
5447 for (iter = pcmcia_sockets; iter; iter = iter->next)
5448 term_printf("%s: %s\n", iter->socket->slot_string,
5449 iter->socket->attached ? iter->socket->card_string :
5450 "Empty");
5453 /***********************************************************/
5454 /* dumb display */
5456 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5460 static void dumb_resize(DisplayState *ds, int w, int h)
5464 static void dumb_refresh(DisplayState *ds)
5466 #if defined(CONFIG_SDL)
5467 vga_hw_update();
5468 #endif
5471 static void dumb_display_init(DisplayState *ds)
5473 ds->data = NULL;
5474 ds->linesize = 0;
5475 ds->depth = 0;
5476 ds->dpy_update = dumb_update;
5477 ds->dpy_resize = dumb_resize;
5478 ds->dpy_refresh = dumb_refresh;
5481 /***********************************************************/
5482 /* I/O handling */
5484 #define MAX_IO_HANDLERS 64
5486 typedef struct IOHandlerRecord {
5487 int fd;
5488 IOCanRWHandler *fd_read_poll;
5489 IOHandler *fd_read;
5490 IOHandler *fd_write;
5491 int deleted;
5492 void *opaque;
5493 /* temporary data */
5494 struct pollfd *ufd;
5495 struct IOHandlerRecord *next;
5496 } IOHandlerRecord;
5498 static IOHandlerRecord *first_io_handler;
5500 /* XXX: fd_read_poll should be suppressed, but an API change is
5501 necessary in the character devices to suppress fd_can_read(). */
5502 int qemu_set_fd_handler2(int fd,
5503 IOCanRWHandler *fd_read_poll,
5504 IOHandler *fd_read,
5505 IOHandler *fd_write,
5506 void *opaque)
5508 IOHandlerRecord **pioh, *ioh;
5510 if (!fd_read && !fd_write) {
5511 pioh = &first_io_handler;
5512 for(;;) {
5513 ioh = *pioh;
5514 if (ioh == NULL)
5515 break;
5516 if (ioh->fd == fd) {
5517 ioh->deleted = 1;
5518 break;
5520 pioh = &ioh->next;
5522 } else {
5523 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5524 if (ioh->fd == fd)
5525 goto found;
5527 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5528 if (!ioh)
5529 return -1;
5530 ioh->next = first_io_handler;
5531 first_io_handler = ioh;
5532 found:
5533 ioh->fd = fd;
5534 ioh->fd_read_poll = fd_read_poll;
5535 ioh->fd_read = fd_read;
5536 ioh->fd_write = fd_write;
5537 ioh->opaque = opaque;
5538 ioh->deleted = 0;
5540 return 0;
5543 int qemu_set_fd_handler(int fd,
5544 IOHandler *fd_read,
5545 IOHandler *fd_write,
5546 void *opaque)
5548 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5551 /***********************************************************/
5552 /* Polling handling */
5554 typedef struct PollingEntry {
5555 PollingFunc *func;
5556 void *opaque;
5557 struct PollingEntry *next;
5558 } PollingEntry;
5560 static PollingEntry *first_polling_entry;
5562 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5564 PollingEntry **ppe, *pe;
5565 pe = qemu_mallocz(sizeof(PollingEntry));
5566 if (!pe)
5567 return -1;
5568 pe->func = func;
5569 pe->opaque = opaque;
5570 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5571 *ppe = pe;
5572 return 0;
5575 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5577 PollingEntry **ppe, *pe;
5578 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5579 pe = *ppe;
5580 if (pe->func == func && pe->opaque == opaque) {
5581 *ppe = pe->next;
5582 qemu_free(pe);
5583 break;
5588 #ifdef _WIN32
5589 /***********************************************************/
5590 /* Wait objects support */
5591 typedef struct WaitObjects {
5592 int num;
5593 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5594 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5595 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5596 } WaitObjects;
5598 static WaitObjects wait_objects = {0};
5600 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5602 WaitObjects *w = &wait_objects;
5604 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5605 return -1;
5606 w->events[w->num] = handle;
5607 w->func[w->num] = func;
5608 w->opaque[w->num] = opaque;
5609 w->num++;
5610 return 0;
5613 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5615 int i, found;
5616 WaitObjects *w = &wait_objects;
5618 found = 0;
5619 for (i = 0; i < w->num; i++) {
5620 if (w->events[i] == handle)
5621 found = 1;
5622 if (found) {
5623 w->events[i] = w->events[i + 1];
5624 w->func[i] = w->func[i + 1];
5625 w->opaque[i] = w->opaque[i + 1];
5628 if (found)
5629 w->num--;
5631 #endif
5633 /***********************************************************/
5634 /* savevm/loadvm support */
5636 #define IO_BUF_SIZE 32768
5638 struct QEMUFile {
5639 FILE *outfile;
5640 BlockDriverState *bs;
5641 int is_file;
5642 int is_writable;
5643 int64_t base_offset;
5644 int64_t buf_offset; /* start of buffer when writing, end of buffer
5645 when reading */
5646 int buf_index;
5647 int buf_size; /* 0 when writing */
5648 uint8_t buf[IO_BUF_SIZE];
5651 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5653 QEMUFile *f;
5655 f = qemu_mallocz(sizeof(QEMUFile));
5656 if (!f)
5657 return NULL;
5658 if (!strcmp(mode, "wb")) {
5659 f->is_writable = 1;
5660 } else if (!strcmp(mode, "rb")) {
5661 f->is_writable = 0;
5662 } else {
5663 goto fail;
5665 f->outfile = fopen(filename, mode);
5666 if (!f->outfile)
5667 goto fail;
5668 f->is_file = 1;
5669 return f;
5670 fail:
5671 if (f->outfile)
5672 fclose(f->outfile);
5673 qemu_free(f);
5674 return NULL;
5677 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5679 QEMUFile *f;
5681 f = qemu_mallocz(sizeof(QEMUFile));
5682 if (!f)
5683 return NULL;
5684 f->is_file = 0;
5685 f->bs = bs;
5686 f->is_writable = is_writable;
5687 f->base_offset = offset;
5688 return f;
5691 void qemu_fflush(QEMUFile *f)
5693 if (!f->is_writable)
5694 return;
5695 if (f->buf_index > 0) {
5696 if (f->is_file) {
5697 fseek(f->outfile, f->buf_offset, SEEK_SET);
5698 fwrite(f->buf, 1, f->buf_index, f->outfile);
5699 } else {
5700 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5701 f->buf, f->buf_index);
5703 f->buf_offset += f->buf_index;
5704 f->buf_index = 0;
5708 static void qemu_fill_buffer(QEMUFile *f)
5710 int len;
5712 if (f->is_writable)
5713 return;
5714 if (f->is_file) {
5715 fseek(f->outfile, f->buf_offset, SEEK_SET);
5716 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5717 if (len < 0)
5718 len = 0;
5719 } else {
5720 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5721 f->buf, IO_BUF_SIZE);
5722 if (len < 0)
5723 len = 0;
5725 f->buf_index = 0;
5726 f->buf_size = len;
5727 f->buf_offset += len;
5730 void qemu_fclose(QEMUFile *f)
5732 if (f->is_writable)
5733 qemu_fflush(f);
5734 if (f->is_file) {
5735 fclose(f->outfile);
5737 qemu_free(f);
5740 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5742 int l;
5743 while (size > 0) {
5744 l = IO_BUF_SIZE - f->buf_index;
5745 if (l > size)
5746 l = size;
5747 memcpy(f->buf + f->buf_index, buf, l);
5748 f->buf_index += l;
5749 buf += l;
5750 size -= l;
5751 if (f->buf_index >= IO_BUF_SIZE)
5752 qemu_fflush(f);
5756 void qemu_put_byte(QEMUFile *f, int v)
5758 f->buf[f->buf_index++] = v;
5759 if (f->buf_index >= IO_BUF_SIZE)
5760 qemu_fflush(f);
5763 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5765 int size, l;
5767 size = size1;
5768 while (size > 0) {
5769 l = f->buf_size - f->buf_index;
5770 if (l == 0) {
5771 qemu_fill_buffer(f);
5772 l = f->buf_size - f->buf_index;
5773 if (l == 0)
5774 break;
5776 if (l > size)
5777 l = size;
5778 memcpy(buf, f->buf + f->buf_index, l);
5779 f->buf_index += l;
5780 buf += l;
5781 size -= l;
5783 return size1 - size;
5786 int qemu_get_byte(QEMUFile *f)
5788 if (f->buf_index >= f->buf_size) {
5789 qemu_fill_buffer(f);
5790 if (f->buf_index >= f->buf_size)
5791 return 0;
5793 return f->buf[f->buf_index++];
5796 int64_t qemu_ftell(QEMUFile *f)
5798 return f->buf_offset - f->buf_size + f->buf_index;
5801 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5803 if (whence == SEEK_SET) {
5804 /* nothing to do */
5805 } else if (whence == SEEK_CUR) {
5806 pos += qemu_ftell(f);
5807 } else {
5808 /* SEEK_END not supported */
5809 return -1;
5811 if (f->is_writable) {
5812 qemu_fflush(f);
5813 f->buf_offset = pos;
5814 } else {
5815 f->buf_offset = pos;
5816 f->buf_index = 0;
5817 f->buf_size = 0;
5819 return pos;
5822 void qemu_put_be16(QEMUFile *f, unsigned int v)
5824 qemu_put_byte(f, v >> 8);
5825 qemu_put_byte(f, v);
5828 void qemu_put_be32(QEMUFile *f, unsigned int v)
5830 qemu_put_byte(f, v >> 24);
5831 qemu_put_byte(f, v >> 16);
5832 qemu_put_byte(f, v >> 8);
5833 qemu_put_byte(f, v);
5836 void qemu_put_be64(QEMUFile *f, uint64_t v)
5838 qemu_put_be32(f, v >> 32);
5839 qemu_put_be32(f, v);
5842 unsigned int qemu_get_be16(QEMUFile *f)
5844 unsigned int v;
5845 v = qemu_get_byte(f) << 8;
5846 v |= qemu_get_byte(f);
5847 return v;
5850 unsigned int qemu_get_be32(QEMUFile *f)
5852 unsigned int v;
5853 v = qemu_get_byte(f) << 24;
5854 v |= qemu_get_byte(f) << 16;
5855 v |= qemu_get_byte(f) << 8;
5856 v |= qemu_get_byte(f);
5857 return v;
5860 uint64_t qemu_get_be64(QEMUFile *f)
5862 uint64_t v;
5863 v = (uint64_t)qemu_get_be32(f) << 32;
5864 v |= qemu_get_be32(f);
5865 return v;
5868 typedef struct SaveStateEntry {
5869 char idstr[256];
5870 int instance_id;
5871 int version_id;
5872 SaveStateHandler *save_state;
5873 LoadStateHandler *load_state;
5874 void *opaque;
5875 struct SaveStateEntry *next;
5876 } SaveStateEntry;
5878 static SaveStateEntry *first_se;
5880 int register_savevm(const char *idstr,
5881 int instance_id,
5882 int version_id,
5883 SaveStateHandler *save_state,
5884 LoadStateHandler *load_state,
5885 void *opaque)
5887 SaveStateEntry *se, **pse;
5889 se = qemu_malloc(sizeof(SaveStateEntry));
5890 if (!se)
5891 return -1;
5892 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5893 se->instance_id = instance_id;
5894 se->version_id = version_id;
5895 se->save_state = save_state;
5896 se->load_state = load_state;
5897 se->opaque = opaque;
5898 se->next = NULL;
5900 /* add at the end of list */
5901 pse = &first_se;
5902 while (*pse != NULL)
5903 pse = &(*pse)->next;
5904 *pse = se;
5905 return 0;
5908 #define QEMU_VM_FILE_MAGIC 0x5145564d
5909 #define QEMU_VM_FILE_VERSION 0x00000002
5911 static int qemu_savevm_state(QEMUFile *f)
5913 SaveStateEntry *se;
5914 int len, ret;
5915 int64_t cur_pos, len_pos, total_len_pos;
5917 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5918 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5919 total_len_pos = qemu_ftell(f);
5920 qemu_put_be64(f, 0); /* total size */
5922 for(se = first_se; se != NULL; se = se->next) {
5923 /* ID string */
5924 len = strlen(se->idstr);
5925 qemu_put_byte(f, len);
5926 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5928 qemu_put_be32(f, se->instance_id);
5929 qemu_put_be32(f, se->version_id);
5931 /* record size: filled later */
5932 len_pos = qemu_ftell(f);
5933 qemu_put_be32(f, 0);
5934 se->save_state(f, se->opaque);
5936 /* fill record size */
5937 cur_pos = qemu_ftell(f);
5938 len = cur_pos - len_pos - 4;
5939 qemu_fseek(f, len_pos, SEEK_SET);
5940 qemu_put_be32(f, len);
5941 qemu_fseek(f, cur_pos, SEEK_SET);
5943 cur_pos = qemu_ftell(f);
5944 qemu_fseek(f, total_len_pos, SEEK_SET);
5945 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5946 qemu_fseek(f, cur_pos, SEEK_SET);
5948 ret = 0;
5949 return ret;
5952 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5954 SaveStateEntry *se;
5956 for(se = first_se; se != NULL; se = se->next) {
5957 if (!strcmp(se->idstr, idstr) &&
5958 instance_id == se->instance_id)
5959 return se;
5961 return NULL;
5964 static int qemu_loadvm_state(QEMUFile *f)
5966 SaveStateEntry *se;
5967 int len, ret, instance_id, record_len, version_id;
5968 int64_t total_len, end_pos, cur_pos;
5969 unsigned int v;
5970 char idstr[256];
5972 v = qemu_get_be32(f);
5973 if (v != QEMU_VM_FILE_MAGIC)
5974 goto fail;
5975 v = qemu_get_be32(f);
5976 if (v != QEMU_VM_FILE_VERSION) {
5977 fail:
5978 ret = -1;
5979 goto the_end;
5981 total_len = qemu_get_be64(f);
5982 end_pos = total_len + qemu_ftell(f);
5983 for(;;) {
5984 if (qemu_ftell(f) >= end_pos)
5985 break;
5986 len = qemu_get_byte(f);
5987 qemu_get_buffer(f, (uint8_t *)idstr, len);
5988 idstr[len] = '\0';
5989 instance_id = qemu_get_be32(f);
5990 version_id = qemu_get_be32(f);
5991 record_len = qemu_get_be32(f);
5992 #if 0
5993 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5994 idstr, instance_id, version_id, record_len);
5995 #endif
5996 cur_pos = qemu_ftell(f);
5997 se = find_se(idstr, instance_id);
5998 if (!se) {
5999 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6000 instance_id, idstr);
6001 } else {
6002 ret = se->load_state(f, se->opaque, version_id);
6003 if (ret < 0) {
6004 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6005 instance_id, idstr);
6008 /* always seek to exact end of record */
6009 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6011 ret = 0;
6012 the_end:
6013 return ret;
6016 /* device can contain snapshots */
6017 static int bdrv_can_snapshot(BlockDriverState *bs)
6019 return (bs &&
6020 !bdrv_is_removable(bs) &&
6021 !bdrv_is_read_only(bs));
6024 /* device must be snapshots in order to have a reliable snapshot */
6025 static int bdrv_has_snapshot(BlockDriverState *bs)
6027 return (bs &&
6028 !bdrv_is_removable(bs) &&
6029 !bdrv_is_read_only(bs));
6032 static BlockDriverState *get_bs_snapshots(void)
6034 BlockDriverState *bs;
6035 int i;
6037 if (bs_snapshots)
6038 return bs_snapshots;
6039 for(i = 0; i <= nb_drives; i++) {
6040 bs = drives_table[i].bdrv;
6041 if (bdrv_can_snapshot(bs))
6042 goto ok;
6044 return NULL;
6046 bs_snapshots = bs;
6047 return bs;
6050 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6051 const char *name)
6053 QEMUSnapshotInfo *sn_tab, *sn;
6054 int nb_sns, i, ret;
6056 ret = -ENOENT;
6057 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6058 if (nb_sns < 0)
6059 return ret;
6060 for(i = 0; i < nb_sns; i++) {
6061 sn = &sn_tab[i];
6062 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6063 *sn_info = *sn;
6064 ret = 0;
6065 break;
6068 qemu_free(sn_tab);
6069 return ret;
6072 void do_savevm(const char *name)
6074 BlockDriverState *bs, *bs1;
6075 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6076 int must_delete, ret, i;
6077 BlockDriverInfo bdi1, *bdi = &bdi1;
6078 QEMUFile *f;
6079 int saved_vm_running;
6080 #ifdef _WIN32
6081 struct _timeb tb;
6082 #else
6083 struct timeval tv;
6084 #endif
6086 bs = get_bs_snapshots();
6087 if (!bs) {
6088 term_printf("No block device can accept snapshots\n");
6089 return;
6092 /* ??? Should this occur after vm_stop? */
6093 qemu_aio_flush();
6095 saved_vm_running = vm_running;
6096 vm_stop(0);
6098 must_delete = 0;
6099 if (name) {
6100 ret = bdrv_snapshot_find(bs, old_sn, name);
6101 if (ret >= 0) {
6102 must_delete = 1;
6105 memset(sn, 0, sizeof(*sn));
6106 if (must_delete) {
6107 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6108 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6109 } else {
6110 if (name)
6111 pstrcpy(sn->name, sizeof(sn->name), name);
6114 /* fill auxiliary fields */
6115 #ifdef _WIN32
6116 _ftime(&tb);
6117 sn->date_sec = tb.time;
6118 sn->date_nsec = tb.millitm * 1000000;
6119 #else
6120 gettimeofday(&tv, NULL);
6121 sn->date_sec = tv.tv_sec;
6122 sn->date_nsec = tv.tv_usec * 1000;
6123 #endif
6124 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6126 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6127 term_printf("Device %s does not support VM state snapshots\n",
6128 bdrv_get_device_name(bs));
6129 goto the_end;
6132 /* save the VM state */
6133 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6134 if (!f) {
6135 term_printf("Could not open VM state file\n");
6136 goto the_end;
6138 ret = qemu_savevm_state(f);
6139 sn->vm_state_size = qemu_ftell(f);
6140 qemu_fclose(f);
6141 if (ret < 0) {
6142 term_printf("Error %d while writing VM\n", ret);
6143 goto the_end;
6146 /* create the snapshots */
6148 for(i = 0; i < nb_drives; i++) {
6149 bs1 = drives_table[i].bdrv;
6150 if (bdrv_has_snapshot(bs1)) {
6151 if (must_delete) {
6152 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6153 if (ret < 0) {
6154 term_printf("Error while deleting snapshot on '%s'\n",
6155 bdrv_get_device_name(bs1));
6158 ret = bdrv_snapshot_create(bs1, sn);
6159 if (ret < 0) {
6160 term_printf("Error while creating snapshot on '%s'\n",
6161 bdrv_get_device_name(bs1));
6166 the_end:
6167 if (saved_vm_running)
6168 vm_start();
6171 void do_loadvm(const char *name)
6173 BlockDriverState *bs, *bs1;
6174 BlockDriverInfo bdi1, *bdi = &bdi1;
6175 QEMUFile *f;
6176 int i, ret;
6177 int saved_vm_running;
6179 bs = get_bs_snapshots();
6180 if (!bs) {
6181 term_printf("No block device supports snapshots\n");
6182 return;
6185 /* Flush all IO requests so they don't interfere with the new state. */
6186 qemu_aio_flush();
6188 saved_vm_running = vm_running;
6189 vm_stop(0);
6191 for(i = 0; i <= nb_drives; i++) {
6192 bs1 = drives_table[i].bdrv;
6193 if (bdrv_has_snapshot(bs1)) {
6194 ret = bdrv_snapshot_goto(bs1, name);
6195 if (ret < 0) {
6196 if (bs != bs1)
6197 term_printf("Warning: ");
6198 switch(ret) {
6199 case -ENOTSUP:
6200 term_printf("Snapshots not supported on device '%s'\n",
6201 bdrv_get_device_name(bs1));
6202 break;
6203 case -ENOENT:
6204 term_printf("Could not find snapshot '%s' on device '%s'\n",
6205 name, bdrv_get_device_name(bs1));
6206 break;
6207 default:
6208 term_printf("Error %d while activating snapshot on '%s'\n",
6209 ret, bdrv_get_device_name(bs1));
6210 break;
6212 /* fatal on snapshot block device */
6213 if (bs == bs1)
6214 goto the_end;
6219 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6220 term_printf("Device %s does not support VM state snapshots\n",
6221 bdrv_get_device_name(bs));
6222 return;
6225 /* restore the VM state */
6226 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6227 if (!f) {
6228 term_printf("Could not open VM state file\n");
6229 goto the_end;
6231 ret = qemu_loadvm_state(f);
6232 qemu_fclose(f);
6233 if (ret < 0) {
6234 term_printf("Error %d while loading VM state\n", ret);
6236 the_end:
6237 if (saved_vm_running)
6238 vm_start();
6241 void do_delvm(const char *name)
6243 BlockDriverState *bs, *bs1;
6244 int i, ret;
6246 bs = get_bs_snapshots();
6247 if (!bs) {
6248 term_printf("No block device supports snapshots\n");
6249 return;
6252 for(i = 0; i <= nb_drives; i++) {
6253 bs1 = drives_table[i].bdrv;
6254 if (bdrv_has_snapshot(bs1)) {
6255 ret = bdrv_snapshot_delete(bs1, name);
6256 if (ret < 0) {
6257 if (ret == -ENOTSUP)
6258 term_printf("Snapshots not supported on device '%s'\n",
6259 bdrv_get_device_name(bs1));
6260 else
6261 term_printf("Error %d while deleting snapshot on '%s'\n",
6262 ret, bdrv_get_device_name(bs1));
6268 void do_info_snapshots(void)
6270 BlockDriverState *bs, *bs1;
6271 QEMUSnapshotInfo *sn_tab, *sn;
6272 int nb_sns, i;
6273 char buf[256];
6275 bs = get_bs_snapshots();
6276 if (!bs) {
6277 term_printf("No available block device supports snapshots\n");
6278 return;
6280 term_printf("Snapshot devices:");
6281 for(i = 0; i <= nb_drives; i++) {
6282 bs1 = drives_table[i].bdrv;
6283 if (bdrv_has_snapshot(bs1)) {
6284 if (bs == bs1)
6285 term_printf(" %s", bdrv_get_device_name(bs1));
6288 term_printf("\n");
6290 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6291 if (nb_sns < 0) {
6292 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6293 return;
6295 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6296 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6297 for(i = 0; i < nb_sns; i++) {
6298 sn = &sn_tab[i];
6299 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6301 qemu_free(sn_tab);
6304 /***********************************************************/
6305 /* cpu save/restore */
6307 #if defined(TARGET_I386)
6309 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6311 qemu_put_be32(f, dt->selector);
6312 qemu_put_betl(f, dt->base);
6313 qemu_put_be32(f, dt->limit);
6314 qemu_put_be32(f, dt->flags);
6317 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6319 dt->selector = qemu_get_be32(f);
6320 dt->base = qemu_get_betl(f);
6321 dt->limit = qemu_get_be32(f);
6322 dt->flags = qemu_get_be32(f);
6325 void cpu_save(QEMUFile *f, void *opaque)
6327 CPUState *env = opaque;
6328 uint16_t fptag, fpus, fpuc, fpregs_format;
6329 uint32_t hflags;
6330 int i;
6332 for(i = 0; i < CPU_NB_REGS; i++)
6333 qemu_put_betls(f, &env->regs[i]);
6334 qemu_put_betls(f, &env->eip);
6335 qemu_put_betls(f, &env->eflags);
6336 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6337 qemu_put_be32s(f, &hflags);
6339 /* FPU */
6340 fpuc = env->fpuc;
6341 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6342 fptag = 0;
6343 for(i = 0; i < 8; i++) {
6344 fptag |= ((!env->fptags[i]) << i);
6347 qemu_put_be16s(f, &fpuc);
6348 qemu_put_be16s(f, &fpus);
6349 qemu_put_be16s(f, &fptag);
6351 #ifdef USE_X86LDOUBLE
6352 fpregs_format = 0;
6353 #else
6354 fpregs_format = 1;
6355 #endif
6356 qemu_put_be16s(f, &fpregs_format);
6358 for(i = 0; i < 8; i++) {
6359 #ifdef USE_X86LDOUBLE
6361 uint64_t mant;
6362 uint16_t exp;
6363 /* we save the real CPU data (in case of MMX usage only 'mant'
6364 contains the MMX register */
6365 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6366 qemu_put_be64(f, mant);
6367 qemu_put_be16(f, exp);
6369 #else
6370 /* if we use doubles for float emulation, we save the doubles to
6371 avoid losing information in case of MMX usage. It can give
6372 problems if the image is restored on a CPU where long
6373 doubles are used instead. */
6374 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6375 #endif
6378 for(i = 0; i < 6; i++)
6379 cpu_put_seg(f, &env->segs[i]);
6380 cpu_put_seg(f, &env->ldt);
6381 cpu_put_seg(f, &env->tr);
6382 cpu_put_seg(f, &env->gdt);
6383 cpu_put_seg(f, &env->idt);
6385 qemu_put_be32s(f, &env->sysenter_cs);
6386 qemu_put_be32s(f, &env->sysenter_esp);
6387 qemu_put_be32s(f, &env->sysenter_eip);
6389 qemu_put_betls(f, &env->cr[0]);
6390 qemu_put_betls(f, &env->cr[2]);
6391 qemu_put_betls(f, &env->cr[3]);
6392 qemu_put_betls(f, &env->cr[4]);
6394 for(i = 0; i < 8; i++)
6395 qemu_put_betls(f, &env->dr[i]);
6397 /* MMU */
6398 qemu_put_be32s(f, &env->a20_mask);
6400 /* XMM */
6401 qemu_put_be32s(f, &env->mxcsr);
6402 for(i = 0; i < CPU_NB_REGS; i++) {
6403 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6404 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6407 #ifdef TARGET_X86_64
6408 qemu_put_be64s(f, &env->efer);
6409 qemu_put_be64s(f, &env->star);
6410 qemu_put_be64s(f, &env->lstar);
6411 qemu_put_be64s(f, &env->cstar);
6412 qemu_put_be64s(f, &env->fmask);
6413 qemu_put_be64s(f, &env->kernelgsbase);
6414 #endif
6415 qemu_put_be32s(f, &env->smbase);
6418 #ifdef USE_X86LDOUBLE
6419 /* XXX: add that in a FPU generic layer */
6420 union x86_longdouble {
6421 uint64_t mant;
6422 uint16_t exp;
6425 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6426 #define EXPBIAS1 1023
6427 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6428 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6430 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6432 int e;
6433 /* mantissa */
6434 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6435 /* exponent + sign */
6436 e = EXPD1(temp) - EXPBIAS1 + 16383;
6437 e |= SIGND1(temp) >> 16;
6438 p->exp = e;
6440 #endif
6442 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6444 CPUState *env = opaque;
6445 int i, guess_mmx;
6446 uint32_t hflags;
6447 uint16_t fpus, fpuc, fptag, fpregs_format;
6449 if (version_id != 3 && version_id != 4)
6450 return -EINVAL;
6451 for(i = 0; i < CPU_NB_REGS; i++)
6452 qemu_get_betls(f, &env->regs[i]);
6453 qemu_get_betls(f, &env->eip);
6454 qemu_get_betls(f, &env->eflags);
6455 qemu_get_be32s(f, &hflags);
6457 qemu_get_be16s(f, &fpuc);
6458 qemu_get_be16s(f, &fpus);
6459 qemu_get_be16s(f, &fptag);
6460 qemu_get_be16s(f, &fpregs_format);
6462 /* NOTE: we cannot always restore the FPU state if the image come
6463 from a host with a different 'USE_X86LDOUBLE' define. We guess
6464 if we are in an MMX state to restore correctly in that case. */
6465 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6466 for(i = 0; i < 8; i++) {
6467 uint64_t mant;
6468 uint16_t exp;
6470 switch(fpregs_format) {
6471 case 0:
6472 mant = qemu_get_be64(f);
6473 exp = qemu_get_be16(f);
6474 #ifdef USE_X86LDOUBLE
6475 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6476 #else
6477 /* difficult case */
6478 if (guess_mmx)
6479 env->fpregs[i].mmx.MMX_Q(0) = mant;
6480 else
6481 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6482 #endif
6483 break;
6484 case 1:
6485 mant = qemu_get_be64(f);
6486 #ifdef USE_X86LDOUBLE
6488 union x86_longdouble *p;
6489 /* difficult case */
6490 p = (void *)&env->fpregs[i];
6491 if (guess_mmx) {
6492 p->mant = mant;
6493 p->exp = 0xffff;
6494 } else {
6495 fp64_to_fp80(p, mant);
6498 #else
6499 env->fpregs[i].mmx.MMX_Q(0) = mant;
6500 #endif
6501 break;
6502 default:
6503 return -EINVAL;
6507 env->fpuc = fpuc;
6508 /* XXX: restore FPU round state */
6509 env->fpstt = (fpus >> 11) & 7;
6510 env->fpus = fpus & ~0x3800;
6511 fptag ^= 0xff;
6512 for(i = 0; i < 8; i++) {
6513 env->fptags[i] = (fptag >> i) & 1;
6516 for(i = 0; i < 6; i++)
6517 cpu_get_seg(f, &env->segs[i]);
6518 cpu_get_seg(f, &env->ldt);
6519 cpu_get_seg(f, &env->tr);
6520 cpu_get_seg(f, &env->gdt);
6521 cpu_get_seg(f, &env->idt);
6523 qemu_get_be32s(f, &env->sysenter_cs);
6524 qemu_get_be32s(f, &env->sysenter_esp);
6525 qemu_get_be32s(f, &env->sysenter_eip);
6527 qemu_get_betls(f, &env->cr[0]);
6528 qemu_get_betls(f, &env->cr[2]);
6529 qemu_get_betls(f, &env->cr[3]);
6530 qemu_get_betls(f, &env->cr[4]);
6532 for(i = 0; i < 8; i++)
6533 qemu_get_betls(f, &env->dr[i]);
6535 /* MMU */
6536 qemu_get_be32s(f, &env->a20_mask);
6538 qemu_get_be32s(f, &env->mxcsr);
6539 for(i = 0; i < CPU_NB_REGS; i++) {
6540 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6541 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6544 #ifdef TARGET_X86_64
6545 qemu_get_be64s(f, &env->efer);
6546 qemu_get_be64s(f, &env->star);
6547 qemu_get_be64s(f, &env->lstar);
6548 qemu_get_be64s(f, &env->cstar);
6549 qemu_get_be64s(f, &env->fmask);
6550 qemu_get_be64s(f, &env->kernelgsbase);
6551 #endif
6552 if (version_id >= 4)
6553 qemu_get_be32s(f, &env->smbase);
6555 /* XXX: compute hflags from scratch, except for CPL and IIF */
6556 env->hflags = hflags;
6557 tlb_flush(env, 1);
6558 return 0;
6561 #elif defined(TARGET_PPC)
6562 void cpu_save(QEMUFile *f, void *opaque)
6566 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6568 return 0;
6571 #elif defined(TARGET_MIPS)
6572 void cpu_save(QEMUFile *f, void *opaque)
6576 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6578 return 0;
6581 #elif defined(TARGET_SPARC)
6582 void cpu_save(QEMUFile *f, void *opaque)
6584 CPUState *env = opaque;
6585 int i;
6586 uint32_t tmp;
6588 for(i = 0; i < 8; i++)
6589 qemu_put_betls(f, &env->gregs[i]);
6590 for(i = 0; i < NWINDOWS * 16; i++)
6591 qemu_put_betls(f, &env->regbase[i]);
6593 /* FPU */
6594 for(i = 0; i < TARGET_FPREGS; i++) {
6595 union {
6596 float32 f;
6597 uint32_t i;
6598 } u;
6599 u.f = env->fpr[i];
6600 qemu_put_be32(f, u.i);
6603 qemu_put_betls(f, &env->pc);
6604 qemu_put_betls(f, &env->npc);
6605 qemu_put_betls(f, &env->y);
6606 tmp = GET_PSR(env);
6607 qemu_put_be32(f, tmp);
6608 qemu_put_betls(f, &env->fsr);
6609 qemu_put_betls(f, &env->tbr);
6610 #ifndef TARGET_SPARC64
6611 qemu_put_be32s(f, &env->wim);
6612 /* MMU */
6613 for(i = 0; i < 16; i++)
6614 qemu_put_be32s(f, &env->mmuregs[i]);
6615 #endif
6618 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6620 CPUState *env = opaque;
6621 int i;
6622 uint32_t tmp;
6624 for(i = 0; i < 8; i++)
6625 qemu_get_betls(f, &env->gregs[i]);
6626 for(i = 0; i < NWINDOWS * 16; i++)
6627 qemu_get_betls(f, &env->regbase[i]);
6629 /* FPU */
6630 for(i = 0; i < TARGET_FPREGS; i++) {
6631 union {
6632 float32 f;
6633 uint32_t i;
6634 } u;
6635 u.i = qemu_get_be32(f);
6636 env->fpr[i] = u.f;
6639 qemu_get_betls(f, &env->pc);
6640 qemu_get_betls(f, &env->npc);
6641 qemu_get_betls(f, &env->y);
6642 tmp = qemu_get_be32(f);
6643 env->cwp = 0; /* needed to ensure that the wrapping registers are
6644 correctly updated */
6645 PUT_PSR(env, tmp);
6646 qemu_get_betls(f, &env->fsr);
6647 qemu_get_betls(f, &env->tbr);
6648 #ifndef TARGET_SPARC64
6649 qemu_get_be32s(f, &env->wim);
6650 /* MMU */
6651 for(i = 0; i < 16; i++)
6652 qemu_get_be32s(f, &env->mmuregs[i]);
6653 #endif
6654 tlb_flush(env, 1);
6655 return 0;
6658 #elif defined(TARGET_ARM)
6660 void cpu_save(QEMUFile *f, void *opaque)
6662 int i;
6663 CPUARMState *env = (CPUARMState *)opaque;
6665 for (i = 0; i < 16; i++) {
6666 qemu_put_be32(f, env->regs[i]);
6668 qemu_put_be32(f, cpsr_read(env));
6669 qemu_put_be32(f, env->spsr);
6670 for (i = 0; i < 6; i++) {
6671 qemu_put_be32(f, env->banked_spsr[i]);
6672 qemu_put_be32(f, env->banked_r13[i]);
6673 qemu_put_be32(f, env->banked_r14[i]);
6675 for (i = 0; i < 5; i++) {
6676 qemu_put_be32(f, env->usr_regs[i]);
6677 qemu_put_be32(f, env->fiq_regs[i]);
6679 qemu_put_be32(f, env->cp15.c0_cpuid);
6680 qemu_put_be32(f, env->cp15.c0_cachetype);
6681 qemu_put_be32(f, env->cp15.c1_sys);
6682 qemu_put_be32(f, env->cp15.c1_coproc);
6683 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6684 qemu_put_be32(f, env->cp15.c2_base0);
6685 qemu_put_be32(f, env->cp15.c2_base1);
6686 qemu_put_be32(f, env->cp15.c2_mask);
6687 qemu_put_be32(f, env->cp15.c2_data);
6688 qemu_put_be32(f, env->cp15.c2_insn);
6689 qemu_put_be32(f, env->cp15.c3);
6690 qemu_put_be32(f, env->cp15.c5_insn);
6691 qemu_put_be32(f, env->cp15.c5_data);
6692 for (i = 0; i < 8; i++) {
6693 qemu_put_be32(f, env->cp15.c6_region[i]);
6695 qemu_put_be32(f, env->cp15.c6_insn);
6696 qemu_put_be32(f, env->cp15.c6_data);
6697 qemu_put_be32(f, env->cp15.c9_insn);
6698 qemu_put_be32(f, env->cp15.c9_data);
6699 qemu_put_be32(f, env->cp15.c13_fcse);
6700 qemu_put_be32(f, env->cp15.c13_context);
6701 qemu_put_be32(f, env->cp15.c13_tls1);
6702 qemu_put_be32(f, env->cp15.c13_tls2);
6703 qemu_put_be32(f, env->cp15.c13_tls3);
6704 qemu_put_be32(f, env->cp15.c15_cpar);
6706 qemu_put_be32(f, env->features);
6708 if (arm_feature(env, ARM_FEATURE_VFP)) {
6709 for (i = 0; i < 16; i++) {
6710 CPU_DoubleU u;
6711 u.d = env->vfp.regs[i];
6712 qemu_put_be32(f, u.l.upper);
6713 qemu_put_be32(f, u.l.lower);
6715 for (i = 0; i < 16; i++) {
6716 qemu_put_be32(f, env->vfp.xregs[i]);
6719 /* TODO: Should use proper FPSCR access functions. */
6720 qemu_put_be32(f, env->vfp.vec_len);
6721 qemu_put_be32(f, env->vfp.vec_stride);
6723 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6724 for (i = 16; i < 32; i++) {
6725 CPU_DoubleU u;
6726 u.d = env->vfp.regs[i];
6727 qemu_put_be32(f, u.l.upper);
6728 qemu_put_be32(f, u.l.lower);
6733 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6734 for (i = 0; i < 16; i++) {
6735 qemu_put_be64(f, env->iwmmxt.regs[i]);
6737 for (i = 0; i < 16; i++) {
6738 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6742 if (arm_feature(env, ARM_FEATURE_M)) {
6743 qemu_put_be32(f, env->v7m.other_sp);
6744 qemu_put_be32(f, env->v7m.vecbase);
6745 qemu_put_be32(f, env->v7m.basepri);
6746 qemu_put_be32(f, env->v7m.control);
6747 qemu_put_be32(f, env->v7m.current_sp);
6748 qemu_put_be32(f, env->v7m.exception);
6752 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6754 CPUARMState *env = (CPUARMState *)opaque;
6755 int i;
6757 if (version_id != ARM_CPU_SAVE_VERSION)
6758 return -EINVAL;
6760 for (i = 0; i < 16; i++) {
6761 env->regs[i] = qemu_get_be32(f);
6763 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6764 env->spsr = qemu_get_be32(f);
6765 for (i = 0; i < 6; i++) {
6766 env->banked_spsr[i] = qemu_get_be32(f);
6767 env->banked_r13[i] = qemu_get_be32(f);
6768 env->banked_r14[i] = qemu_get_be32(f);
6770 for (i = 0; i < 5; i++) {
6771 env->usr_regs[i] = qemu_get_be32(f);
6772 env->fiq_regs[i] = qemu_get_be32(f);
6774 env->cp15.c0_cpuid = qemu_get_be32(f);
6775 env->cp15.c0_cachetype = qemu_get_be32(f);
6776 env->cp15.c1_sys = qemu_get_be32(f);
6777 env->cp15.c1_coproc = qemu_get_be32(f);
6778 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6779 env->cp15.c2_base0 = qemu_get_be32(f);
6780 env->cp15.c2_base1 = qemu_get_be32(f);
6781 env->cp15.c2_mask = qemu_get_be32(f);
6782 env->cp15.c2_data = qemu_get_be32(f);
6783 env->cp15.c2_insn = qemu_get_be32(f);
6784 env->cp15.c3 = qemu_get_be32(f);
6785 env->cp15.c5_insn = qemu_get_be32(f);
6786 env->cp15.c5_data = qemu_get_be32(f);
6787 for (i = 0; i < 8; i++) {
6788 env->cp15.c6_region[i] = qemu_get_be32(f);
6790 env->cp15.c6_insn = qemu_get_be32(f);
6791 env->cp15.c6_data = qemu_get_be32(f);
6792 env->cp15.c9_insn = qemu_get_be32(f);
6793 env->cp15.c9_data = qemu_get_be32(f);
6794 env->cp15.c13_fcse = qemu_get_be32(f);
6795 env->cp15.c13_context = qemu_get_be32(f);
6796 env->cp15.c13_tls1 = qemu_get_be32(f);
6797 env->cp15.c13_tls2 = qemu_get_be32(f);
6798 env->cp15.c13_tls3 = qemu_get_be32(f);
6799 env->cp15.c15_cpar = qemu_get_be32(f);
6801 env->features = qemu_get_be32(f);
6803 if (arm_feature(env, ARM_FEATURE_VFP)) {
6804 for (i = 0; i < 16; i++) {
6805 CPU_DoubleU u;
6806 u.l.upper = qemu_get_be32(f);
6807 u.l.lower = qemu_get_be32(f);
6808 env->vfp.regs[i] = u.d;
6810 for (i = 0; i < 16; i++) {
6811 env->vfp.xregs[i] = qemu_get_be32(f);
6814 /* TODO: Should use proper FPSCR access functions. */
6815 env->vfp.vec_len = qemu_get_be32(f);
6816 env->vfp.vec_stride = qemu_get_be32(f);
6818 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6819 for (i = 0; i < 16; i++) {
6820 CPU_DoubleU u;
6821 u.l.upper = qemu_get_be32(f);
6822 u.l.lower = qemu_get_be32(f);
6823 env->vfp.regs[i] = u.d;
6828 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6829 for (i = 0; i < 16; i++) {
6830 env->iwmmxt.regs[i] = qemu_get_be64(f);
6832 for (i = 0; i < 16; i++) {
6833 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6837 if (arm_feature(env, ARM_FEATURE_M)) {
6838 env->v7m.other_sp = qemu_get_be32(f);
6839 env->v7m.vecbase = qemu_get_be32(f);
6840 env->v7m.basepri = qemu_get_be32(f);
6841 env->v7m.control = qemu_get_be32(f);
6842 env->v7m.current_sp = qemu_get_be32(f);
6843 env->v7m.exception = qemu_get_be32(f);
6846 return 0;
6849 #else
6851 //#warning No CPU save/restore functions
6853 #endif
6855 /***********************************************************/
6856 /* ram save/restore */
6858 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6860 int v;
6862 v = qemu_get_byte(f);
6863 switch(v) {
6864 case 0:
6865 if (qemu_get_buffer(f, buf, len) != len)
6866 return -EIO;
6867 break;
6868 case 1:
6869 v = qemu_get_byte(f);
6870 memset(buf, v, len);
6871 break;
6872 default:
6873 return -EINVAL;
6875 return 0;
6878 static int ram_load_v1(QEMUFile *f, void *opaque)
6880 int i, ret;
6882 if (qemu_get_be32(f) != phys_ram_size)
6883 return -EINVAL;
6884 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6885 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6886 if (ret)
6887 return ret;
6889 return 0;
6892 #define BDRV_HASH_BLOCK_SIZE 1024
6893 #define IOBUF_SIZE 4096
6894 #define RAM_CBLOCK_MAGIC 0xfabe
6896 typedef struct RamCompressState {
6897 z_stream zstream;
6898 QEMUFile *f;
6899 uint8_t buf[IOBUF_SIZE];
6900 } RamCompressState;
6902 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6904 int ret;
6905 memset(s, 0, sizeof(*s));
6906 s->f = f;
6907 ret = deflateInit2(&s->zstream, 1,
6908 Z_DEFLATED, 15,
6909 9, Z_DEFAULT_STRATEGY);
6910 if (ret != Z_OK)
6911 return -1;
6912 s->zstream.avail_out = IOBUF_SIZE;
6913 s->zstream.next_out = s->buf;
6914 return 0;
6917 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6919 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6920 qemu_put_be16(s->f, len);
6921 qemu_put_buffer(s->f, buf, len);
6924 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6926 int ret;
6928 s->zstream.avail_in = len;
6929 s->zstream.next_in = (uint8_t *)buf;
6930 while (s->zstream.avail_in > 0) {
6931 ret = deflate(&s->zstream, Z_NO_FLUSH);
6932 if (ret != Z_OK)
6933 return -1;
6934 if (s->zstream.avail_out == 0) {
6935 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6936 s->zstream.avail_out = IOBUF_SIZE;
6937 s->zstream.next_out = s->buf;
6940 return 0;
6943 static void ram_compress_close(RamCompressState *s)
6945 int len, ret;
6947 /* compress last bytes */
6948 for(;;) {
6949 ret = deflate(&s->zstream, Z_FINISH);
6950 if (ret == Z_OK || ret == Z_STREAM_END) {
6951 len = IOBUF_SIZE - s->zstream.avail_out;
6952 if (len > 0) {
6953 ram_put_cblock(s, s->buf, len);
6955 s->zstream.avail_out = IOBUF_SIZE;
6956 s->zstream.next_out = s->buf;
6957 if (ret == Z_STREAM_END)
6958 break;
6959 } else {
6960 goto fail;
6963 fail:
6964 deflateEnd(&s->zstream);
6967 typedef struct RamDecompressState {
6968 z_stream zstream;
6969 QEMUFile *f;
6970 uint8_t buf[IOBUF_SIZE];
6971 } RamDecompressState;
6973 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6975 int ret;
6976 memset(s, 0, sizeof(*s));
6977 s->f = f;
6978 ret = inflateInit(&s->zstream);
6979 if (ret != Z_OK)
6980 return -1;
6981 return 0;
6984 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6986 int ret, clen;
6988 s->zstream.avail_out = len;
6989 s->zstream.next_out = buf;
6990 while (s->zstream.avail_out > 0) {
6991 if (s->zstream.avail_in == 0) {
6992 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6993 return -1;
6994 clen = qemu_get_be16(s->f);
6995 if (clen > IOBUF_SIZE)
6996 return -1;
6997 qemu_get_buffer(s->f, s->buf, clen);
6998 s->zstream.avail_in = clen;
6999 s->zstream.next_in = s->buf;
7001 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7002 if (ret != Z_OK && ret != Z_STREAM_END) {
7003 return -1;
7006 return 0;
7009 static void ram_decompress_close(RamDecompressState *s)
7011 inflateEnd(&s->zstream);
7014 static void ram_save(QEMUFile *f, void *opaque)
7016 int i;
7017 RamCompressState s1, *s = &s1;
7018 uint8_t buf[10];
7020 qemu_put_be32(f, phys_ram_size);
7021 if (ram_compress_open(s, f) < 0)
7022 return;
7023 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7024 #if 0
7025 if (tight_savevm_enabled) {
7026 int64_t sector_num;
7027 int j;
7029 /* find if the memory block is available on a virtual
7030 block device */
7031 sector_num = -1;
7032 for(j = 0; j < nb_drives; j++) {
7033 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7034 phys_ram_base + i,
7035 BDRV_HASH_BLOCK_SIZE);
7036 if (sector_num >= 0)
7037 break;
7039 if (j == nb_drives)
7040 goto normal_compress;
7041 buf[0] = 1;
7042 buf[1] = j;
7043 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7044 ram_compress_buf(s, buf, 10);
7045 } else
7046 #endif
7048 // normal_compress:
7049 buf[0] = 0;
7050 ram_compress_buf(s, buf, 1);
7051 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7054 ram_compress_close(s);
7057 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7059 RamDecompressState s1, *s = &s1;
7060 uint8_t buf[10];
7061 int i;
7063 if (version_id == 1)
7064 return ram_load_v1(f, opaque);
7065 if (version_id != 2)
7066 return -EINVAL;
7067 if (qemu_get_be32(f) != phys_ram_size)
7068 return -EINVAL;
7069 if (ram_decompress_open(s, f) < 0)
7070 return -EINVAL;
7071 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7072 if (ram_decompress_buf(s, buf, 1) < 0) {
7073 fprintf(stderr, "Error while reading ram block header\n");
7074 goto error;
7076 if (buf[0] == 0) {
7077 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7078 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7079 goto error;
7081 } else
7082 #if 0
7083 if (buf[0] == 1) {
7084 int bs_index;
7085 int64_t sector_num;
7087 ram_decompress_buf(s, buf + 1, 9);
7088 bs_index = buf[1];
7089 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7090 if (bs_index >= nb_drives) {
7091 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7092 goto error;
7094 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7095 phys_ram_base + i,
7096 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7097 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7098 bs_index, sector_num);
7099 goto error;
7101 } else
7102 #endif
7104 error:
7105 printf("Error block header\n");
7106 return -EINVAL;
7109 ram_decompress_close(s);
7110 return 0;
7113 /***********************************************************/
7114 /* bottom halves (can be seen as timers which expire ASAP) */
7116 struct QEMUBH {
7117 QEMUBHFunc *cb;
7118 void *opaque;
7119 int scheduled;
7120 QEMUBH *next;
7123 static QEMUBH *first_bh = NULL;
7125 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7127 QEMUBH *bh;
7128 bh = qemu_mallocz(sizeof(QEMUBH));
7129 if (!bh)
7130 return NULL;
7131 bh->cb = cb;
7132 bh->opaque = opaque;
7133 return bh;
7136 int qemu_bh_poll(void)
7138 QEMUBH *bh, **pbh;
7139 int ret;
7141 ret = 0;
7142 for(;;) {
7143 pbh = &first_bh;
7144 bh = *pbh;
7145 if (!bh)
7146 break;
7147 ret = 1;
7148 *pbh = bh->next;
7149 bh->scheduled = 0;
7150 bh->cb(bh->opaque);
7152 return ret;
7155 void qemu_bh_schedule(QEMUBH *bh)
7157 CPUState *env = cpu_single_env;
7158 if (bh->scheduled)
7159 return;
7160 bh->scheduled = 1;
7161 bh->next = first_bh;
7162 first_bh = bh;
7164 /* stop the currently executing CPU to execute the BH ASAP */
7165 if (env) {
7166 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7170 void qemu_bh_cancel(QEMUBH *bh)
7172 QEMUBH **pbh;
7173 if (bh->scheduled) {
7174 pbh = &first_bh;
7175 while (*pbh != bh)
7176 pbh = &(*pbh)->next;
7177 *pbh = bh->next;
7178 bh->scheduled = 0;
7182 void qemu_bh_delete(QEMUBH *bh)
7184 qemu_bh_cancel(bh);
7185 qemu_free(bh);
7188 /***********************************************************/
7189 /* machine registration */
7191 QEMUMachine *first_machine = NULL;
7193 int qemu_register_machine(QEMUMachine *m)
7195 QEMUMachine **pm;
7196 pm = &first_machine;
7197 while (*pm != NULL)
7198 pm = &(*pm)->next;
7199 m->next = NULL;
7200 *pm = m;
7201 return 0;
7204 static QEMUMachine *find_machine(const char *name)
7206 QEMUMachine *m;
7208 for(m = first_machine; m != NULL; m = m->next) {
7209 if (!strcmp(m->name, name))
7210 return m;
7212 return NULL;
7215 /***********************************************************/
7216 /* main execution loop */
7218 static void gui_update(void *opaque)
7220 DisplayState *ds = opaque;
7221 ds->dpy_refresh(ds);
7222 qemu_mod_timer(ds->gui_timer,
7223 (ds->gui_timer_interval ?
7224 ds->gui_timer_interval :
7225 GUI_REFRESH_INTERVAL)
7226 + qemu_get_clock(rt_clock));
7229 struct vm_change_state_entry {
7230 VMChangeStateHandler *cb;
7231 void *opaque;
7232 LIST_ENTRY (vm_change_state_entry) entries;
7235 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7237 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7238 void *opaque)
7240 VMChangeStateEntry *e;
7242 e = qemu_mallocz(sizeof (*e));
7243 if (!e)
7244 return NULL;
7246 e->cb = cb;
7247 e->opaque = opaque;
7248 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7249 return e;
7252 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7254 LIST_REMOVE (e, entries);
7255 qemu_free (e);
7258 static void vm_state_notify(int running)
7260 VMChangeStateEntry *e;
7262 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7263 e->cb(e->opaque, running);
7267 /* XXX: support several handlers */
7268 static VMStopHandler *vm_stop_cb;
7269 static void *vm_stop_opaque;
7271 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7273 vm_stop_cb = cb;
7274 vm_stop_opaque = opaque;
7275 return 0;
7278 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7280 vm_stop_cb = NULL;
7283 void vm_start(void)
7285 if (!vm_running) {
7286 cpu_enable_ticks();
7287 vm_running = 1;
7288 vm_state_notify(1);
7289 qemu_rearm_alarm_timer(alarm_timer);
7293 void vm_stop(int reason)
7295 if (vm_running) {
7296 cpu_disable_ticks();
7297 vm_running = 0;
7298 if (reason != 0) {
7299 if (vm_stop_cb) {
7300 vm_stop_cb(vm_stop_opaque, reason);
7303 vm_state_notify(0);
7307 /* reset/shutdown handler */
7309 typedef struct QEMUResetEntry {
7310 QEMUResetHandler *func;
7311 void *opaque;
7312 struct QEMUResetEntry *next;
7313 } QEMUResetEntry;
7315 static QEMUResetEntry *first_reset_entry;
7316 static int reset_requested;
7317 static int shutdown_requested;
7318 static int powerdown_requested;
7320 int qemu_shutdown_requested(void)
7322 int r = shutdown_requested;
7323 shutdown_requested = 0;
7324 return r;
7327 int qemu_reset_requested(void)
7329 int r = reset_requested;
7330 reset_requested = 0;
7331 return r;
7334 int qemu_powerdown_requested(void)
7336 int r = powerdown_requested;
7337 powerdown_requested = 0;
7338 return r;
7341 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7343 QEMUResetEntry **pre, *re;
7345 pre = &first_reset_entry;
7346 while (*pre != NULL)
7347 pre = &(*pre)->next;
7348 re = qemu_mallocz(sizeof(QEMUResetEntry));
7349 re->func = func;
7350 re->opaque = opaque;
7351 re->next = NULL;
7352 *pre = re;
7355 void qemu_system_reset(void)
7357 QEMUResetEntry *re;
7359 /* reset all devices */
7360 for(re = first_reset_entry; re != NULL; re = re->next) {
7361 re->func(re->opaque);
7365 void qemu_system_reset_request(void)
7367 if (no_reboot) {
7368 shutdown_requested = 1;
7369 } else {
7370 reset_requested = 1;
7372 if (cpu_single_env)
7373 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7376 void qemu_system_shutdown_request(void)
7378 shutdown_requested = 1;
7379 if (cpu_single_env)
7380 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7383 void qemu_system_powerdown_request(void)
7385 powerdown_requested = 1;
7386 if (cpu_single_env)
7387 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7390 void main_loop_wait(int timeout)
7392 IOHandlerRecord *ioh;
7393 fd_set rfds, wfds, xfds;
7394 int ret, nfds;
7395 #ifdef _WIN32
7396 int ret2, i;
7397 #endif
7398 struct timeval tv;
7399 PollingEntry *pe;
7402 /* XXX: need to suppress polling by better using win32 events */
7403 ret = 0;
7404 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7405 ret |= pe->func(pe->opaque);
7407 #ifdef _WIN32
7408 if (ret == 0) {
7409 int err;
7410 WaitObjects *w = &wait_objects;
7412 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7413 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7414 if (w->func[ret - WAIT_OBJECT_0])
7415 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7417 /* Check for additional signaled events */
7418 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7420 /* Check if event is signaled */
7421 ret2 = WaitForSingleObject(w->events[i], 0);
7422 if(ret2 == WAIT_OBJECT_0) {
7423 if (w->func[i])
7424 w->func[i](w->opaque[i]);
7425 } else if (ret2 == WAIT_TIMEOUT) {
7426 } else {
7427 err = GetLastError();
7428 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7431 } else if (ret == WAIT_TIMEOUT) {
7432 } else {
7433 err = GetLastError();
7434 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7437 #endif
7438 /* poll any events */
7439 /* XXX: separate device handlers from system ones */
7440 nfds = -1;
7441 FD_ZERO(&rfds);
7442 FD_ZERO(&wfds);
7443 FD_ZERO(&xfds);
7444 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7445 if (ioh->deleted)
7446 continue;
7447 if (ioh->fd_read &&
7448 (!ioh->fd_read_poll ||
7449 ioh->fd_read_poll(ioh->opaque) != 0)) {
7450 FD_SET(ioh->fd, &rfds);
7451 if (ioh->fd > nfds)
7452 nfds = ioh->fd;
7454 if (ioh->fd_write) {
7455 FD_SET(ioh->fd, &wfds);
7456 if (ioh->fd > nfds)
7457 nfds = ioh->fd;
7461 tv.tv_sec = 0;
7462 #ifdef _WIN32
7463 tv.tv_usec = 0;
7464 #else
7465 tv.tv_usec = timeout * 1000;
7466 #endif
7467 #if defined(CONFIG_SLIRP)
7468 if (slirp_inited) {
7469 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7471 #endif
7472 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7473 if (ret > 0) {
7474 IOHandlerRecord **pioh;
7476 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7477 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7478 ioh->fd_read(ioh->opaque);
7480 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7481 ioh->fd_write(ioh->opaque);
7485 /* remove deleted IO handlers */
7486 pioh = &first_io_handler;
7487 while (*pioh) {
7488 ioh = *pioh;
7489 if (ioh->deleted) {
7490 *pioh = ioh->next;
7491 qemu_free(ioh);
7492 } else
7493 pioh = &ioh->next;
7496 #if defined(CONFIG_SLIRP)
7497 if (slirp_inited) {
7498 if (ret < 0) {
7499 FD_ZERO(&rfds);
7500 FD_ZERO(&wfds);
7501 FD_ZERO(&xfds);
7503 slirp_select_poll(&rfds, &wfds, &xfds);
7505 #endif
7506 qemu_aio_poll();
7508 if (vm_running) {
7509 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7510 qemu_get_clock(vm_clock));
7511 /* run dma transfers, if any */
7512 DMA_run();
7515 /* real time timers */
7516 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7517 qemu_get_clock(rt_clock));
7519 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7520 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7521 qemu_rearm_alarm_timer(alarm_timer);
7524 /* Check bottom-halves last in case any of the earlier events triggered
7525 them. */
7526 qemu_bh_poll();
7530 static int main_loop(void)
7532 int ret, timeout;
7533 #ifdef CONFIG_PROFILER
7534 int64_t ti;
7535 #endif
7536 CPUState *env;
7538 cur_cpu = first_cpu;
7539 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7540 for(;;) {
7541 if (vm_running) {
7543 for(;;) {
7544 /* get next cpu */
7545 env = next_cpu;
7546 #ifdef CONFIG_PROFILER
7547 ti = profile_getclock();
7548 #endif
7549 ret = cpu_exec(env);
7550 #ifdef CONFIG_PROFILER
7551 qemu_time += profile_getclock() - ti;
7552 #endif
7553 next_cpu = env->next_cpu ?: first_cpu;
7554 if (event_pending && likely(ret != EXCP_DEBUG)) {
7555 ret = EXCP_INTERRUPT;
7556 event_pending = 0;
7557 break;
7559 if (ret == EXCP_HLT) {
7560 /* Give the next CPU a chance to run. */
7561 cur_cpu = env;
7562 continue;
7564 if (ret != EXCP_HALTED)
7565 break;
7566 /* all CPUs are halted ? */
7567 if (env == cur_cpu)
7568 break;
7570 cur_cpu = env;
7572 if (shutdown_requested) {
7573 ret = EXCP_INTERRUPT;
7574 if (no_shutdown) {
7575 vm_stop(0);
7576 no_shutdown = 0;
7578 else
7579 break;
7581 if (reset_requested) {
7582 reset_requested = 0;
7583 qemu_system_reset();
7584 ret = EXCP_INTERRUPT;
7586 if (powerdown_requested) {
7587 powerdown_requested = 0;
7588 qemu_system_powerdown();
7589 ret = EXCP_INTERRUPT;
7591 if (unlikely(ret == EXCP_DEBUG)) {
7592 vm_stop(EXCP_DEBUG);
7594 /* If all cpus are halted then wait until the next IRQ */
7595 /* XXX: use timeout computed from timers */
7596 if (ret == EXCP_HALTED)
7597 timeout = 10;
7598 else
7599 timeout = 0;
7600 } else {
7601 timeout = 10;
7603 #ifdef CONFIG_PROFILER
7604 ti = profile_getclock();
7605 #endif
7606 main_loop_wait(timeout);
7607 #ifdef CONFIG_PROFILER
7608 dev_time += profile_getclock() - ti;
7609 #endif
7611 cpu_disable_ticks();
7612 return ret;
7615 static void help(int exitcode)
7617 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7618 "usage: %s [options] [disk_image]\n"
7619 "\n"
7620 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7621 "\n"
7622 "Standard options:\n"
7623 "-M machine select emulated machine (-M ? for list)\n"
7624 "-cpu cpu select CPU (-cpu ? for list)\n"
7625 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7626 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7627 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7628 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7629 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7630 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7631 " [,cache=on|off]\n"
7632 " use 'file' as a drive image\n"
7633 "-mtdblock file use 'file' as on-board Flash memory image\n"
7634 "-sd file use 'file' as SecureDigital card image\n"
7635 "-pflash file use 'file' as a parallel flash image\n"
7636 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7637 "-snapshot write to temporary files instead of disk image files\n"
7638 #ifdef CONFIG_SDL
7639 "-no-frame open SDL window without a frame and window decorations\n"
7640 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7641 "-no-quit disable SDL window close capability\n"
7642 #endif
7643 #ifdef TARGET_I386
7644 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7645 #endif
7646 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7647 "-smp n set the number of CPUs to 'n' [default=1]\n"
7648 "-nographic disable graphical output and redirect serial I/Os to console\n"
7649 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7650 #ifndef _WIN32
7651 "-k language use keyboard layout (for example \"fr\" for French)\n"
7652 #endif
7653 #ifdef HAS_AUDIO
7654 "-audio-help print list of audio drivers and their options\n"
7655 "-soundhw c1,... enable audio support\n"
7656 " and only specified sound cards (comma separated list)\n"
7657 " use -soundhw ? to get the list of supported cards\n"
7658 " use -soundhw all to enable all of them\n"
7659 #endif
7660 "-localtime set the real time clock to local time [default=utc]\n"
7661 "-full-screen start in full screen\n"
7662 #ifdef TARGET_I386
7663 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7664 #endif
7665 "-usb enable the USB driver (will be the default soon)\n"
7666 "-usbdevice name add the host or guest USB device 'name'\n"
7667 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7668 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7669 #endif
7670 "-name string set the name of the guest\n"
7671 "\n"
7672 "Network options:\n"
7673 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7674 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7675 #ifdef CONFIG_SLIRP
7676 "-net user[,vlan=n][,hostname=host]\n"
7677 " connect the user mode network stack to VLAN 'n' and send\n"
7678 " hostname 'host' to DHCP clients\n"
7679 #endif
7680 #ifdef _WIN32
7681 "-net tap[,vlan=n],ifname=name\n"
7682 " connect the host TAP network interface to VLAN 'n'\n"
7683 #else
7684 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7685 " connect the host TAP network interface to VLAN 'n' and use the\n"
7686 " network scripts 'file' (default=%s)\n"
7687 " and 'dfile' (default=%s);\n"
7688 " use '[down]script=no' to disable script execution;\n"
7689 " use 'fd=h' to connect to an already opened TAP interface\n"
7690 #endif
7691 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7692 " connect the vlan 'n' to another VLAN using a socket connection\n"
7693 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7694 " connect the vlan 'n' to multicast maddr and port\n"
7695 "-net none use it alone to have zero network devices; if no -net option\n"
7696 " is provided, the default is '-net nic -net user'\n"
7697 "\n"
7698 #ifdef CONFIG_SLIRP
7699 "-tftp dir allow tftp access to files in dir [-net user]\n"
7700 "-bootp file advertise file in BOOTP replies\n"
7701 #ifndef _WIN32
7702 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7703 #endif
7704 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7705 " redirect TCP or UDP connections from host to guest [-net user]\n"
7706 #endif
7707 "\n"
7708 "Linux boot specific:\n"
7709 "-kernel bzImage use 'bzImage' as kernel image\n"
7710 "-append cmdline use 'cmdline' as kernel command line\n"
7711 "-initrd file use 'file' as initial ram disk\n"
7712 "\n"
7713 "Debug/Expert options:\n"
7714 "-monitor dev redirect the monitor to char device 'dev'\n"
7715 "-serial dev redirect the serial port to char device 'dev'\n"
7716 "-parallel dev redirect the parallel port to char device 'dev'\n"
7717 "-pidfile file Write PID to 'file'\n"
7718 "-S freeze CPU at startup (use 'c' to start execution)\n"
7719 "-s wait gdb connection to port\n"
7720 "-p port set gdb connection port [default=%s]\n"
7721 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7722 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7723 " translation (t=none or lba) (usually qemu can guess them)\n"
7724 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7725 #ifdef USE_KQEMU
7726 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7727 "-no-kqemu disable KQEMU kernel module usage\n"
7728 #endif
7729 #ifdef TARGET_I386
7730 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7731 " (default is CL-GD5446 PCI VGA)\n"
7732 "-no-acpi disable ACPI\n"
7733 #endif
7734 #ifdef CONFIG_CURSES
7735 "-curses use a curses/ncurses interface instead of SDL\n"
7736 #endif
7737 "-no-reboot exit instead of rebooting\n"
7738 "-no-shutdown stop before shutdown\n"
7739 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7740 "-vnc display start a VNC server on display\n"
7741 #ifndef _WIN32
7742 "-daemonize daemonize QEMU after initializing\n"
7743 #endif
7744 "-option-rom rom load a file, rom, into the option ROM space\n"
7745 #ifdef TARGET_SPARC
7746 "-prom-env variable=value set OpenBIOS nvram variables\n"
7747 #endif
7748 "-clock force the use of the given methods for timer alarm.\n"
7749 " To see what timers are available use -clock ?\n"
7750 "-startdate select initial date of the clock\n"
7751 "\n"
7752 "During emulation, the following keys are useful:\n"
7753 "ctrl-alt-f toggle full screen\n"
7754 "ctrl-alt-n switch to virtual console 'n'\n"
7755 "ctrl-alt toggle mouse and keyboard grab\n"
7756 "\n"
7757 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7759 "qemu",
7760 DEFAULT_RAM_SIZE,
7761 #ifndef _WIN32
7762 DEFAULT_NETWORK_SCRIPT,
7763 DEFAULT_NETWORK_DOWN_SCRIPT,
7764 #endif
7765 DEFAULT_GDBSTUB_PORT,
7766 "/tmp/qemu.log");
7767 exit(exitcode);
7770 #define HAS_ARG 0x0001
7772 enum {
7773 QEMU_OPTION_h,
7775 QEMU_OPTION_M,
7776 QEMU_OPTION_cpu,
7777 QEMU_OPTION_fda,
7778 QEMU_OPTION_fdb,
7779 QEMU_OPTION_hda,
7780 QEMU_OPTION_hdb,
7781 QEMU_OPTION_hdc,
7782 QEMU_OPTION_hdd,
7783 QEMU_OPTION_drive,
7784 QEMU_OPTION_cdrom,
7785 QEMU_OPTION_mtdblock,
7786 QEMU_OPTION_sd,
7787 QEMU_OPTION_pflash,
7788 QEMU_OPTION_boot,
7789 QEMU_OPTION_snapshot,
7790 #ifdef TARGET_I386
7791 QEMU_OPTION_no_fd_bootchk,
7792 #endif
7793 QEMU_OPTION_m,
7794 QEMU_OPTION_nographic,
7795 QEMU_OPTION_portrait,
7796 #ifdef HAS_AUDIO
7797 QEMU_OPTION_audio_help,
7798 QEMU_OPTION_soundhw,
7799 #endif
7801 QEMU_OPTION_net,
7802 QEMU_OPTION_tftp,
7803 QEMU_OPTION_bootp,
7804 QEMU_OPTION_smb,
7805 QEMU_OPTION_redir,
7807 QEMU_OPTION_kernel,
7808 QEMU_OPTION_append,
7809 QEMU_OPTION_initrd,
7811 QEMU_OPTION_S,
7812 QEMU_OPTION_s,
7813 QEMU_OPTION_p,
7814 QEMU_OPTION_d,
7815 QEMU_OPTION_hdachs,
7816 QEMU_OPTION_L,
7817 QEMU_OPTION_bios,
7818 QEMU_OPTION_no_code_copy,
7819 QEMU_OPTION_k,
7820 QEMU_OPTION_localtime,
7821 QEMU_OPTION_cirrusvga,
7822 QEMU_OPTION_vmsvga,
7823 QEMU_OPTION_g,
7824 QEMU_OPTION_std_vga,
7825 QEMU_OPTION_echr,
7826 QEMU_OPTION_monitor,
7827 QEMU_OPTION_serial,
7828 QEMU_OPTION_parallel,
7829 QEMU_OPTION_loadvm,
7830 QEMU_OPTION_full_screen,
7831 QEMU_OPTION_no_frame,
7832 QEMU_OPTION_alt_grab,
7833 QEMU_OPTION_no_quit,
7834 QEMU_OPTION_pidfile,
7835 QEMU_OPTION_no_kqemu,
7836 QEMU_OPTION_kernel_kqemu,
7837 QEMU_OPTION_win2k_hack,
7838 QEMU_OPTION_usb,
7839 QEMU_OPTION_usbdevice,
7840 QEMU_OPTION_smp,
7841 QEMU_OPTION_vnc,
7842 QEMU_OPTION_no_acpi,
7843 QEMU_OPTION_curses,
7844 QEMU_OPTION_no_reboot,
7845 QEMU_OPTION_no_shutdown,
7846 QEMU_OPTION_show_cursor,
7847 QEMU_OPTION_daemonize,
7848 QEMU_OPTION_option_rom,
7849 QEMU_OPTION_semihosting,
7850 QEMU_OPTION_name,
7851 QEMU_OPTION_prom_env,
7852 QEMU_OPTION_old_param,
7853 QEMU_OPTION_clock,
7854 QEMU_OPTION_startdate,
7857 typedef struct QEMUOption {
7858 const char *name;
7859 int flags;
7860 int index;
7861 } QEMUOption;
7863 const QEMUOption qemu_options[] = {
7864 { "h", 0, QEMU_OPTION_h },
7865 { "help", 0, QEMU_OPTION_h },
7867 { "M", HAS_ARG, QEMU_OPTION_M },
7868 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7869 { "fda", HAS_ARG, QEMU_OPTION_fda },
7870 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7871 { "hda", HAS_ARG, QEMU_OPTION_hda },
7872 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7873 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7874 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7875 { "drive", HAS_ARG, QEMU_OPTION_drive },
7876 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7877 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7878 { "sd", HAS_ARG, QEMU_OPTION_sd },
7879 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7880 { "boot", HAS_ARG, QEMU_OPTION_boot },
7881 { "snapshot", 0, QEMU_OPTION_snapshot },
7882 #ifdef TARGET_I386
7883 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7884 #endif
7885 { "m", HAS_ARG, QEMU_OPTION_m },
7886 { "nographic", 0, QEMU_OPTION_nographic },
7887 { "portrait", 0, QEMU_OPTION_portrait },
7888 { "k", HAS_ARG, QEMU_OPTION_k },
7889 #ifdef HAS_AUDIO
7890 { "audio-help", 0, QEMU_OPTION_audio_help },
7891 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7892 #endif
7894 { "net", HAS_ARG, QEMU_OPTION_net},
7895 #ifdef CONFIG_SLIRP
7896 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7897 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7898 #ifndef _WIN32
7899 { "smb", HAS_ARG, QEMU_OPTION_smb },
7900 #endif
7901 { "redir", HAS_ARG, QEMU_OPTION_redir },
7902 #endif
7904 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7905 { "append", HAS_ARG, QEMU_OPTION_append },
7906 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7908 { "S", 0, QEMU_OPTION_S },
7909 { "s", 0, QEMU_OPTION_s },
7910 { "p", HAS_ARG, QEMU_OPTION_p },
7911 { "d", HAS_ARG, QEMU_OPTION_d },
7912 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7913 { "L", HAS_ARG, QEMU_OPTION_L },
7914 { "bios", HAS_ARG, QEMU_OPTION_bios },
7915 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7916 #ifdef USE_KQEMU
7917 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7918 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7919 #endif
7920 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7921 { "g", 1, QEMU_OPTION_g },
7922 #endif
7923 { "localtime", 0, QEMU_OPTION_localtime },
7924 { "std-vga", 0, QEMU_OPTION_std_vga },
7925 { "echr", HAS_ARG, QEMU_OPTION_echr },
7926 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7927 { "serial", HAS_ARG, QEMU_OPTION_serial },
7928 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7929 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7930 { "full-screen", 0, QEMU_OPTION_full_screen },
7931 #ifdef CONFIG_SDL
7932 { "no-frame", 0, QEMU_OPTION_no_frame },
7933 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7934 { "no-quit", 0, QEMU_OPTION_no_quit },
7935 #endif
7936 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7937 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7938 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7939 { "smp", HAS_ARG, QEMU_OPTION_smp },
7940 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7941 #ifdef CONFIG_CURSES
7942 { "curses", 0, QEMU_OPTION_curses },
7943 #endif
7945 /* temporary options */
7946 { "usb", 0, QEMU_OPTION_usb },
7947 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7948 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7949 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7950 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7951 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7952 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7953 { "daemonize", 0, QEMU_OPTION_daemonize },
7954 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7955 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7956 { "semihosting", 0, QEMU_OPTION_semihosting },
7957 #endif
7958 { "name", HAS_ARG, QEMU_OPTION_name },
7959 #if defined(TARGET_SPARC)
7960 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7961 #endif
7962 #if defined(TARGET_ARM)
7963 { "old-param", 0, QEMU_OPTION_old_param },
7964 #endif
7965 { "clock", HAS_ARG, QEMU_OPTION_clock },
7966 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7967 { NULL },
7970 /* password input */
7972 int qemu_key_check(BlockDriverState *bs, const char *name)
7974 char password[256];
7975 int i;
7977 if (!bdrv_is_encrypted(bs))
7978 return 0;
7980 term_printf("%s is encrypted.\n", name);
7981 for(i = 0; i < 3; i++) {
7982 monitor_readline("Password: ", 1, password, sizeof(password));
7983 if (bdrv_set_key(bs, password) == 0)
7984 return 0;
7985 term_printf("invalid password\n");
7987 return -EPERM;
7990 static BlockDriverState *get_bdrv(int index)
7992 if (index > nb_drives)
7993 return NULL;
7994 return drives_table[index].bdrv;
7997 static void read_passwords(void)
7999 BlockDriverState *bs;
8000 int i;
8002 for(i = 0; i < 6; i++) {
8003 bs = get_bdrv(i);
8004 if (bs)
8005 qemu_key_check(bs, bdrv_get_device_name(bs));
8009 /* XXX: currently we cannot use simultaneously different CPUs */
8010 static void register_machines(void)
8012 #if defined(TARGET_I386)
8013 qemu_register_machine(&pc_machine);
8014 qemu_register_machine(&isapc_machine);
8015 #elif defined(TARGET_PPC)
8016 qemu_register_machine(&heathrow_machine);
8017 qemu_register_machine(&core99_machine);
8018 qemu_register_machine(&prep_machine);
8019 qemu_register_machine(&ref405ep_machine);
8020 qemu_register_machine(&taihu_machine);
8021 #elif defined(TARGET_MIPS)
8022 qemu_register_machine(&mips_machine);
8023 qemu_register_machine(&mips_magnum_machine);
8024 qemu_register_machine(&mips_malta_machine);
8025 qemu_register_machine(&mips_pica61_machine);
8026 qemu_register_machine(&mips_mipssim_machine);
8027 #elif defined(TARGET_SPARC)
8028 #ifdef TARGET_SPARC64
8029 qemu_register_machine(&sun4u_machine);
8030 #else
8031 qemu_register_machine(&ss5_machine);
8032 qemu_register_machine(&ss10_machine);
8033 qemu_register_machine(&ss600mp_machine);
8034 qemu_register_machine(&ss20_machine);
8035 qemu_register_machine(&ss2_machine);
8036 qemu_register_machine(&voyager_machine);
8037 qemu_register_machine(&ss_lx_machine);
8038 qemu_register_machine(&ss4_machine);
8039 qemu_register_machine(&scls_machine);
8040 qemu_register_machine(&sbook_machine);
8041 qemu_register_machine(&ss1000_machine);
8042 qemu_register_machine(&ss2000_machine);
8043 #endif
8044 #elif defined(TARGET_ARM)
8045 qemu_register_machine(&integratorcp_machine);
8046 qemu_register_machine(&versatilepb_machine);
8047 qemu_register_machine(&versatileab_machine);
8048 qemu_register_machine(&realview_machine);
8049 qemu_register_machine(&akitapda_machine);
8050 qemu_register_machine(&spitzpda_machine);
8051 qemu_register_machine(&borzoipda_machine);
8052 qemu_register_machine(&terrierpda_machine);
8053 qemu_register_machine(&palmte_machine);
8054 qemu_register_machine(&n800_machine);
8055 qemu_register_machine(&lm3s811evb_machine);
8056 qemu_register_machine(&lm3s6965evb_machine);
8057 qemu_register_machine(&connex_machine);
8058 qemu_register_machine(&verdex_machine);
8059 qemu_register_machine(&mainstone2_machine);
8060 #elif defined(TARGET_SH4)
8061 qemu_register_machine(&shix_machine);
8062 qemu_register_machine(&r2d_machine);
8063 #elif defined(TARGET_ALPHA)
8064 /* XXX: TODO */
8065 #elif defined(TARGET_M68K)
8066 qemu_register_machine(&mcf5208evb_machine);
8067 qemu_register_machine(&an5206_machine);
8068 qemu_register_machine(&dummy_m68k_machine);
8069 #elif defined(TARGET_CRIS)
8070 qemu_register_machine(&bareetraxfs_machine);
8071 #else
8072 #error unsupported CPU
8073 #endif
8076 #ifdef HAS_AUDIO
8077 struct soundhw soundhw[] = {
8078 #ifdef HAS_AUDIO_CHOICE
8079 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8081 "pcspk",
8082 "PC speaker",
8085 { .init_isa = pcspk_audio_init }
8087 #endif
8089 "sb16",
8090 "Creative Sound Blaster 16",
8093 { .init_isa = SB16_init }
8096 #ifdef CONFIG_ADLIB
8098 "adlib",
8099 #ifdef HAS_YMF262
8100 "Yamaha YMF262 (OPL3)",
8101 #else
8102 "Yamaha YM3812 (OPL2)",
8103 #endif
8106 { .init_isa = Adlib_init }
8108 #endif
8110 #ifdef CONFIG_GUS
8112 "gus",
8113 "Gravis Ultrasound GF1",
8116 { .init_isa = GUS_init }
8118 #endif
8120 #ifdef CONFIG_AC97
8122 "ac97",
8123 "Intel 82801AA AC97 Audio",
8126 { .init_pci = ac97_init }
8128 #endif
8131 "es1370",
8132 "ENSONIQ AudioPCI ES1370",
8135 { .init_pci = es1370_init }
8137 #endif
8139 { NULL, NULL, 0, 0, { NULL } }
8142 static void select_soundhw (const char *optarg)
8144 struct soundhw *c;
8146 if (*optarg == '?') {
8147 show_valid_cards:
8149 printf ("Valid sound card names (comma separated):\n");
8150 for (c = soundhw; c->name; ++c) {
8151 printf ("%-11s %s\n", c->name, c->descr);
8153 printf ("\n-soundhw all will enable all of the above\n");
8154 exit (*optarg != '?');
8156 else {
8157 size_t l;
8158 const char *p;
8159 char *e;
8160 int bad_card = 0;
8162 if (!strcmp (optarg, "all")) {
8163 for (c = soundhw; c->name; ++c) {
8164 c->enabled = 1;
8166 return;
8169 p = optarg;
8170 while (*p) {
8171 e = strchr (p, ',');
8172 l = !e ? strlen (p) : (size_t) (e - p);
8174 for (c = soundhw; c->name; ++c) {
8175 if (!strncmp (c->name, p, l)) {
8176 c->enabled = 1;
8177 break;
8181 if (!c->name) {
8182 if (l > 80) {
8183 fprintf (stderr,
8184 "Unknown sound card name (too big to show)\n");
8186 else {
8187 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8188 (int) l, p);
8190 bad_card = 1;
8192 p += l + (e != NULL);
8195 if (bad_card)
8196 goto show_valid_cards;
8199 #endif
8201 #ifdef _WIN32
8202 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8204 exit(STATUS_CONTROL_C_EXIT);
8205 return TRUE;
8207 #endif
8209 #define MAX_NET_CLIENTS 32
8211 int main(int argc, char **argv)
8213 #ifdef CONFIG_GDBSTUB
8214 int use_gdbstub;
8215 const char *gdbstub_port;
8216 #endif
8217 uint32_t boot_devices_bitmap = 0;
8218 int i;
8219 int snapshot, linux_boot, net_boot;
8220 const char *initrd_filename;
8221 const char *kernel_filename, *kernel_cmdline;
8222 const char *boot_devices = "";
8223 DisplayState *ds = &display_state;
8224 int cyls, heads, secs, translation;
8225 const char *net_clients[MAX_NET_CLIENTS];
8226 int nb_net_clients;
8227 int hda_index;
8228 int optind;
8229 const char *r, *optarg;
8230 CharDriverState *monitor_hd;
8231 const char *monitor_device;
8232 const char *serial_devices[MAX_SERIAL_PORTS];
8233 int serial_device_index;
8234 const char *parallel_devices[MAX_PARALLEL_PORTS];
8235 int parallel_device_index;
8236 const char *loadvm = NULL;
8237 QEMUMachine *machine;
8238 const char *cpu_model;
8239 const char *usb_devices[MAX_USB_CMDLINE];
8240 int usb_devices_index;
8241 int fds[2];
8242 const char *pid_file = NULL;
8243 VLANState *vlan;
8245 LIST_INIT (&vm_change_state_head);
8246 #ifndef _WIN32
8248 struct sigaction act;
8249 sigfillset(&act.sa_mask);
8250 act.sa_flags = 0;
8251 act.sa_handler = SIG_IGN;
8252 sigaction(SIGPIPE, &act, NULL);
8254 #else
8255 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8256 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8257 QEMU to run on a single CPU */
8259 HANDLE h;
8260 DWORD mask, smask;
8261 int i;
8262 h = GetCurrentProcess();
8263 if (GetProcessAffinityMask(h, &mask, &smask)) {
8264 for(i = 0; i < 32; i++) {
8265 if (mask & (1 << i))
8266 break;
8268 if (i != 32) {
8269 mask = 1 << i;
8270 SetProcessAffinityMask(h, mask);
8274 #endif
8276 register_machines();
8277 machine = first_machine;
8278 cpu_model = NULL;
8279 initrd_filename = NULL;
8280 ram_size = -1;
8281 vga_ram_size = VGA_RAM_SIZE;
8282 #ifdef CONFIG_GDBSTUB
8283 use_gdbstub = 0;
8284 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8285 #endif
8286 snapshot = 0;
8287 nographic = 0;
8288 curses = 0;
8289 kernel_filename = NULL;
8290 kernel_cmdline = "";
8291 cyls = heads = secs = 0;
8292 translation = BIOS_ATA_TRANSLATION_AUTO;
8293 monitor_device = "vc";
8295 serial_devices[0] = "vc";
8296 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8297 serial_devices[i] = NULL;
8298 serial_device_index = 0;
8300 parallel_devices[0] = "vc";
8301 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8302 parallel_devices[i] = NULL;
8303 parallel_device_index = 0;
8305 usb_devices_index = 0;
8307 nb_net_clients = 0;
8308 nb_drives = 0;
8309 nb_drives_opt = 0;
8310 hda_index = -1;
8312 nb_nics = 0;
8313 /* default mac address of the first network interface */
8315 optind = 1;
8316 for(;;) {
8317 if (optind >= argc)
8318 break;
8319 r = argv[optind];
8320 if (r[0] != '-') {
8321 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8322 } else {
8323 const QEMUOption *popt;
8325 optind++;
8326 /* Treat --foo the same as -foo. */
8327 if (r[1] == '-')
8328 r++;
8329 popt = qemu_options;
8330 for(;;) {
8331 if (!popt->name) {
8332 fprintf(stderr, "%s: invalid option -- '%s'\n",
8333 argv[0], r);
8334 exit(1);
8336 if (!strcmp(popt->name, r + 1))
8337 break;
8338 popt++;
8340 if (popt->flags & HAS_ARG) {
8341 if (optind >= argc) {
8342 fprintf(stderr, "%s: option '%s' requires an argument\n",
8343 argv[0], r);
8344 exit(1);
8346 optarg = argv[optind++];
8347 } else {
8348 optarg = NULL;
8351 switch(popt->index) {
8352 case QEMU_OPTION_M:
8353 machine = find_machine(optarg);
8354 if (!machine) {
8355 QEMUMachine *m;
8356 printf("Supported machines are:\n");
8357 for(m = first_machine; m != NULL; m = m->next) {
8358 printf("%-10s %s%s\n",
8359 m->name, m->desc,
8360 m == first_machine ? " (default)" : "");
8362 exit(*optarg != '?');
8364 break;
8365 case QEMU_OPTION_cpu:
8366 /* hw initialization will check this */
8367 if (*optarg == '?') {
8368 /* XXX: implement xxx_cpu_list for targets that still miss it */
8369 #if defined(cpu_list)
8370 cpu_list(stdout, &fprintf);
8371 #endif
8372 exit(0);
8373 } else {
8374 cpu_model = optarg;
8376 break;
8377 case QEMU_OPTION_initrd:
8378 initrd_filename = optarg;
8379 break;
8380 case QEMU_OPTION_hda:
8381 if (cyls == 0)
8382 hda_index = drive_add(optarg, HD_ALIAS, 0);
8383 else
8384 hda_index = drive_add(optarg, HD_ALIAS
8385 ",cyls=%d,heads=%d,secs=%d%s",
8386 0, cyls, heads, secs,
8387 translation == BIOS_ATA_TRANSLATION_LBA ?
8388 ",trans=lba" :
8389 translation == BIOS_ATA_TRANSLATION_NONE ?
8390 ",trans=none" : "");
8391 break;
8392 case QEMU_OPTION_hdb:
8393 case QEMU_OPTION_hdc:
8394 case QEMU_OPTION_hdd:
8395 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8396 break;
8397 case QEMU_OPTION_drive:
8398 drive_add(NULL, "%s", optarg);
8399 break;
8400 case QEMU_OPTION_mtdblock:
8401 drive_add(optarg, MTD_ALIAS);
8402 break;
8403 case QEMU_OPTION_sd:
8404 drive_add(optarg, SD_ALIAS);
8405 break;
8406 case QEMU_OPTION_pflash:
8407 drive_add(optarg, PFLASH_ALIAS);
8408 break;
8409 case QEMU_OPTION_snapshot:
8410 snapshot = 1;
8411 break;
8412 case QEMU_OPTION_hdachs:
8414 const char *p;
8415 p = optarg;
8416 cyls = strtol(p, (char **)&p, 0);
8417 if (cyls < 1 || cyls > 16383)
8418 goto chs_fail;
8419 if (*p != ',')
8420 goto chs_fail;
8421 p++;
8422 heads = strtol(p, (char **)&p, 0);
8423 if (heads < 1 || heads > 16)
8424 goto chs_fail;
8425 if (*p != ',')
8426 goto chs_fail;
8427 p++;
8428 secs = strtol(p, (char **)&p, 0);
8429 if (secs < 1 || secs > 63)
8430 goto chs_fail;
8431 if (*p == ',') {
8432 p++;
8433 if (!strcmp(p, "none"))
8434 translation = BIOS_ATA_TRANSLATION_NONE;
8435 else if (!strcmp(p, "lba"))
8436 translation = BIOS_ATA_TRANSLATION_LBA;
8437 else if (!strcmp(p, "auto"))
8438 translation = BIOS_ATA_TRANSLATION_AUTO;
8439 else
8440 goto chs_fail;
8441 } else if (*p != '\0') {
8442 chs_fail:
8443 fprintf(stderr, "qemu: invalid physical CHS format\n");
8444 exit(1);
8446 if (hda_index != -1)
8447 snprintf(drives_opt[hda_index].opt,
8448 sizeof(drives_opt[hda_index].opt),
8449 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8450 0, cyls, heads, secs,
8451 translation == BIOS_ATA_TRANSLATION_LBA ?
8452 ",trans=lba" :
8453 translation == BIOS_ATA_TRANSLATION_NONE ?
8454 ",trans=none" : "");
8456 break;
8457 case QEMU_OPTION_nographic:
8458 serial_devices[0] = "stdio";
8459 parallel_devices[0] = "null";
8460 monitor_device = "stdio";
8461 nographic = 1;
8462 break;
8463 #ifdef CONFIG_CURSES
8464 case QEMU_OPTION_curses:
8465 curses = 1;
8466 break;
8467 #endif
8468 case QEMU_OPTION_portrait:
8469 graphic_rotate = 1;
8470 break;
8471 case QEMU_OPTION_kernel:
8472 kernel_filename = optarg;
8473 break;
8474 case QEMU_OPTION_append:
8475 kernel_cmdline = optarg;
8476 break;
8477 case QEMU_OPTION_cdrom:
8478 drive_add(optarg, CDROM_ALIAS);
8479 break;
8480 case QEMU_OPTION_boot:
8481 boot_devices = optarg;
8482 /* We just do some generic consistency checks */
8484 /* Could easily be extended to 64 devices if needed */
8485 const char *p;
8487 boot_devices_bitmap = 0;
8488 for (p = boot_devices; *p != '\0'; p++) {
8489 /* Allowed boot devices are:
8490 * a b : floppy disk drives
8491 * c ... f : IDE disk drives
8492 * g ... m : machine implementation dependant drives
8493 * n ... p : network devices
8494 * It's up to each machine implementation to check
8495 * if the given boot devices match the actual hardware
8496 * implementation and firmware features.
8498 if (*p < 'a' || *p > 'q') {
8499 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8500 exit(1);
8502 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8503 fprintf(stderr,
8504 "Boot device '%c' was given twice\n",*p);
8505 exit(1);
8507 boot_devices_bitmap |= 1 << (*p - 'a');
8510 break;
8511 case QEMU_OPTION_fda:
8512 case QEMU_OPTION_fdb:
8513 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8514 break;
8515 #ifdef TARGET_I386
8516 case QEMU_OPTION_no_fd_bootchk:
8517 fd_bootchk = 0;
8518 break;
8519 #endif
8520 case QEMU_OPTION_no_code_copy:
8521 code_copy_enabled = 0;
8522 break;
8523 case QEMU_OPTION_net:
8524 if (nb_net_clients >= MAX_NET_CLIENTS) {
8525 fprintf(stderr, "qemu: too many network clients\n");
8526 exit(1);
8528 net_clients[nb_net_clients] = optarg;
8529 nb_net_clients++;
8530 break;
8531 #ifdef CONFIG_SLIRP
8532 case QEMU_OPTION_tftp:
8533 tftp_prefix = optarg;
8534 break;
8535 case QEMU_OPTION_bootp:
8536 bootp_filename = optarg;
8537 break;
8538 #ifndef _WIN32
8539 case QEMU_OPTION_smb:
8540 net_slirp_smb(optarg);
8541 break;
8542 #endif
8543 case QEMU_OPTION_redir:
8544 net_slirp_redir(optarg);
8545 break;
8546 #endif
8547 #ifdef HAS_AUDIO
8548 case QEMU_OPTION_audio_help:
8549 AUD_help ();
8550 exit (0);
8551 break;
8552 case QEMU_OPTION_soundhw:
8553 select_soundhw (optarg);
8554 break;
8555 #endif
8556 case QEMU_OPTION_h:
8557 help(0);
8558 break;
8559 case QEMU_OPTION_m:
8560 ram_size = atoi(optarg) * 1024 * 1024;
8561 if (ram_size <= 0)
8562 help(1);
8563 if (ram_size > PHYS_RAM_MAX_SIZE) {
8564 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8565 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8566 exit(1);
8568 break;
8569 case QEMU_OPTION_d:
8571 int mask;
8572 CPULogItem *item;
8574 mask = cpu_str_to_log_mask(optarg);
8575 if (!mask) {
8576 printf("Log items (comma separated):\n");
8577 for(item = cpu_log_items; item->mask != 0; item++) {
8578 printf("%-10s %s\n", item->name, item->help);
8580 exit(1);
8582 cpu_set_log(mask);
8584 break;
8585 #ifdef CONFIG_GDBSTUB
8586 case QEMU_OPTION_s:
8587 use_gdbstub = 1;
8588 break;
8589 case QEMU_OPTION_p:
8590 gdbstub_port = optarg;
8591 break;
8592 #endif
8593 case QEMU_OPTION_L:
8594 bios_dir = optarg;
8595 break;
8596 case QEMU_OPTION_bios:
8597 bios_name = optarg;
8598 break;
8599 case QEMU_OPTION_S:
8600 autostart = 0;
8601 break;
8602 case QEMU_OPTION_k:
8603 keyboard_layout = optarg;
8604 break;
8605 case QEMU_OPTION_localtime:
8606 rtc_utc = 0;
8607 break;
8608 case QEMU_OPTION_cirrusvga:
8609 cirrus_vga_enabled = 1;
8610 vmsvga_enabled = 0;
8611 break;
8612 case QEMU_OPTION_vmsvga:
8613 cirrus_vga_enabled = 0;
8614 vmsvga_enabled = 1;
8615 break;
8616 case QEMU_OPTION_std_vga:
8617 cirrus_vga_enabled = 0;
8618 vmsvga_enabled = 0;
8619 break;
8620 case QEMU_OPTION_g:
8622 const char *p;
8623 int w, h, depth;
8624 p = optarg;
8625 w = strtol(p, (char **)&p, 10);
8626 if (w <= 0) {
8627 graphic_error:
8628 fprintf(stderr, "qemu: invalid resolution or depth\n");
8629 exit(1);
8631 if (*p != 'x')
8632 goto graphic_error;
8633 p++;
8634 h = strtol(p, (char **)&p, 10);
8635 if (h <= 0)
8636 goto graphic_error;
8637 if (*p == 'x') {
8638 p++;
8639 depth = strtol(p, (char **)&p, 10);
8640 if (depth != 8 && depth != 15 && depth != 16 &&
8641 depth != 24 && depth != 32)
8642 goto graphic_error;
8643 } else if (*p == '\0') {
8644 depth = graphic_depth;
8645 } else {
8646 goto graphic_error;
8649 graphic_width = w;
8650 graphic_height = h;
8651 graphic_depth = depth;
8653 break;
8654 case QEMU_OPTION_echr:
8656 char *r;
8657 term_escape_char = strtol(optarg, &r, 0);
8658 if (r == optarg)
8659 printf("Bad argument to echr\n");
8660 break;
8662 case QEMU_OPTION_monitor:
8663 monitor_device = optarg;
8664 break;
8665 case QEMU_OPTION_serial:
8666 if (serial_device_index >= MAX_SERIAL_PORTS) {
8667 fprintf(stderr, "qemu: too many serial ports\n");
8668 exit(1);
8670 serial_devices[serial_device_index] = optarg;
8671 serial_device_index++;
8672 break;
8673 case QEMU_OPTION_parallel:
8674 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8675 fprintf(stderr, "qemu: too many parallel ports\n");
8676 exit(1);
8678 parallel_devices[parallel_device_index] = optarg;
8679 parallel_device_index++;
8680 break;
8681 case QEMU_OPTION_loadvm:
8682 loadvm = optarg;
8683 break;
8684 case QEMU_OPTION_full_screen:
8685 full_screen = 1;
8686 break;
8687 #ifdef CONFIG_SDL
8688 case QEMU_OPTION_no_frame:
8689 no_frame = 1;
8690 break;
8691 case QEMU_OPTION_alt_grab:
8692 alt_grab = 1;
8693 break;
8694 case QEMU_OPTION_no_quit:
8695 no_quit = 1;
8696 break;
8697 #endif
8698 case QEMU_OPTION_pidfile:
8699 pid_file = optarg;
8700 break;
8701 #ifdef TARGET_I386
8702 case QEMU_OPTION_win2k_hack:
8703 win2k_install_hack = 1;
8704 break;
8705 #endif
8706 #ifdef USE_KQEMU
8707 case QEMU_OPTION_no_kqemu:
8708 kqemu_allowed = 0;
8709 break;
8710 case QEMU_OPTION_kernel_kqemu:
8711 kqemu_allowed = 2;
8712 break;
8713 #endif
8714 case QEMU_OPTION_usb:
8715 usb_enabled = 1;
8716 break;
8717 case QEMU_OPTION_usbdevice:
8718 usb_enabled = 1;
8719 if (usb_devices_index >= MAX_USB_CMDLINE) {
8720 fprintf(stderr, "Too many USB devices\n");
8721 exit(1);
8723 usb_devices[usb_devices_index] = optarg;
8724 usb_devices_index++;
8725 break;
8726 case QEMU_OPTION_smp:
8727 smp_cpus = atoi(optarg);
8728 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8729 fprintf(stderr, "Invalid number of CPUs\n");
8730 exit(1);
8732 break;
8733 case QEMU_OPTION_vnc:
8734 vnc_display = optarg;
8735 break;
8736 case QEMU_OPTION_no_acpi:
8737 acpi_enabled = 0;
8738 break;
8739 case QEMU_OPTION_no_reboot:
8740 no_reboot = 1;
8741 break;
8742 case QEMU_OPTION_no_shutdown:
8743 no_shutdown = 1;
8744 break;
8745 case QEMU_OPTION_show_cursor:
8746 cursor_hide = 0;
8747 break;
8748 case QEMU_OPTION_daemonize:
8749 daemonize = 1;
8750 break;
8751 case QEMU_OPTION_option_rom:
8752 if (nb_option_roms >= MAX_OPTION_ROMS) {
8753 fprintf(stderr, "Too many option ROMs\n");
8754 exit(1);
8756 option_rom[nb_option_roms] = optarg;
8757 nb_option_roms++;
8758 break;
8759 case QEMU_OPTION_semihosting:
8760 semihosting_enabled = 1;
8761 break;
8762 case QEMU_OPTION_name:
8763 qemu_name = optarg;
8764 break;
8765 #ifdef TARGET_SPARC
8766 case QEMU_OPTION_prom_env:
8767 if (nb_prom_envs >= MAX_PROM_ENVS) {
8768 fprintf(stderr, "Too many prom variables\n");
8769 exit(1);
8771 prom_envs[nb_prom_envs] = optarg;
8772 nb_prom_envs++;
8773 break;
8774 #endif
8775 #ifdef TARGET_ARM
8776 case QEMU_OPTION_old_param:
8777 old_param = 1;
8778 break;
8779 #endif
8780 case QEMU_OPTION_clock:
8781 configure_alarms(optarg);
8782 break;
8783 case QEMU_OPTION_startdate:
8785 struct tm tm;
8786 time_t rtc_start_date;
8787 if (!strcmp(optarg, "now")) {
8788 rtc_date_offset = -1;
8789 } else {
8790 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8791 &tm.tm_year,
8792 &tm.tm_mon,
8793 &tm.tm_mday,
8794 &tm.tm_hour,
8795 &tm.tm_min,
8796 &tm.tm_sec) == 6) {
8797 /* OK */
8798 } else if (sscanf(optarg, "%d-%d-%d",
8799 &tm.tm_year,
8800 &tm.tm_mon,
8801 &tm.tm_mday) == 3) {
8802 tm.tm_hour = 0;
8803 tm.tm_min = 0;
8804 tm.tm_sec = 0;
8805 } else {
8806 goto date_fail;
8808 tm.tm_year -= 1900;
8809 tm.tm_mon--;
8810 rtc_start_date = mktimegm(&tm);
8811 if (rtc_start_date == -1) {
8812 date_fail:
8813 fprintf(stderr, "Invalid date format. Valid format are:\n"
8814 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8815 exit(1);
8817 rtc_date_offset = time(NULL) - rtc_start_date;
8820 break;
8825 #ifndef _WIN32
8826 if (daemonize && !nographic && vnc_display == NULL) {
8827 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8828 daemonize = 0;
8831 if (daemonize) {
8832 pid_t pid;
8834 if (pipe(fds) == -1)
8835 exit(1);
8837 pid = fork();
8838 if (pid > 0) {
8839 uint8_t status;
8840 ssize_t len;
8842 close(fds[1]);
8844 again:
8845 len = read(fds[0], &status, 1);
8846 if (len == -1 && (errno == EINTR))
8847 goto again;
8849 if (len != 1)
8850 exit(1);
8851 else if (status == 1) {
8852 fprintf(stderr, "Could not acquire pidfile\n");
8853 exit(1);
8854 } else
8855 exit(0);
8856 } else if (pid < 0)
8857 exit(1);
8859 setsid();
8861 pid = fork();
8862 if (pid > 0)
8863 exit(0);
8864 else if (pid < 0)
8865 exit(1);
8867 umask(027);
8868 chdir("/");
8870 signal(SIGTSTP, SIG_IGN);
8871 signal(SIGTTOU, SIG_IGN);
8872 signal(SIGTTIN, SIG_IGN);
8874 #endif
8876 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8877 if (daemonize) {
8878 uint8_t status = 1;
8879 write(fds[1], &status, 1);
8880 } else
8881 fprintf(stderr, "Could not acquire pid file\n");
8882 exit(1);
8885 #ifdef USE_KQEMU
8886 if (smp_cpus > 1)
8887 kqemu_allowed = 0;
8888 #endif
8889 linux_boot = (kernel_filename != NULL);
8890 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8892 /* XXX: this should not be: some embedded targets just have flash */
8893 if (!linux_boot && net_boot == 0 &&
8894 nb_drives_opt == 0)
8895 help(1);
8897 /* boot to floppy or the default cd if no hard disk defined yet */
8898 if (!boot_devices[0]) {
8899 boot_devices = "cad";
8901 setvbuf(stdout, NULL, _IOLBF, 0);
8903 init_timers();
8904 init_timer_alarm();
8905 qemu_aio_init();
8907 #ifdef _WIN32
8908 socket_init();
8909 #endif
8911 /* init network clients */
8912 if (nb_net_clients == 0) {
8913 /* if no clients, we use a default config */
8914 net_clients[0] = "nic";
8915 net_clients[1] = "user";
8916 nb_net_clients = 2;
8919 for(i = 0;i < nb_net_clients; i++) {
8920 if (net_client_init(net_clients[i]) < 0)
8921 exit(1);
8923 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8924 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8925 continue;
8926 if (vlan->nb_guest_devs == 0) {
8927 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8928 exit(1);
8930 if (vlan->nb_host_devs == 0)
8931 fprintf(stderr,
8932 "Warning: vlan %d is not connected to host network\n",
8933 vlan->id);
8936 #ifdef TARGET_I386
8937 /* XXX: this should be moved in the PC machine instantiation code */
8938 if (net_boot != 0) {
8939 int netroms = 0;
8940 for (i = 0; i < nb_nics && i < 4; i++) {
8941 const char *model = nd_table[i].model;
8942 char buf[1024];
8943 if (net_boot & (1 << i)) {
8944 if (model == NULL)
8945 model = "ne2k_pci";
8946 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8947 if (get_image_size(buf) > 0) {
8948 if (nb_option_roms >= MAX_OPTION_ROMS) {
8949 fprintf(stderr, "Too many option ROMs\n");
8950 exit(1);
8952 option_rom[nb_option_roms] = strdup(buf);
8953 nb_option_roms++;
8954 netroms++;
8958 if (netroms == 0) {
8959 fprintf(stderr, "No valid PXE rom found for network device\n");
8960 exit(1);
8963 #endif
8965 /* init the memory */
8966 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8968 if (machine->ram_require & RAMSIZE_FIXED) {
8969 if (ram_size > 0) {
8970 if (ram_size < phys_ram_size) {
8971 fprintf(stderr, "Machine `%s' requires %i bytes of memory\n",
8972 machine->name, phys_ram_size);
8973 exit(-1);
8976 phys_ram_size = ram_size;
8977 } else
8978 ram_size = phys_ram_size;
8979 } else {
8980 if (ram_size < 0)
8981 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8983 phys_ram_size += ram_size;
8986 phys_ram_base = qemu_vmalloc(phys_ram_size);
8987 if (!phys_ram_base) {
8988 fprintf(stderr, "Could not allocate physical memory\n");
8989 exit(1);
8992 bdrv_init();
8994 /* we always create the cdrom drive, even if no disk is there */
8996 if (nb_drives_opt < MAX_DRIVES)
8997 drive_add(NULL, CDROM_ALIAS);
8999 /* we always create at least one floppy */
9001 if (nb_drives_opt < MAX_DRIVES)
9002 drive_add(NULL, FD_ALIAS, 0);
9004 /* we always create one sd slot, even if no card is in it */
9006 if (nb_drives_opt < MAX_DRIVES)
9007 drive_add(NULL, SD_ALIAS);
9009 /* open the virtual block devices */
9011 for(i = 0; i < nb_drives_opt; i++)
9012 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9013 exit(1);
9015 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9016 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9018 init_ioports();
9020 /* terminal init */
9021 memset(&display_state, 0, sizeof(display_state));
9022 if (nographic) {
9023 if (curses) {
9024 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9025 exit(1);
9027 /* nearly nothing to do */
9028 dumb_display_init(ds);
9029 } else if (vnc_display != NULL) {
9030 vnc_display_init(ds);
9031 if (vnc_display_open(ds, vnc_display) < 0)
9032 exit(1);
9033 } else
9034 #if defined(CONFIG_CURSES)
9035 if (curses) {
9036 curses_display_init(ds, full_screen);
9037 } else
9038 #endif
9040 #if defined(CONFIG_SDL)
9041 sdl_display_init(ds, full_screen, no_frame);
9042 #elif defined(CONFIG_COCOA)
9043 cocoa_display_init(ds, full_screen);
9044 #else
9045 dumb_display_init(ds);
9046 #endif
9049 /* Maintain compatibility with multiple stdio monitors */
9050 if (!strcmp(monitor_device,"stdio")) {
9051 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9052 const char *devname = serial_devices[i];
9053 if (devname && !strcmp(devname,"mon:stdio")) {
9054 monitor_device = NULL;
9055 break;
9056 } else if (devname && !strcmp(devname,"stdio")) {
9057 monitor_device = NULL;
9058 serial_devices[i] = "mon:stdio";
9059 break;
9063 if (monitor_device) {
9064 monitor_hd = qemu_chr_open(monitor_device);
9065 if (!monitor_hd) {
9066 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9067 exit(1);
9069 monitor_init(monitor_hd, !nographic);
9072 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9073 const char *devname = serial_devices[i];
9074 if (devname && strcmp(devname, "none")) {
9075 serial_hds[i] = qemu_chr_open(devname);
9076 if (!serial_hds[i]) {
9077 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9078 devname);
9079 exit(1);
9081 if (strstart(devname, "vc", 0))
9082 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9086 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9087 const char *devname = parallel_devices[i];
9088 if (devname && strcmp(devname, "none")) {
9089 parallel_hds[i] = qemu_chr_open(devname);
9090 if (!parallel_hds[i]) {
9091 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9092 devname);
9093 exit(1);
9095 if (strstart(devname, "vc", 0))
9096 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9100 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9101 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9103 /* init USB devices */
9104 if (usb_enabled) {
9105 for(i = 0; i < usb_devices_index; i++) {
9106 if (usb_device_add(usb_devices[i]) < 0) {
9107 fprintf(stderr, "Warning: could not add USB device %s\n",
9108 usb_devices[i]);
9113 if (display_state.dpy_refresh) {
9114 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9115 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9118 #ifdef CONFIG_GDBSTUB
9119 if (use_gdbstub) {
9120 /* XXX: use standard host:port notation and modify options
9121 accordingly. */
9122 if (gdbserver_start(gdbstub_port) < 0) {
9123 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9124 gdbstub_port);
9125 exit(1);
9128 #endif
9130 if (loadvm)
9131 do_loadvm(loadvm);
9134 /* XXX: simplify init */
9135 read_passwords();
9136 if (autostart) {
9137 vm_start();
9141 if (daemonize) {
9142 uint8_t status = 0;
9143 ssize_t len;
9144 int fd;
9146 again1:
9147 len = write(fds[1], &status, 1);
9148 if (len == -1 && (errno == EINTR))
9149 goto again1;
9151 if (len != 1)
9152 exit(1);
9154 TFR(fd = open("/dev/null", O_RDWR));
9155 if (fd == -1)
9156 exit(1);
9158 dup2(fd, 0);
9159 dup2(fd, 1);
9160 dup2(fd, 2);
9162 close(fd);
9165 main_loop();
9166 quit_timers();
9168 #if !defined(_WIN32)
9169 /* close network clients */
9170 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9171 VLANClientState *vc;
9173 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9174 if (vc->fd_read == tap_receive) {
9175 char ifname[64];
9176 TAPState *s = vc->opaque;
9178 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9179 s->down_script[0])
9180 launch_script(s->down_script, ifname, s->fd);
9184 #endif
9185 return 0;