ARM PL181 MMCI fixes.
[qemu/mini2440.git] / vl.c
blob4f9c4438960994ef9a1ab9c8a41089048dbfbaec
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
59 #else
60 #include <sys/stat.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
71 #include <net/if.h>
72 #include <syslog.h>
73 #include <stropts.h>
74 #endif
75 #endif
76 #endif
78 #if defined(CONFIG_SLIRP)
79 #include "libslirp.h"
80 #endif
82 #ifdef _WIN32
83 #include <malloc.h>
84 #include <sys/timeb.h>
85 #include <windows.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
88 #endif
90 #include "qemu_socket.h"
92 #ifdef CONFIG_SDL
93 #ifdef __APPLE__
94 #include <SDL/SDL.h>
95 #endif
96 #endif /* CONFIG_SDL */
98 #ifdef CONFIG_COCOA
99 #undef main
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
103 #include "disas.h"
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108 #ifdef __sun__
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110 #else
111 #define SMBD_COMMAND "/usr/sbin/smbd"
112 #endif
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
119 #ifdef TARGET_PPC
120 #define DEFAULT_RAM_SIZE 144
121 #else
122 #define DEFAULT_RAM_SIZE 128
123 #endif
124 /* in ms */
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141 BlockDriverState *pflash_table[MAX_PFLASH];
142 BlockDriverState *sd_bdrv;
143 BlockDriverState *mtd_bdrv;
144 /* point to the block driver where the snapshots are managed */
145 BlockDriverState *bs_snapshots;
146 int vga_ram_size;
147 static DisplayState display_state;
148 int nographic;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 int boot_device = 'c';
152 int ram_size;
153 int pit_min_timer_count = 0;
154 int nb_nics;
155 NICInfo nd_table[MAX_NICS];
156 int vm_running;
157 int rtc_utc = 1;
158 int cirrus_vga_enabled = 1;
159 int vmsvga_enabled = 0;
160 #ifdef TARGET_SPARC
161 int graphic_width = 1024;
162 int graphic_height = 768;
163 int graphic_depth = 8;
164 #else
165 int graphic_width = 800;
166 int graphic_height = 600;
167 int graphic_depth = 15;
168 #endif
169 int full_screen = 0;
170 int no_frame = 0;
171 int no_quit = 0;
172 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
173 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
174 #ifdef TARGET_I386
175 int win2k_install_hack = 0;
176 #endif
177 int usb_enabled = 0;
178 static VLANState *first_vlan;
179 int smp_cpus = 1;
180 const char *vnc_display;
181 #if defined(TARGET_SPARC)
182 #define MAX_CPUS 16
183 #elif defined(TARGET_I386)
184 #define MAX_CPUS 255
185 #else
186 #define MAX_CPUS 1
187 #endif
188 int acpi_enabled = 1;
189 int fd_bootchk = 1;
190 int no_reboot = 0;
191 int cursor_hide = 1;
192 int graphic_rotate = 0;
193 int daemonize = 0;
194 const char *option_rom[MAX_OPTION_ROMS];
195 int nb_option_roms;
196 int semihosting_enabled = 0;
197 int autostart = 1;
198 const char *qemu_name;
199 #ifdef TARGET_SPARC
200 unsigned int nb_prom_envs = 0;
201 const char *prom_envs[MAX_PROM_ENVS];
202 #endif
204 /***********************************************************/
205 /* x86 ISA bus support */
207 target_phys_addr_t isa_mem_base = 0;
208 PicState2 *isa_pic;
210 uint32_t default_ioport_readb(void *opaque, uint32_t address)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "unused inb: port=0x%04x\n", address);
214 #endif
215 return 0xff;
218 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
220 #ifdef DEBUG_UNUSED_IOPORT
221 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
222 #endif
225 /* default is to make two byte accesses */
226 uint32_t default_ioport_readw(void *opaque, uint32_t address)
228 uint32_t data;
229 data = ioport_read_table[0][address](ioport_opaque[address], address);
230 address = (address + 1) & (MAX_IOPORTS - 1);
231 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
232 return data;
235 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
237 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
238 address = (address + 1) & (MAX_IOPORTS - 1);
239 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
242 uint32_t default_ioport_readl(void *opaque, uint32_t address)
244 #ifdef DEBUG_UNUSED_IOPORT
245 fprintf(stderr, "unused inl: port=0x%04x\n", address);
246 #endif
247 return 0xffffffff;
250 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
252 #ifdef DEBUG_UNUSED_IOPORT
253 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
254 #endif
257 void init_ioports(void)
259 int i;
261 for(i = 0; i < MAX_IOPORTS; i++) {
262 ioport_read_table[0][i] = default_ioport_readb;
263 ioport_write_table[0][i] = default_ioport_writeb;
264 ioport_read_table[1][i] = default_ioport_readw;
265 ioport_write_table[1][i] = default_ioport_writew;
266 ioport_read_table[2][i] = default_ioport_readl;
267 ioport_write_table[2][i] = default_ioport_writel;
271 /* size is the word size in byte */
272 int register_ioport_read(int start, int length, int size,
273 IOPortReadFunc *func, void *opaque)
275 int i, bsize;
277 if (size == 1) {
278 bsize = 0;
279 } else if (size == 2) {
280 bsize = 1;
281 } else if (size == 4) {
282 bsize = 2;
283 } else {
284 hw_error("register_ioport_read: invalid size");
285 return -1;
287 for(i = start; i < start + length; i += size) {
288 ioport_read_table[bsize][i] = func;
289 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
290 hw_error("register_ioport_read: invalid opaque");
291 ioport_opaque[i] = opaque;
293 return 0;
296 /* size is the word size in byte */
297 int register_ioport_write(int start, int length, int size,
298 IOPortWriteFunc *func, void *opaque)
300 int i, bsize;
302 if (size == 1) {
303 bsize = 0;
304 } else if (size == 2) {
305 bsize = 1;
306 } else if (size == 4) {
307 bsize = 2;
308 } else {
309 hw_error("register_ioport_write: invalid size");
310 return -1;
312 for(i = start; i < start + length; i += size) {
313 ioport_write_table[bsize][i] = func;
314 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
315 hw_error("register_ioport_write: invalid opaque");
316 ioport_opaque[i] = opaque;
318 return 0;
321 void isa_unassign_ioport(int start, int length)
323 int i;
325 for(i = start; i < start + length; i++) {
326 ioport_read_table[0][i] = default_ioport_readb;
327 ioport_read_table[1][i] = default_ioport_readw;
328 ioport_read_table[2][i] = default_ioport_readl;
330 ioport_write_table[0][i] = default_ioport_writeb;
331 ioport_write_table[1][i] = default_ioport_writew;
332 ioport_write_table[2][i] = default_ioport_writel;
336 /***********************************************************/
338 void cpu_outb(CPUState *env, int addr, int val)
340 #ifdef DEBUG_IOPORT
341 if (loglevel & CPU_LOG_IOPORT)
342 fprintf(logfile, "outb: %04x %02x\n", addr, val);
343 #endif
344 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
345 #ifdef USE_KQEMU
346 if (env)
347 env->last_io_time = cpu_get_time_fast();
348 #endif
351 void cpu_outw(CPUState *env, int addr, int val)
353 #ifdef DEBUG_IOPORT
354 if (loglevel & CPU_LOG_IOPORT)
355 fprintf(logfile, "outw: %04x %04x\n", addr, val);
356 #endif
357 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
358 #ifdef USE_KQEMU
359 if (env)
360 env->last_io_time = cpu_get_time_fast();
361 #endif
364 void cpu_outl(CPUState *env, int addr, int val)
366 #ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outl: %04x %08x\n", addr, val);
369 #endif
370 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
371 #ifdef USE_KQEMU
372 if (env)
373 env->last_io_time = cpu_get_time_fast();
374 #endif
377 int cpu_inb(CPUState *env, int addr)
379 int val;
380 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
381 #ifdef DEBUG_IOPORT
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "inb : %04x %02x\n", addr, val);
384 #endif
385 #ifdef USE_KQEMU
386 if (env)
387 env->last_io_time = cpu_get_time_fast();
388 #endif
389 return val;
392 int cpu_inw(CPUState *env, int addr)
394 int val;
395 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
396 #ifdef DEBUG_IOPORT
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "inw : %04x %04x\n", addr, val);
399 #endif
400 #ifdef USE_KQEMU
401 if (env)
402 env->last_io_time = cpu_get_time_fast();
403 #endif
404 return val;
407 int cpu_inl(CPUState *env, int addr)
409 int val;
410 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
411 #ifdef DEBUG_IOPORT
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "inl : %04x %08x\n", addr, val);
414 #endif
415 #ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
418 #endif
419 return val;
422 /***********************************************************/
423 void hw_error(const char *fmt, ...)
425 va_list ap;
426 CPUState *env;
428 va_start(ap, fmt);
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 for(env = first_cpu; env != NULL; env = env->next_cpu) {
433 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
434 #ifdef TARGET_I386
435 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
436 #else
437 cpu_dump_state(env, stderr, fprintf, 0);
438 #endif
440 va_end(ap);
441 abort();
444 /***********************************************************/
445 /* keyboard/mouse */
447 static QEMUPutKBDEvent *qemu_put_kbd_event;
448 static void *qemu_put_kbd_event_opaque;
449 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
450 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
459 void *opaque, int absolute,
460 const char *name)
462 QEMUPutMouseEntry *s, *cursor;
464 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
465 if (!s)
466 return NULL;
468 s->qemu_put_mouse_event = func;
469 s->qemu_put_mouse_event_opaque = opaque;
470 s->qemu_put_mouse_event_absolute = absolute;
471 s->qemu_put_mouse_event_name = qemu_strdup(name);
472 s->next = NULL;
474 if (!qemu_put_mouse_event_head) {
475 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
476 return s;
479 cursor = qemu_put_mouse_event_head;
480 while (cursor->next != NULL)
481 cursor = cursor->next;
483 cursor->next = s;
484 qemu_put_mouse_event_current = s;
486 return s;
489 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
491 QEMUPutMouseEntry *prev = NULL, *cursor;
493 if (!qemu_put_mouse_event_head || entry == NULL)
494 return;
496 cursor = qemu_put_mouse_event_head;
497 while (cursor != NULL && cursor != entry) {
498 prev = cursor;
499 cursor = cursor->next;
502 if (cursor == NULL) // does not exist or list empty
503 return;
504 else if (prev == NULL) { // entry is head
505 qemu_put_mouse_event_head = cursor->next;
506 if (qemu_put_mouse_event_current == entry)
507 qemu_put_mouse_event_current = cursor->next;
508 qemu_free(entry->qemu_put_mouse_event_name);
509 qemu_free(entry);
510 return;
513 prev->next = entry->next;
515 if (qemu_put_mouse_event_current == entry)
516 qemu_put_mouse_event_current = prev;
518 qemu_free(entry->qemu_put_mouse_event_name);
519 qemu_free(entry);
522 void kbd_put_keycode(int keycode)
524 if (qemu_put_kbd_event) {
525 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
529 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
531 QEMUPutMouseEvent *mouse_event;
532 void *mouse_event_opaque;
533 int width;
535 if (!qemu_put_mouse_event_current) {
536 return;
539 mouse_event =
540 qemu_put_mouse_event_current->qemu_put_mouse_event;
541 mouse_event_opaque =
542 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
544 if (mouse_event) {
545 if (graphic_rotate) {
546 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
547 width = 0x7fff;
548 else
549 width = graphic_width;
550 mouse_event(mouse_event_opaque,
551 width - dy, dx, dz, buttons_state);
552 } else
553 mouse_event(mouse_event_opaque,
554 dx, dy, dz, buttons_state);
558 int kbd_mouse_is_absolute(void)
560 if (!qemu_put_mouse_event_current)
561 return 0;
563 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
566 void do_info_mice(void)
568 QEMUPutMouseEntry *cursor;
569 int index = 0;
571 if (!qemu_put_mouse_event_head) {
572 term_printf("No mouse devices connected\n");
573 return;
576 term_printf("Mouse devices available:\n");
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL) {
579 term_printf("%c Mouse #%d: %s\n",
580 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
581 index, cursor->qemu_put_mouse_event_name);
582 index++;
583 cursor = cursor->next;
587 void do_mouse_set(int index)
589 QEMUPutMouseEntry *cursor;
590 int i = 0;
592 if (!qemu_put_mouse_event_head) {
593 term_printf("No mouse devices connected\n");
594 return;
597 cursor = qemu_put_mouse_event_head;
598 while (cursor != NULL && index != i) {
599 i++;
600 cursor = cursor->next;
603 if (cursor != NULL)
604 qemu_put_mouse_event_current = cursor;
605 else
606 term_printf("Mouse at given index not found\n");
609 /* compute with 96 bit intermediate result: (a*b)/c */
610 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
612 union {
613 uint64_t ll;
614 struct {
615 #ifdef WORDS_BIGENDIAN
616 uint32_t high, low;
617 #else
618 uint32_t low, high;
619 #endif
620 } l;
621 } u, res;
622 uint64_t rl, rh;
624 u.ll = a;
625 rl = (uint64_t)u.l.low * (uint64_t)b;
626 rh = (uint64_t)u.l.high * (uint64_t)b;
627 rh += (rl >> 32);
628 res.l.high = rh / c;
629 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
630 return res.ll;
633 /***********************************************************/
634 /* real time host monotonic timer */
636 #define QEMU_TIMER_BASE 1000000000LL
638 #ifdef WIN32
640 static int64_t clock_freq;
642 static void init_get_clock(void)
644 LARGE_INTEGER freq;
645 int ret;
646 ret = QueryPerformanceFrequency(&freq);
647 if (ret == 0) {
648 fprintf(stderr, "Could not calibrate ticks\n");
649 exit(1);
651 clock_freq = freq.QuadPart;
654 static int64_t get_clock(void)
656 LARGE_INTEGER ti;
657 QueryPerformanceCounter(&ti);
658 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
661 #else
663 static int use_rt_clock;
665 static void init_get_clock(void)
667 use_rt_clock = 0;
668 #if defined(__linux__)
670 struct timespec ts;
671 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
672 use_rt_clock = 1;
675 #endif
678 static int64_t get_clock(void)
680 #if defined(__linux__)
681 if (use_rt_clock) {
682 struct timespec ts;
683 clock_gettime(CLOCK_MONOTONIC, &ts);
684 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
685 } else
686 #endif
688 /* XXX: using gettimeofday leads to problems if the date
689 changes, so it should be avoided. */
690 struct timeval tv;
691 gettimeofday(&tv, NULL);
692 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
696 #endif
698 /***********************************************************/
699 /* guest cycle counter */
701 static int64_t cpu_ticks_prev;
702 static int64_t cpu_ticks_offset;
703 static int64_t cpu_clock_offset;
704 static int cpu_ticks_enabled;
706 /* return the host CPU cycle counter and handle stop/restart */
707 int64_t cpu_get_ticks(void)
709 if (!cpu_ticks_enabled) {
710 return cpu_ticks_offset;
711 } else {
712 int64_t ticks;
713 ticks = cpu_get_real_ticks();
714 if (cpu_ticks_prev > ticks) {
715 /* Note: non increasing ticks may happen if the host uses
716 software suspend */
717 cpu_ticks_offset += cpu_ticks_prev - ticks;
719 cpu_ticks_prev = ticks;
720 return ticks + cpu_ticks_offset;
724 /* return the host CPU monotonic timer and handle stop/restart */
725 static int64_t cpu_get_clock(void)
727 int64_t ti;
728 if (!cpu_ticks_enabled) {
729 return cpu_clock_offset;
730 } else {
731 ti = get_clock();
732 return ti + cpu_clock_offset;
736 /* enable cpu_get_ticks() */
737 void cpu_enable_ticks(void)
739 if (!cpu_ticks_enabled) {
740 cpu_ticks_offset -= cpu_get_real_ticks();
741 cpu_clock_offset -= get_clock();
742 cpu_ticks_enabled = 1;
746 /* disable cpu_get_ticks() : the clock is stopped. You must not call
747 cpu_get_ticks() after that. */
748 void cpu_disable_ticks(void)
750 if (cpu_ticks_enabled) {
751 cpu_ticks_offset = cpu_get_ticks();
752 cpu_clock_offset = cpu_get_clock();
753 cpu_ticks_enabled = 0;
757 /***********************************************************/
758 /* timers */
760 #define QEMU_TIMER_REALTIME 0
761 #define QEMU_TIMER_VIRTUAL 1
763 struct QEMUClock {
764 int type;
765 /* XXX: add frequency */
768 struct QEMUTimer {
769 QEMUClock *clock;
770 int64_t expire_time;
771 QEMUTimerCB *cb;
772 void *opaque;
773 struct QEMUTimer *next;
776 QEMUClock *rt_clock;
777 QEMUClock *vm_clock;
779 static QEMUTimer *active_timers[2];
780 #ifdef _WIN32
781 static MMRESULT timerID;
782 static HANDLE host_alarm = NULL;
783 static unsigned int period = 1;
784 #else
785 /* frequency of the times() clock tick */
786 static int timer_freq;
787 #endif
789 QEMUClock *qemu_new_clock(int type)
791 QEMUClock *clock;
792 clock = qemu_mallocz(sizeof(QEMUClock));
793 if (!clock)
794 return NULL;
795 clock->type = type;
796 return clock;
799 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
801 QEMUTimer *ts;
803 ts = qemu_mallocz(sizeof(QEMUTimer));
804 ts->clock = clock;
805 ts->cb = cb;
806 ts->opaque = opaque;
807 return ts;
810 void qemu_free_timer(QEMUTimer *ts)
812 qemu_free(ts);
815 /* stop a timer, but do not dealloc it */
816 void qemu_del_timer(QEMUTimer *ts)
818 QEMUTimer **pt, *t;
820 /* NOTE: this code must be signal safe because
821 qemu_timer_expired() can be called from a signal. */
822 pt = &active_timers[ts->clock->type];
823 for(;;) {
824 t = *pt;
825 if (!t)
826 break;
827 if (t == ts) {
828 *pt = t->next;
829 break;
831 pt = &t->next;
835 /* modify the current timer so that it will be fired when current_time
836 >= expire_time. The corresponding callback will be called. */
837 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
839 QEMUTimer **pt, *t;
841 qemu_del_timer(ts);
843 /* add the timer in the sorted list */
844 /* NOTE: this code must be signal safe because
845 qemu_timer_expired() can be called from a signal. */
846 pt = &active_timers[ts->clock->type];
847 for(;;) {
848 t = *pt;
849 if (!t)
850 break;
851 if (t->expire_time > expire_time)
852 break;
853 pt = &t->next;
855 ts->expire_time = expire_time;
856 ts->next = *pt;
857 *pt = ts;
860 int qemu_timer_pending(QEMUTimer *ts)
862 QEMUTimer *t;
863 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
864 if (t == ts)
865 return 1;
867 return 0;
870 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
872 if (!timer_head)
873 return 0;
874 return (timer_head->expire_time <= current_time);
877 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
879 QEMUTimer *ts;
881 for(;;) {
882 ts = *ptimer_head;
883 if (!ts || ts->expire_time > current_time)
884 break;
885 /* remove timer from the list before calling the callback */
886 *ptimer_head = ts->next;
887 ts->next = NULL;
889 /* run the callback (the timer list can be modified) */
890 ts->cb(ts->opaque);
894 int64_t qemu_get_clock(QEMUClock *clock)
896 switch(clock->type) {
897 case QEMU_TIMER_REALTIME:
898 return get_clock() / 1000000;
899 default:
900 case QEMU_TIMER_VIRTUAL:
901 return cpu_get_clock();
905 static void init_timers(void)
907 init_get_clock();
908 ticks_per_sec = QEMU_TIMER_BASE;
909 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
910 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
913 /* save a timer */
914 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
916 uint64_t expire_time;
918 if (qemu_timer_pending(ts)) {
919 expire_time = ts->expire_time;
920 } else {
921 expire_time = -1;
923 qemu_put_be64(f, expire_time);
926 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
928 uint64_t expire_time;
930 expire_time = qemu_get_be64(f);
931 if (expire_time != -1) {
932 qemu_mod_timer(ts, expire_time);
933 } else {
934 qemu_del_timer(ts);
938 static void timer_save(QEMUFile *f, void *opaque)
940 if (cpu_ticks_enabled) {
941 hw_error("cannot save state if virtual timers are running");
943 qemu_put_be64s(f, &cpu_ticks_offset);
944 qemu_put_be64s(f, &ticks_per_sec);
945 qemu_put_be64s(f, &cpu_clock_offset);
948 static int timer_load(QEMUFile *f, void *opaque, int version_id)
950 if (version_id != 1 && version_id != 2)
951 return -EINVAL;
952 if (cpu_ticks_enabled) {
953 return -EINVAL;
955 qemu_get_be64s(f, &cpu_ticks_offset);
956 qemu_get_be64s(f, &ticks_per_sec);
957 if (version_id == 2) {
958 qemu_get_be64s(f, &cpu_clock_offset);
960 return 0;
963 #ifdef _WIN32
964 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
965 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
966 #else
967 static void host_alarm_handler(int host_signum)
968 #endif
970 #if 0
971 #define DISP_FREQ 1000
973 static int64_t delta_min = INT64_MAX;
974 static int64_t delta_max, delta_cum, last_clock, delta, ti;
975 static int count;
976 ti = qemu_get_clock(vm_clock);
977 if (last_clock != 0) {
978 delta = ti - last_clock;
979 if (delta < delta_min)
980 delta_min = delta;
981 if (delta > delta_max)
982 delta_max = delta;
983 delta_cum += delta;
984 if (++count == DISP_FREQ) {
985 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
986 muldiv64(delta_min, 1000000, ticks_per_sec),
987 muldiv64(delta_max, 1000000, ticks_per_sec),
988 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
989 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
990 count = 0;
991 delta_min = INT64_MAX;
992 delta_max = 0;
993 delta_cum = 0;
996 last_clock = ti;
998 #endif
999 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1000 qemu_get_clock(vm_clock)) ||
1001 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1002 qemu_get_clock(rt_clock))) {
1003 #ifdef _WIN32
1004 SetEvent(host_alarm);
1005 #endif
1006 CPUState *env = cpu_single_env;
1007 if (env) {
1008 /* stop the currently executing cpu because a timer occured */
1009 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1010 #ifdef USE_KQEMU
1011 if (env->kqemu_enabled) {
1012 kqemu_cpu_interrupt(env);
1014 #endif
1019 #ifndef _WIN32
1021 #if defined(__linux__)
1023 #define RTC_FREQ 1024
1025 static int rtc_fd;
1027 static int start_rtc_timer(void)
1029 rtc_fd = open("/dev/rtc", O_RDONLY);
1030 if (rtc_fd < 0)
1031 return -1;
1032 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1033 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1034 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1035 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1036 goto fail;
1038 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1039 fail:
1040 close(rtc_fd);
1041 return -1;
1043 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1044 return 0;
1047 #else
1049 static int start_rtc_timer(void)
1051 return -1;
1054 #endif /* !defined(__linux__) */
1056 #endif /* !defined(_WIN32) */
1058 static void init_timer_alarm(void)
1060 #ifdef _WIN32
1062 int count=0;
1063 TIMECAPS tc;
1065 ZeroMemory(&tc, sizeof(TIMECAPS));
1066 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1067 if (period < tc.wPeriodMin)
1068 period = tc.wPeriodMin;
1069 timeBeginPeriod(period);
1070 timerID = timeSetEvent(1, // interval (ms)
1071 period, // resolution
1072 host_alarm_handler, // function
1073 (DWORD)&count, // user parameter
1074 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1075 if( !timerID ) {
1076 perror("failed timer alarm");
1077 exit(1);
1079 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1080 if (!host_alarm) {
1081 perror("failed CreateEvent");
1082 exit(1);
1084 qemu_add_wait_object(host_alarm, NULL, NULL);
1086 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1087 #else
1089 struct sigaction act;
1090 struct itimerval itv;
1092 /* get times() syscall frequency */
1093 timer_freq = sysconf(_SC_CLK_TCK);
1095 /* timer signal */
1096 sigfillset(&act.sa_mask);
1097 act.sa_flags = 0;
1098 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1099 act.sa_flags |= SA_ONSTACK;
1100 #endif
1101 act.sa_handler = host_alarm_handler;
1102 sigaction(SIGALRM, &act, NULL);
1104 itv.it_interval.tv_sec = 0;
1105 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1106 itv.it_value.tv_sec = 0;
1107 itv.it_value.tv_usec = 10 * 1000;
1108 setitimer(ITIMER_REAL, &itv, NULL);
1109 /* we probe the tick duration of the kernel to inform the user if
1110 the emulated kernel requested a too high timer frequency */
1111 getitimer(ITIMER_REAL, &itv);
1113 #if defined(__linux__)
1114 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1115 have timers with 1 ms resolution. The correct solution will
1116 be to use the POSIX real time timers available in recent
1117 2.6 kernels */
1118 if (itv.it_interval.tv_usec > 1000 || 1) {
1119 /* try to use /dev/rtc to have a faster timer */
1120 if (start_rtc_timer() < 0)
1121 goto use_itimer;
1122 /* disable itimer */
1123 itv.it_interval.tv_sec = 0;
1124 itv.it_interval.tv_usec = 0;
1125 itv.it_value.tv_sec = 0;
1126 itv.it_value.tv_usec = 0;
1127 setitimer(ITIMER_REAL, &itv, NULL);
1129 /* use the RTC */
1130 sigaction(SIGIO, &act, NULL);
1131 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1132 fcntl(rtc_fd, F_SETOWN, getpid());
1133 } else
1134 #endif /* defined(__linux__) */
1136 use_itimer:
1137 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1138 PIT_FREQ) / 1000000;
1141 #endif
1144 void quit_timers(void)
1146 #ifdef _WIN32
1147 timeKillEvent(timerID);
1148 timeEndPeriod(period);
1149 if (host_alarm) {
1150 CloseHandle(host_alarm);
1151 host_alarm = NULL;
1153 #endif
1156 /***********************************************************/
1157 /* character device */
1159 static void qemu_chr_event(CharDriverState *s, int event)
1161 if (!s->chr_event)
1162 return;
1163 s->chr_event(s->handler_opaque, event);
1166 static void qemu_chr_reset_bh(void *opaque)
1168 CharDriverState *s = opaque;
1169 qemu_chr_event(s, CHR_EVENT_RESET);
1170 qemu_bh_delete(s->bh);
1171 s->bh = NULL;
1174 void qemu_chr_reset(CharDriverState *s)
1176 if (s->bh == NULL) {
1177 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1178 qemu_bh_schedule(s->bh);
1182 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1184 return s->chr_write(s, buf, len);
1187 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1189 if (!s->chr_ioctl)
1190 return -ENOTSUP;
1191 return s->chr_ioctl(s, cmd, arg);
1194 int qemu_chr_can_read(CharDriverState *s)
1196 if (!s->chr_can_read)
1197 return 0;
1198 return s->chr_can_read(s->handler_opaque);
1201 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1203 s->chr_read(s->handler_opaque, buf, len);
1207 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1209 char buf[4096];
1210 va_list ap;
1211 va_start(ap, fmt);
1212 vsnprintf(buf, sizeof(buf), fmt, ap);
1213 qemu_chr_write(s, buf, strlen(buf));
1214 va_end(ap);
1217 void qemu_chr_send_event(CharDriverState *s, int event)
1219 if (s->chr_send_event)
1220 s->chr_send_event(s, event);
1223 void qemu_chr_add_handlers(CharDriverState *s,
1224 IOCanRWHandler *fd_can_read,
1225 IOReadHandler *fd_read,
1226 IOEventHandler *fd_event,
1227 void *opaque)
1229 s->chr_can_read = fd_can_read;
1230 s->chr_read = fd_read;
1231 s->chr_event = fd_event;
1232 s->handler_opaque = opaque;
1233 if (s->chr_update_read_handler)
1234 s->chr_update_read_handler(s);
1237 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1239 return len;
1242 static CharDriverState *qemu_chr_open_null(void)
1244 CharDriverState *chr;
1246 chr = qemu_mallocz(sizeof(CharDriverState));
1247 if (!chr)
1248 return NULL;
1249 chr->chr_write = null_chr_write;
1250 return chr;
1253 /* MUX driver for serial I/O splitting */
1254 static int term_timestamps;
1255 static int64_t term_timestamps_start;
1256 #define MAX_MUX 4
1257 typedef struct {
1258 IOCanRWHandler *chr_can_read[MAX_MUX];
1259 IOReadHandler *chr_read[MAX_MUX];
1260 IOEventHandler *chr_event[MAX_MUX];
1261 void *ext_opaque[MAX_MUX];
1262 CharDriverState *drv;
1263 int mux_cnt;
1264 int term_got_escape;
1265 int max_size;
1266 } MuxDriver;
1269 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1271 MuxDriver *d = chr->opaque;
1272 int ret;
1273 if (!term_timestamps) {
1274 ret = d->drv->chr_write(d->drv, buf, len);
1275 } else {
1276 int i;
1278 ret = 0;
1279 for(i = 0; i < len; i++) {
1280 ret += d->drv->chr_write(d->drv, buf+i, 1);
1281 if (buf[i] == '\n') {
1282 char buf1[64];
1283 int64_t ti;
1284 int secs;
1286 ti = get_clock();
1287 if (term_timestamps_start == -1)
1288 term_timestamps_start = ti;
1289 ti -= term_timestamps_start;
1290 secs = ti / 1000000000;
1291 snprintf(buf1, sizeof(buf1),
1292 "[%02d:%02d:%02d.%03d] ",
1293 secs / 3600,
1294 (secs / 60) % 60,
1295 secs % 60,
1296 (int)((ti / 1000000) % 1000));
1297 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1301 return ret;
1304 static char *mux_help[] = {
1305 "% h print this help\n\r",
1306 "% x exit emulator\n\r",
1307 "% s save disk data back to file (if -snapshot)\n\r",
1308 "% t toggle console timestamps\n\r"
1309 "% b send break (magic sysrq)\n\r",
1310 "% c switch between console and monitor\n\r",
1311 "% % sends %\n\r",
1312 NULL
1315 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1316 static void mux_print_help(CharDriverState *chr)
1318 int i, j;
1319 char ebuf[15] = "Escape-Char";
1320 char cbuf[50] = "\n\r";
1322 if (term_escape_char > 0 && term_escape_char < 26) {
1323 sprintf(cbuf,"\n\r");
1324 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1325 } else {
1326 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1328 chr->chr_write(chr, cbuf, strlen(cbuf));
1329 for (i = 0; mux_help[i] != NULL; i++) {
1330 for (j=0; mux_help[i][j] != '\0'; j++) {
1331 if (mux_help[i][j] == '%')
1332 chr->chr_write(chr, ebuf, strlen(ebuf));
1333 else
1334 chr->chr_write(chr, &mux_help[i][j], 1);
1339 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1341 if (d->term_got_escape) {
1342 d->term_got_escape = 0;
1343 if (ch == term_escape_char)
1344 goto send_char;
1345 switch(ch) {
1346 case '?':
1347 case 'h':
1348 mux_print_help(chr);
1349 break;
1350 case 'x':
1352 char *term = "QEMU: Terminated\n\r";
1353 chr->chr_write(chr,term,strlen(term));
1354 exit(0);
1355 break;
1357 case 's':
1359 int i;
1360 for (i = 0; i < MAX_DISKS; i++) {
1361 if (bs_table[i])
1362 bdrv_commit(bs_table[i]);
1364 if (mtd_bdrv)
1365 bdrv_commit(mtd_bdrv);
1367 break;
1368 case 'b':
1369 qemu_chr_event(chr, CHR_EVENT_BREAK);
1370 break;
1371 case 'c':
1372 /* Switch to the next registered device */
1373 chr->focus++;
1374 if (chr->focus >= d->mux_cnt)
1375 chr->focus = 0;
1376 break;
1377 case 't':
1378 term_timestamps = !term_timestamps;
1379 term_timestamps_start = -1;
1380 break;
1382 } else if (ch == term_escape_char) {
1383 d->term_got_escape = 1;
1384 } else {
1385 send_char:
1386 return 1;
1388 return 0;
1391 static int mux_chr_can_read(void *opaque)
1393 CharDriverState *chr = opaque;
1394 MuxDriver *d = chr->opaque;
1395 if (d->chr_can_read[chr->focus])
1396 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1397 return 0;
1400 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1402 CharDriverState *chr = opaque;
1403 MuxDriver *d = chr->opaque;
1404 int i;
1405 for(i = 0; i < size; i++)
1406 if (mux_proc_byte(chr, d, buf[i]))
1407 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1410 static void mux_chr_event(void *opaque, int event)
1412 CharDriverState *chr = opaque;
1413 MuxDriver *d = chr->opaque;
1414 int i;
1416 /* Send the event to all registered listeners */
1417 for (i = 0; i < d->mux_cnt; i++)
1418 if (d->chr_event[i])
1419 d->chr_event[i](d->ext_opaque[i], event);
1422 static void mux_chr_update_read_handler(CharDriverState *chr)
1424 MuxDriver *d = chr->opaque;
1426 if (d->mux_cnt >= MAX_MUX) {
1427 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1428 return;
1430 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1431 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1432 d->chr_read[d->mux_cnt] = chr->chr_read;
1433 d->chr_event[d->mux_cnt] = chr->chr_event;
1434 /* Fix up the real driver with mux routines */
1435 if (d->mux_cnt == 0) {
1436 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1437 mux_chr_event, chr);
1439 chr->focus = d->mux_cnt;
1440 d->mux_cnt++;
1443 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1445 CharDriverState *chr;
1446 MuxDriver *d;
1448 chr = qemu_mallocz(sizeof(CharDriverState));
1449 if (!chr)
1450 return NULL;
1451 d = qemu_mallocz(sizeof(MuxDriver));
1452 if (!d) {
1453 free(chr);
1454 return NULL;
1457 chr->opaque = d;
1458 d->drv = drv;
1459 chr->focus = -1;
1460 chr->chr_write = mux_chr_write;
1461 chr->chr_update_read_handler = mux_chr_update_read_handler;
1462 return chr;
1466 #ifdef _WIN32
1468 static void socket_cleanup(void)
1470 WSACleanup();
1473 static int socket_init(void)
1475 WSADATA Data;
1476 int ret, err;
1478 ret = WSAStartup(MAKEWORD(2,2), &Data);
1479 if (ret != 0) {
1480 err = WSAGetLastError();
1481 fprintf(stderr, "WSAStartup: %d\n", err);
1482 return -1;
1484 atexit(socket_cleanup);
1485 return 0;
1488 static int send_all(int fd, const uint8_t *buf, int len1)
1490 int ret, len;
1492 len = len1;
1493 while (len > 0) {
1494 ret = send(fd, buf, len, 0);
1495 if (ret < 0) {
1496 int errno;
1497 errno = WSAGetLastError();
1498 if (errno != WSAEWOULDBLOCK) {
1499 return -1;
1501 } else if (ret == 0) {
1502 break;
1503 } else {
1504 buf += ret;
1505 len -= ret;
1508 return len1 - len;
1511 void socket_set_nonblock(int fd)
1513 unsigned long opt = 1;
1514 ioctlsocket(fd, FIONBIO, &opt);
1517 #else
1519 static int unix_write(int fd, const uint8_t *buf, int len1)
1521 int ret, len;
1523 len = len1;
1524 while (len > 0) {
1525 ret = write(fd, buf, len);
1526 if (ret < 0) {
1527 if (errno != EINTR && errno != EAGAIN)
1528 return -1;
1529 } else if (ret == 0) {
1530 break;
1531 } else {
1532 buf += ret;
1533 len -= ret;
1536 return len1 - len;
1539 static inline int send_all(int fd, const uint8_t *buf, int len1)
1541 return unix_write(fd, buf, len1);
1544 void socket_set_nonblock(int fd)
1546 fcntl(fd, F_SETFL, O_NONBLOCK);
1548 #endif /* !_WIN32 */
1550 #ifndef _WIN32
1552 typedef struct {
1553 int fd_in, fd_out;
1554 int max_size;
1555 } FDCharDriver;
1557 #define STDIO_MAX_CLIENTS 1
1558 static int stdio_nb_clients = 0;
1560 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1562 FDCharDriver *s = chr->opaque;
1563 return unix_write(s->fd_out, buf, len);
1566 static int fd_chr_read_poll(void *opaque)
1568 CharDriverState *chr = opaque;
1569 FDCharDriver *s = chr->opaque;
1571 s->max_size = qemu_chr_can_read(chr);
1572 return s->max_size;
1575 static void fd_chr_read(void *opaque)
1577 CharDriverState *chr = opaque;
1578 FDCharDriver *s = chr->opaque;
1579 int size, len;
1580 uint8_t buf[1024];
1582 len = sizeof(buf);
1583 if (len > s->max_size)
1584 len = s->max_size;
1585 if (len == 0)
1586 return;
1587 size = read(s->fd_in, buf, len);
1588 if (size == 0) {
1589 /* FD has been closed. Remove it from the active list. */
1590 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1591 return;
1593 if (size > 0) {
1594 qemu_chr_read(chr, buf, size);
1598 static void fd_chr_update_read_handler(CharDriverState *chr)
1600 FDCharDriver *s = chr->opaque;
1602 if (s->fd_in >= 0) {
1603 if (nographic && s->fd_in == 0) {
1604 } else {
1605 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1606 fd_chr_read, NULL, chr);
1611 /* open a character device to a unix fd */
1612 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1614 CharDriverState *chr;
1615 FDCharDriver *s;
1617 chr = qemu_mallocz(sizeof(CharDriverState));
1618 if (!chr)
1619 return NULL;
1620 s = qemu_mallocz(sizeof(FDCharDriver));
1621 if (!s) {
1622 free(chr);
1623 return NULL;
1625 s->fd_in = fd_in;
1626 s->fd_out = fd_out;
1627 chr->opaque = s;
1628 chr->chr_write = fd_chr_write;
1629 chr->chr_update_read_handler = fd_chr_update_read_handler;
1631 qemu_chr_reset(chr);
1633 return chr;
1636 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1638 int fd_out;
1640 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1641 if (fd_out < 0)
1642 return NULL;
1643 return qemu_chr_open_fd(-1, fd_out);
1646 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1648 int fd_in, fd_out;
1649 char filename_in[256], filename_out[256];
1651 snprintf(filename_in, 256, "%s.in", filename);
1652 snprintf(filename_out, 256, "%s.out", filename);
1653 fd_in = open(filename_in, O_RDWR | O_BINARY);
1654 fd_out = open(filename_out, O_RDWR | O_BINARY);
1655 if (fd_in < 0 || fd_out < 0) {
1656 if (fd_in >= 0)
1657 close(fd_in);
1658 if (fd_out >= 0)
1659 close(fd_out);
1660 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1661 if (fd_in < 0)
1662 return NULL;
1664 return qemu_chr_open_fd(fd_in, fd_out);
1668 /* for STDIO, we handle the case where several clients use it
1669 (nographic mode) */
1671 #define TERM_FIFO_MAX_SIZE 1
1673 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1674 static int term_fifo_size;
1676 static int stdio_read_poll(void *opaque)
1678 CharDriverState *chr = opaque;
1680 /* try to flush the queue if needed */
1681 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1682 qemu_chr_read(chr, term_fifo, 1);
1683 term_fifo_size = 0;
1685 /* see if we can absorb more chars */
1686 if (term_fifo_size == 0)
1687 return 1;
1688 else
1689 return 0;
1692 static void stdio_read(void *opaque)
1694 int size;
1695 uint8_t buf[1];
1696 CharDriverState *chr = opaque;
1698 size = read(0, buf, 1);
1699 if (size == 0) {
1700 /* stdin has been closed. Remove it from the active list. */
1701 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1702 return;
1704 if (size > 0) {
1705 if (qemu_chr_can_read(chr) > 0) {
1706 qemu_chr_read(chr, buf, 1);
1707 } else if (term_fifo_size == 0) {
1708 term_fifo[term_fifo_size++] = buf[0];
1713 /* init terminal so that we can grab keys */
1714 static struct termios oldtty;
1715 static int old_fd0_flags;
1717 static void term_exit(void)
1719 tcsetattr (0, TCSANOW, &oldtty);
1720 fcntl(0, F_SETFL, old_fd0_flags);
1723 static void term_init(void)
1725 struct termios tty;
1727 tcgetattr (0, &tty);
1728 oldtty = tty;
1729 old_fd0_flags = fcntl(0, F_GETFL);
1731 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1732 |INLCR|IGNCR|ICRNL|IXON);
1733 tty.c_oflag |= OPOST;
1734 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1735 /* if graphical mode, we allow Ctrl-C handling */
1736 if (nographic)
1737 tty.c_lflag &= ~ISIG;
1738 tty.c_cflag &= ~(CSIZE|PARENB);
1739 tty.c_cflag |= CS8;
1740 tty.c_cc[VMIN] = 1;
1741 tty.c_cc[VTIME] = 0;
1743 tcsetattr (0, TCSANOW, &tty);
1745 atexit(term_exit);
1747 fcntl(0, F_SETFL, O_NONBLOCK);
1750 static CharDriverState *qemu_chr_open_stdio(void)
1752 CharDriverState *chr;
1754 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1755 return NULL;
1756 chr = qemu_chr_open_fd(0, 1);
1757 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1758 stdio_nb_clients++;
1759 term_init();
1761 return chr;
1764 #if defined(__linux__)
1765 static CharDriverState *qemu_chr_open_pty(void)
1767 struct termios tty;
1768 char slave_name[1024];
1769 int master_fd, slave_fd;
1771 /* Not satisfying */
1772 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1773 return NULL;
1776 /* Disabling local echo and line-buffered output */
1777 tcgetattr (master_fd, &tty);
1778 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1779 tty.c_cc[VMIN] = 1;
1780 tty.c_cc[VTIME] = 0;
1781 tcsetattr (master_fd, TCSAFLUSH, &tty);
1783 fprintf(stderr, "char device redirected to %s\n", slave_name);
1784 return qemu_chr_open_fd(master_fd, master_fd);
1787 static void tty_serial_init(int fd, int speed,
1788 int parity, int data_bits, int stop_bits)
1790 struct termios tty;
1791 speed_t spd;
1793 #if 0
1794 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1795 speed, parity, data_bits, stop_bits);
1796 #endif
1797 tcgetattr (fd, &tty);
1799 switch(speed) {
1800 case 50:
1801 spd = B50;
1802 break;
1803 case 75:
1804 spd = B75;
1805 break;
1806 case 300:
1807 spd = B300;
1808 break;
1809 case 600:
1810 spd = B600;
1811 break;
1812 case 1200:
1813 spd = B1200;
1814 break;
1815 case 2400:
1816 spd = B2400;
1817 break;
1818 case 4800:
1819 spd = B4800;
1820 break;
1821 case 9600:
1822 spd = B9600;
1823 break;
1824 case 19200:
1825 spd = B19200;
1826 break;
1827 case 38400:
1828 spd = B38400;
1829 break;
1830 case 57600:
1831 spd = B57600;
1832 break;
1833 default:
1834 case 115200:
1835 spd = B115200;
1836 break;
1839 cfsetispeed(&tty, spd);
1840 cfsetospeed(&tty, spd);
1842 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1843 |INLCR|IGNCR|ICRNL|IXON);
1844 tty.c_oflag |= OPOST;
1845 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1846 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1847 switch(data_bits) {
1848 default:
1849 case 8:
1850 tty.c_cflag |= CS8;
1851 break;
1852 case 7:
1853 tty.c_cflag |= CS7;
1854 break;
1855 case 6:
1856 tty.c_cflag |= CS6;
1857 break;
1858 case 5:
1859 tty.c_cflag |= CS5;
1860 break;
1862 switch(parity) {
1863 default:
1864 case 'N':
1865 break;
1866 case 'E':
1867 tty.c_cflag |= PARENB;
1868 break;
1869 case 'O':
1870 tty.c_cflag |= PARENB | PARODD;
1871 break;
1873 if (stop_bits == 2)
1874 tty.c_cflag |= CSTOPB;
1876 tcsetattr (fd, TCSANOW, &tty);
1879 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1881 FDCharDriver *s = chr->opaque;
1883 switch(cmd) {
1884 case CHR_IOCTL_SERIAL_SET_PARAMS:
1886 QEMUSerialSetParams *ssp = arg;
1887 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1888 ssp->data_bits, ssp->stop_bits);
1890 break;
1891 case CHR_IOCTL_SERIAL_SET_BREAK:
1893 int enable = *(int *)arg;
1894 if (enable)
1895 tcsendbreak(s->fd_in, 1);
1897 break;
1898 default:
1899 return -ENOTSUP;
1901 return 0;
1904 static CharDriverState *qemu_chr_open_tty(const char *filename)
1906 CharDriverState *chr;
1907 int fd;
1909 fd = open(filename, O_RDWR | O_NONBLOCK);
1910 if (fd < 0)
1911 return NULL;
1912 fcntl(fd, F_SETFL, O_NONBLOCK);
1913 tty_serial_init(fd, 115200, 'N', 8, 1);
1914 chr = qemu_chr_open_fd(fd, fd);
1915 if (!chr)
1916 return NULL;
1917 chr->chr_ioctl = tty_serial_ioctl;
1918 qemu_chr_reset(chr);
1919 return chr;
1922 typedef struct {
1923 int fd;
1924 int mode;
1925 } ParallelCharDriver;
1927 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1929 if (s->mode != mode) {
1930 int m = mode;
1931 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1932 return 0;
1933 s->mode = mode;
1935 return 1;
1938 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1940 ParallelCharDriver *drv = chr->opaque;
1941 int fd = drv->fd;
1942 uint8_t b;
1944 switch(cmd) {
1945 case CHR_IOCTL_PP_READ_DATA:
1946 if (ioctl(fd, PPRDATA, &b) < 0)
1947 return -ENOTSUP;
1948 *(uint8_t *)arg = b;
1949 break;
1950 case CHR_IOCTL_PP_WRITE_DATA:
1951 b = *(uint8_t *)arg;
1952 if (ioctl(fd, PPWDATA, &b) < 0)
1953 return -ENOTSUP;
1954 break;
1955 case CHR_IOCTL_PP_READ_CONTROL:
1956 if (ioctl(fd, PPRCONTROL, &b) < 0)
1957 return -ENOTSUP;
1958 /* Linux gives only the lowest bits, and no way to know data
1959 direction! For better compatibility set the fixed upper
1960 bits. */
1961 *(uint8_t *)arg = b | 0xc0;
1962 break;
1963 case CHR_IOCTL_PP_WRITE_CONTROL:
1964 b = *(uint8_t *)arg;
1965 if (ioctl(fd, PPWCONTROL, &b) < 0)
1966 return -ENOTSUP;
1967 break;
1968 case CHR_IOCTL_PP_READ_STATUS:
1969 if (ioctl(fd, PPRSTATUS, &b) < 0)
1970 return -ENOTSUP;
1971 *(uint8_t *)arg = b;
1972 break;
1973 case CHR_IOCTL_PP_EPP_READ_ADDR:
1974 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1975 struct ParallelIOArg *parg = arg;
1976 int n = read(fd, parg->buffer, parg->count);
1977 if (n != parg->count) {
1978 return -EIO;
1981 break;
1982 case CHR_IOCTL_PP_EPP_READ:
1983 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1984 struct ParallelIOArg *parg = arg;
1985 int n = read(fd, parg->buffer, parg->count);
1986 if (n != parg->count) {
1987 return -EIO;
1990 break;
1991 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1992 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1993 struct ParallelIOArg *parg = arg;
1994 int n = write(fd, parg->buffer, parg->count);
1995 if (n != parg->count) {
1996 return -EIO;
1999 break;
2000 case CHR_IOCTL_PP_EPP_WRITE:
2001 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2002 struct ParallelIOArg *parg = arg;
2003 int n = write(fd, parg->buffer, parg->count);
2004 if (n != parg->count) {
2005 return -EIO;
2008 break;
2009 default:
2010 return -ENOTSUP;
2012 return 0;
2015 static void pp_close(CharDriverState *chr)
2017 ParallelCharDriver *drv = chr->opaque;
2018 int fd = drv->fd;
2020 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2021 ioctl(fd, PPRELEASE);
2022 close(fd);
2023 qemu_free(drv);
2026 static CharDriverState *qemu_chr_open_pp(const char *filename)
2028 CharDriverState *chr;
2029 ParallelCharDriver *drv;
2030 int fd;
2032 fd = open(filename, O_RDWR);
2033 if (fd < 0)
2034 return NULL;
2036 if (ioctl(fd, PPCLAIM) < 0) {
2037 close(fd);
2038 return NULL;
2041 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2042 if (!drv) {
2043 close(fd);
2044 return NULL;
2046 drv->fd = fd;
2047 drv->mode = IEEE1284_MODE_COMPAT;
2049 chr = qemu_mallocz(sizeof(CharDriverState));
2050 if (!chr) {
2051 qemu_free(drv);
2052 close(fd);
2053 return NULL;
2055 chr->chr_write = null_chr_write;
2056 chr->chr_ioctl = pp_ioctl;
2057 chr->chr_close = pp_close;
2058 chr->opaque = drv;
2060 qemu_chr_reset(chr);
2062 return chr;
2065 #else
2066 static CharDriverState *qemu_chr_open_pty(void)
2068 return NULL;
2070 #endif
2072 #endif /* !defined(_WIN32) */
2074 #ifdef _WIN32
2075 typedef struct {
2076 int max_size;
2077 HANDLE hcom, hrecv, hsend;
2078 OVERLAPPED orecv, osend;
2079 BOOL fpipe;
2080 DWORD len;
2081 } WinCharState;
2083 #define NSENDBUF 2048
2084 #define NRECVBUF 2048
2085 #define MAXCONNECT 1
2086 #define NTIMEOUT 5000
2088 static int win_chr_poll(void *opaque);
2089 static int win_chr_pipe_poll(void *opaque);
2091 static void win_chr_close(CharDriverState *chr)
2093 WinCharState *s = chr->opaque;
2095 if (s->hsend) {
2096 CloseHandle(s->hsend);
2097 s->hsend = NULL;
2099 if (s->hrecv) {
2100 CloseHandle(s->hrecv);
2101 s->hrecv = NULL;
2103 if (s->hcom) {
2104 CloseHandle(s->hcom);
2105 s->hcom = NULL;
2107 if (s->fpipe)
2108 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2109 else
2110 qemu_del_polling_cb(win_chr_poll, chr);
2113 static int win_chr_init(CharDriverState *chr, const char *filename)
2115 WinCharState *s = chr->opaque;
2116 COMMCONFIG comcfg;
2117 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2118 COMSTAT comstat;
2119 DWORD size;
2120 DWORD err;
2122 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2123 if (!s->hsend) {
2124 fprintf(stderr, "Failed CreateEvent\n");
2125 goto fail;
2127 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 if (!s->hrecv) {
2129 fprintf(stderr, "Failed CreateEvent\n");
2130 goto fail;
2133 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2134 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2135 if (s->hcom == INVALID_HANDLE_VALUE) {
2136 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2137 s->hcom = NULL;
2138 goto fail;
2141 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2142 fprintf(stderr, "Failed SetupComm\n");
2143 goto fail;
2146 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2147 size = sizeof(COMMCONFIG);
2148 GetDefaultCommConfig(filename, &comcfg, &size);
2149 comcfg.dcb.DCBlength = sizeof(DCB);
2150 CommConfigDialog(filename, NULL, &comcfg);
2152 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2153 fprintf(stderr, "Failed SetCommState\n");
2154 goto fail;
2157 if (!SetCommMask(s->hcom, EV_ERR)) {
2158 fprintf(stderr, "Failed SetCommMask\n");
2159 goto fail;
2162 cto.ReadIntervalTimeout = MAXDWORD;
2163 if (!SetCommTimeouts(s->hcom, &cto)) {
2164 fprintf(stderr, "Failed SetCommTimeouts\n");
2165 goto fail;
2168 if (!ClearCommError(s->hcom, &err, &comstat)) {
2169 fprintf(stderr, "Failed ClearCommError\n");
2170 goto fail;
2172 qemu_add_polling_cb(win_chr_poll, chr);
2173 return 0;
2175 fail:
2176 win_chr_close(chr);
2177 return -1;
2180 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2182 WinCharState *s = chr->opaque;
2183 DWORD len, ret, size, err;
2185 len = len1;
2186 ZeroMemory(&s->osend, sizeof(s->osend));
2187 s->osend.hEvent = s->hsend;
2188 while (len > 0) {
2189 if (s->hsend)
2190 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2191 else
2192 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2193 if (!ret) {
2194 err = GetLastError();
2195 if (err == ERROR_IO_PENDING) {
2196 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2197 if (ret) {
2198 buf += size;
2199 len -= size;
2200 } else {
2201 break;
2203 } else {
2204 break;
2206 } else {
2207 buf += size;
2208 len -= size;
2211 return len1 - len;
2214 static int win_chr_read_poll(CharDriverState *chr)
2216 WinCharState *s = chr->opaque;
2218 s->max_size = qemu_chr_can_read(chr);
2219 return s->max_size;
2222 static void win_chr_readfile(CharDriverState *chr)
2224 WinCharState *s = chr->opaque;
2225 int ret, err;
2226 uint8_t buf[1024];
2227 DWORD size;
2229 ZeroMemory(&s->orecv, sizeof(s->orecv));
2230 s->orecv.hEvent = s->hrecv;
2231 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2232 if (!ret) {
2233 err = GetLastError();
2234 if (err == ERROR_IO_PENDING) {
2235 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2239 if (size > 0) {
2240 qemu_chr_read(chr, buf, size);
2244 static void win_chr_read(CharDriverState *chr)
2246 WinCharState *s = chr->opaque;
2248 if (s->len > s->max_size)
2249 s->len = s->max_size;
2250 if (s->len == 0)
2251 return;
2253 win_chr_readfile(chr);
2256 static int win_chr_poll(void *opaque)
2258 CharDriverState *chr = opaque;
2259 WinCharState *s = chr->opaque;
2260 COMSTAT status;
2261 DWORD comerr;
2263 ClearCommError(s->hcom, &comerr, &status);
2264 if (status.cbInQue > 0) {
2265 s->len = status.cbInQue;
2266 win_chr_read_poll(chr);
2267 win_chr_read(chr);
2268 return 1;
2270 return 0;
2273 static CharDriverState *qemu_chr_open_win(const char *filename)
2275 CharDriverState *chr;
2276 WinCharState *s;
2278 chr = qemu_mallocz(sizeof(CharDriverState));
2279 if (!chr)
2280 return NULL;
2281 s = qemu_mallocz(sizeof(WinCharState));
2282 if (!s) {
2283 free(chr);
2284 return NULL;
2286 chr->opaque = s;
2287 chr->chr_write = win_chr_write;
2288 chr->chr_close = win_chr_close;
2290 if (win_chr_init(chr, filename) < 0) {
2291 free(s);
2292 free(chr);
2293 return NULL;
2295 qemu_chr_reset(chr);
2296 return chr;
2299 static int win_chr_pipe_poll(void *opaque)
2301 CharDriverState *chr = opaque;
2302 WinCharState *s = chr->opaque;
2303 DWORD size;
2305 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2306 if (size > 0) {
2307 s->len = size;
2308 win_chr_read_poll(chr);
2309 win_chr_read(chr);
2310 return 1;
2312 return 0;
2315 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2317 WinCharState *s = chr->opaque;
2318 OVERLAPPED ov;
2319 int ret;
2320 DWORD size;
2321 char openname[256];
2323 s->fpipe = TRUE;
2325 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2326 if (!s->hsend) {
2327 fprintf(stderr, "Failed CreateEvent\n");
2328 goto fail;
2330 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2331 if (!s->hrecv) {
2332 fprintf(stderr, "Failed CreateEvent\n");
2333 goto fail;
2336 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2337 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2338 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2339 PIPE_WAIT,
2340 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2341 if (s->hcom == INVALID_HANDLE_VALUE) {
2342 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2343 s->hcom = NULL;
2344 goto fail;
2347 ZeroMemory(&ov, sizeof(ov));
2348 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2349 ret = ConnectNamedPipe(s->hcom, &ov);
2350 if (ret) {
2351 fprintf(stderr, "Failed ConnectNamedPipe\n");
2352 goto fail;
2355 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2356 if (!ret) {
2357 fprintf(stderr, "Failed GetOverlappedResult\n");
2358 if (ov.hEvent) {
2359 CloseHandle(ov.hEvent);
2360 ov.hEvent = NULL;
2362 goto fail;
2365 if (ov.hEvent) {
2366 CloseHandle(ov.hEvent);
2367 ov.hEvent = NULL;
2369 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2370 return 0;
2372 fail:
2373 win_chr_close(chr);
2374 return -1;
2378 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2380 CharDriverState *chr;
2381 WinCharState *s;
2383 chr = qemu_mallocz(sizeof(CharDriverState));
2384 if (!chr)
2385 return NULL;
2386 s = qemu_mallocz(sizeof(WinCharState));
2387 if (!s) {
2388 free(chr);
2389 return NULL;
2391 chr->opaque = s;
2392 chr->chr_write = win_chr_write;
2393 chr->chr_close = win_chr_close;
2395 if (win_chr_pipe_init(chr, filename) < 0) {
2396 free(s);
2397 free(chr);
2398 return NULL;
2400 qemu_chr_reset(chr);
2401 return chr;
2404 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2406 CharDriverState *chr;
2407 WinCharState *s;
2409 chr = qemu_mallocz(sizeof(CharDriverState));
2410 if (!chr)
2411 return NULL;
2412 s = qemu_mallocz(sizeof(WinCharState));
2413 if (!s) {
2414 free(chr);
2415 return NULL;
2417 s->hcom = fd_out;
2418 chr->opaque = s;
2419 chr->chr_write = win_chr_write;
2420 qemu_chr_reset(chr);
2421 return chr;
2424 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2426 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2429 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2431 HANDLE fd_out;
2433 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2434 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2435 if (fd_out == INVALID_HANDLE_VALUE)
2436 return NULL;
2438 return qemu_chr_open_win_file(fd_out);
2440 #endif
2442 /***********************************************************/
2443 /* UDP Net console */
2445 typedef struct {
2446 int fd;
2447 struct sockaddr_in daddr;
2448 char buf[1024];
2449 int bufcnt;
2450 int bufptr;
2451 int max_size;
2452 } NetCharDriver;
2454 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2456 NetCharDriver *s = chr->opaque;
2458 return sendto(s->fd, buf, len, 0,
2459 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2462 static int udp_chr_read_poll(void *opaque)
2464 CharDriverState *chr = opaque;
2465 NetCharDriver *s = chr->opaque;
2467 s->max_size = qemu_chr_can_read(chr);
2469 /* If there were any stray characters in the queue process them
2470 * first
2472 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2473 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2474 s->bufptr++;
2475 s->max_size = qemu_chr_can_read(chr);
2477 return s->max_size;
2480 static void udp_chr_read(void *opaque)
2482 CharDriverState *chr = opaque;
2483 NetCharDriver *s = chr->opaque;
2485 if (s->max_size == 0)
2486 return;
2487 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2488 s->bufptr = s->bufcnt;
2489 if (s->bufcnt <= 0)
2490 return;
2492 s->bufptr = 0;
2493 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2494 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2495 s->bufptr++;
2496 s->max_size = qemu_chr_can_read(chr);
2500 static void udp_chr_update_read_handler(CharDriverState *chr)
2502 NetCharDriver *s = chr->opaque;
2504 if (s->fd >= 0) {
2505 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2506 udp_chr_read, NULL, chr);
2510 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2511 #ifndef _WIN32
2512 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2513 #endif
2514 int parse_host_src_port(struct sockaddr_in *haddr,
2515 struct sockaddr_in *saddr,
2516 const char *str);
2518 static CharDriverState *qemu_chr_open_udp(const char *def)
2520 CharDriverState *chr = NULL;
2521 NetCharDriver *s = NULL;
2522 int fd = -1;
2523 struct sockaddr_in saddr;
2525 chr = qemu_mallocz(sizeof(CharDriverState));
2526 if (!chr)
2527 goto return_err;
2528 s = qemu_mallocz(sizeof(NetCharDriver));
2529 if (!s)
2530 goto return_err;
2532 fd = socket(PF_INET, SOCK_DGRAM, 0);
2533 if (fd < 0) {
2534 perror("socket(PF_INET, SOCK_DGRAM)");
2535 goto return_err;
2538 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2539 printf("Could not parse: %s\n", def);
2540 goto return_err;
2543 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2545 perror("bind");
2546 goto return_err;
2549 s->fd = fd;
2550 s->bufcnt = 0;
2551 s->bufptr = 0;
2552 chr->opaque = s;
2553 chr->chr_write = udp_chr_write;
2554 chr->chr_update_read_handler = udp_chr_update_read_handler;
2555 return chr;
2557 return_err:
2558 if (chr)
2559 free(chr);
2560 if (s)
2561 free(s);
2562 if (fd >= 0)
2563 closesocket(fd);
2564 return NULL;
2567 /***********************************************************/
2568 /* TCP Net console */
2570 typedef struct {
2571 int fd, listen_fd;
2572 int connected;
2573 int max_size;
2574 int do_telnetopt;
2575 int do_nodelay;
2576 int is_unix;
2577 } TCPCharDriver;
2579 static void tcp_chr_accept(void *opaque);
2581 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2583 TCPCharDriver *s = chr->opaque;
2584 if (s->connected) {
2585 return send_all(s->fd, buf, len);
2586 } else {
2587 /* XXX: indicate an error ? */
2588 return len;
2592 static int tcp_chr_read_poll(void *opaque)
2594 CharDriverState *chr = opaque;
2595 TCPCharDriver *s = chr->opaque;
2596 if (!s->connected)
2597 return 0;
2598 s->max_size = qemu_chr_can_read(chr);
2599 return s->max_size;
2602 #define IAC 255
2603 #define IAC_BREAK 243
2604 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2605 TCPCharDriver *s,
2606 char *buf, int *size)
2608 /* Handle any telnet client's basic IAC options to satisfy char by
2609 * char mode with no echo. All IAC options will be removed from
2610 * the buf and the do_telnetopt variable will be used to track the
2611 * state of the width of the IAC information.
2613 * IAC commands come in sets of 3 bytes with the exception of the
2614 * "IAC BREAK" command and the double IAC.
2617 int i;
2618 int j = 0;
2620 for (i = 0; i < *size; i++) {
2621 if (s->do_telnetopt > 1) {
2622 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2623 /* Double IAC means send an IAC */
2624 if (j != i)
2625 buf[j] = buf[i];
2626 j++;
2627 s->do_telnetopt = 1;
2628 } else {
2629 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2630 /* Handle IAC break commands by sending a serial break */
2631 qemu_chr_event(chr, CHR_EVENT_BREAK);
2632 s->do_telnetopt++;
2634 s->do_telnetopt++;
2636 if (s->do_telnetopt >= 4) {
2637 s->do_telnetopt = 1;
2639 } else {
2640 if ((unsigned char)buf[i] == IAC) {
2641 s->do_telnetopt = 2;
2642 } else {
2643 if (j != i)
2644 buf[j] = buf[i];
2645 j++;
2649 *size = j;
2652 static void tcp_chr_read(void *opaque)
2654 CharDriverState *chr = opaque;
2655 TCPCharDriver *s = chr->opaque;
2656 uint8_t buf[1024];
2657 int len, size;
2659 if (!s->connected || s->max_size <= 0)
2660 return;
2661 len = sizeof(buf);
2662 if (len > s->max_size)
2663 len = s->max_size;
2664 size = recv(s->fd, buf, len, 0);
2665 if (size == 0) {
2666 /* connection closed */
2667 s->connected = 0;
2668 if (s->listen_fd >= 0) {
2669 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2671 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2672 closesocket(s->fd);
2673 s->fd = -1;
2674 } else if (size > 0) {
2675 if (s->do_telnetopt)
2676 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2677 if (size > 0)
2678 qemu_chr_read(chr, buf, size);
2682 static void tcp_chr_connect(void *opaque)
2684 CharDriverState *chr = opaque;
2685 TCPCharDriver *s = chr->opaque;
2687 s->connected = 1;
2688 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2689 tcp_chr_read, NULL, chr);
2690 qemu_chr_reset(chr);
2693 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2694 static void tcp_chr_telnet_init(int fd)
2696 char buf[3];
2697 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2698 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2699 send(fd, (char *)buf, 3, 0);
2700 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2701 send(fd, (char *)buf, 3, 0);
2702 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2703 send(fd, (char *)buf, 3, 0);
2704 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2705 send(fd, (char *)buf, 3, 0);
2708 static void socket_set_nodelay(int fd)
2710 int val = 1;
2711 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2714 static void tcp_chr_accept(void *opaque)
2716 CharDriverState *chr = opaque;
2717 TCPCharDriver *s = chr->opaque;
2718 struct sockaddr_in saddr;
2719 #ifndef _WIN32
2720 struct sockaddr_un uaddr;
2721 #endif
2722 struct sockaddr *addr;
2723 socklen_t len;
2724 int fd;
2726 for(;;) {
2727 #ifndef _WIN32
2728 if (s->is_unix) {
2729 len = sizeof(uaddr);
2730 addr = (struct sockaddr *)&uaddr;
2731 } else
2732 #endif
2734 len = sizeof(saddr);
2735 addr = (struct sockaddr *)&saddr;
2737 fd = accept(s->listen_fd, addr, &len);
2738 if (fd < 0 && errno != EINTR) {
2739 return;
2740 } else if (fd >= 0) {
2741 if (s->do_telnetopt)
2742 tcp_chr_telnet_init(fd);
2743 break;
2746 socket_set_nonblock(fd);
2747 if (s->do_nodelay)
2748 socket_set_nodelay(fd);
2749 s->fd = fd;
2750 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2751 tcp_chr_connect(chr);
2754 static void tcp_chr_close(CharDriverState *chr)
2756 TCPCharDriver *s = chr->opaque;
2757 if (s->fd >= 0)
2758 closesocket(s->fd);
2759 if (s->listen_fd >= 0)
2760 closesocket(s->listen_fd);
2761 qemu_free(s);
2764 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2765 int is_telnet,
2766 int is_unix)
2768 CharDriverState *chr = NULL;
2769 TCPCharDriver *s = NULL;
2770 int fd = -1, ret, err, val;
2771 int is_listen = 0;
2772 int is_waitconnect = 1;
2773 int do_nodelay = 0;
2774 const char *ptr;
2775 struct sockaddr_in saddr;
2776 #ifndef _WIN32
2777 struct sockaddr_un uaddr;
2778 #endif
2779 struct sockaddr *addr;
2780 socklen_t addrlen;
2782 #ifndef _WIN32
2783 if (is_unix) {
2784 addr = (struct sockaddr *)&uaddr;
2785 addrlen = sizeof(uaddr);
2786 if (parse_unix_path(&uaddr, host_str) < 0)
2787 goto fail;
2788 } else
2789 #endif
2791 addr = (struct sockaddr *)&saddr;
2792 addrlen = sizeof(saddr);
2793 if (parse_host_port(&saddr, host_str) < 0)
2794 goto fail;
2797 ptr = host_str;
2798 while((ptr = strchr(ptr,','))) {
2799 ptr++;
2800 if (!strncmp(ptr,"server",6)) {
2801 is_listen = 1;
2802 } else if (!strncmp(ptr,"nowait",6)) {
2803 is_waitconnect = 0;
2804 } else if (!strncmp(ptr,"nodelay",6)) {
2805 do_nodelay = 1;
2806 } else {
2807 printf("Unknown option: %s\n", ptr);
2808 goto fail;
2811 if (!is_listen)
2812 is_waitconnect = 0;
2814 chr = qemu_mallocz(sizeof(CharDriverState));
2815 if (!chr)
2816 goto fail;
2817 s = qemu_mallocz(sizeof(TCPCharDriver));
2818 if (!s)
2819 goto fail;
2821 #ifndef _WIN32
2822 if (is_unix)
2823 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2824 else
2825 #endif
2826 fd = socket(PF_INET, SOCK_STREAM, 0);
2828 if (fd < 0)
2829 goto fail;
2831 if (!is_waitconnect)
2832 socket_set_nonblock(fd);
2834 s->connected = 0;
2835 s->fd = -1;
2836 s->listen_fd = -1;
2837 s->is_unix = is_unix;
2838 s->do_nodelay = do_nodelay && !is_unix;
2840 chr->opaque = s;
2841 chr->chr_write = tcp_chr_write;
2842 chr->chr_close = tcp_chr_close;
2844 if (is_listen) {
2845 /* allow fast reuse */
2846 #ifndef _WIN32
2847 if (is_unix) {
2848 char path[109];
2849 strncpy(path, uaddr.sun_path, 108);
2850 path[108] = 0;
2851 unlink(path);
2852 } else
2853 #endif
2855 val = 1;
2856 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2859 ret = bind(fd, addr, addrlen);
2860 if (ret < 0)
2861 goto fail;
2863 ret = listen(fd, 0);
2864 if (ret < 0)
2865 goto fail;
2867 s->listen_fd = fd;
2868 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2869 if (is_telnet)
2870 s->do_telnetopt = 1;
2871 } else {
2872 for(;;) {
2873 ret = connect(fd, addr, addrlen);
2874 if (ret < 0) {
2875 err = socket_error();
2876 if (err == EINTR || err == EWOULDBLOCK) {
2877 } else if (err == EINPROGRESS) {
2878 break;
2879 #ifdef _WIN32
2880 } else if (err == WSAEALREADY) {
2881 break;
2882 #endif
2883 } else {
2884 goto fail;
2886 } else {
2887 s->connected = 1;
2888 break;
2891 s->fd = fd;
2892 socket_set_nodelay(fd);
2893 if (s->connected)
2894 tcp_chr_connect(chr);
2895 else
2896 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2899 if (is_listen && is_waitconnect) {
2900 printf("QEMU waiting for connection on: %s\n", host_str);
2901 tcp_chr_accept(chr);
2902 socket_set_nonblock(s->listen_fd);
2905 return chr;
2906 fail:
2907 if (fd >= 0)
2908 closesocket(fd);
2909 qemu_free(s);
2910 qemu_free(chr);
2911 return NULL;
2914 CharDriverState *qemu_chr_open(const char *filename)
2916 const char *p;
2918 if (!strcmp(filename, "vc")) {
2919 return text_console_init(&display_state);
2920 } else if (!strcmp(filename, "null")) {
2921 return qemu_chr_open_null();
2922 } else
2923 if (strstart(filename, "tcp:", &p)) {
2924 return qemu_chr_open_tcp(p, 0, 0);
2925 } else
2926 if (strstart(filename, "telnet:", &p)) {
2927 return qemu_chr_open_tcp(p, 1, 0);
2928 } else
2929 if (strstart(filename, "udp:", &p)) {
2930 return qemu_chr_open_udp(p);
2931 } else
2932 if (strstart(filename, "mon:", &p)) {
2933 CharDriverState *drv = qemu_chr_open(p);
2934 if (drv) {
2935 drv = qemu_chr_open_mux(drv);
2936 monitor_init(drv, !nographic);
2937 return drv;
2939 printf("Unable to open driver: %s\n", p);
2940 return 0;
2941 } else
2942 #ifndef _WIN32
2943 if (strstart(filename, "unix:", &p)) {
2944 return qemu_chr_open_tcp(p, 0, 1);
2945 } else if (strstart(filename, "file:", &p)) {
2946 return qemu_chr_open_file_out(p);
2947 } else if (strstart(filename, "pipe:", &p)) {
2948 return qemu_chr_open_pipe(p);
2949 } else if (!strcmp(filename, "pty")) {
2950 return qemu_chr_open_pty();
2951 } else if (!strcmp(filename, "stdio")) {
2952 return qemu_chr_open_stdio();
2953 } else
2954 #endif
2955 #if defined(__linux__)
2956 if (strstart(filename, "/dev/parport", NULL)) {
2957 return qemu_chr_open_pp(filename);
2958 } else
2959 if (strstart(filename, "/dev/", NULL)) {
2960 return qemu_chr_open_tty(filename);
2961 } else
2962 #endif
2963 #ifdef _WIN32
2964 if (strstart(filename, "COM", NULL)) {
2965 return qemu_chr_open_win(filename);
2966 } else
2967 if (strstart(filename, "pipe:", &p)) {
2968 return qemu_chr_open_win_pipe(p);
2969 } else
2970 if (strstart(filename, "con:", NULL)) {
2971 return qemu_chr_open_win_con(filename);
2972 } else
2973 if (strstart(filename, "file:", &p)) {
2974 return qemu_chr_open_win_file_out(p);
2976 #endif
2978 return NULL;
2982 void qemu_chr_close(CharDriverState *chr)
2984 if (chr->chr_close)
2985 chr->chr_close(chr);
2988 /***********************************************************/
2989 /* network device redirectors */
2991 void hex_dump(FILE *f, const uint8_t *buf, int size)
2993 int len, i, j, c;
2995 for(i=0;i<size;i+=16) {
2996 len = size - i;
2997 if (len > 16)
2998 len = 16;
2999 fprintf(f, "%08x ", i);
3000 for(j=0;j<16;j++) {
3001 if (j < len)
3002 fprintf(f, " %02x", buf[i+j]);
3003 else
3004 fprintf(f, " ");
3006 fprintf(f, " ");
3007 for(j=0;j<len;j++) {
3008 c = buf[i+j];
3009 if (c < ' ' || c > '~')
3010 c = '.';
3011 fprintf(f, "%c", c);
3013 fprintf(f, "\n");
3017 static int parse_macaddr(uint8_t *macaddr, const char *p)
3019 int i;
3020 for(i = 0; i < 6; i++) {
3021 macaddr[i] = strtol(p, (char **)&p, 16);
3022 if (i == 5) {
3023 if (*p != '\0')
3024 return -1;
3025 } else {
3026 if (*p != ':')
3027 return -1;
3028 p++;
3031 return 0;
3034 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3036 const char *p, *p1;
3037 int len;
3038 p = *pp;
3039 p1 = strchr(p, sep);
3040 if (!p1)
3041 return -1;
3042 len = p1 - p;
3043 p1++;
3044 if (buf_size > 0) {
3045 if (len > buf_size - 1)
3046 len = buf_size - 1;
3047 memcpy(buf, p, len);
3048 buf[len] = '\0';
3050 *pp = p1;
3051 return 0;
3054 int parse_host_src_port(struct sockaddr_in *haddr,
3055 struct sockaddr_in *saddr,
3056 const char *input_str)
3058 char *str = strdup(input_str);
3059 char *host_str = str;
3060 char *src_str;
3061 char *ptr;
3064 * Chop off any extra arguments at the end of the string which
3065 * would start with a comma, then fill in the src port information
3066 * if it was provided else use the "any address" and "any port".
3068 if ((ptr = strchr(str,',')))
3069 *ptr = '\0';
3071 if ((src_str = strchr(input_str,'@'))) {
3072 *src_str = '\0';
3073 src_str++;
3076 if (parse_host_port(haddr, host_str) < 0)
3077 goto fail;
3079 if (!src_str || *src_str == '\0')
3080 src_str = ":0";
3082 if (parse_host_port(saddr, src_str) < 0)
3083 goto fail;
3085 free(str);
3086 return(0);
3088 fail:
3089 free(str);
3090 return -1;
3093 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3095 char buf[512];
3096 struct hostent *he;
3097 const char *p, *r;
3098 int port;
3100 p = str;
3101 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3102 return -1;
3103 saddr->sin_family = AF_INET;
3104 if (buf[0] == '\0') {
3105 saddr->sin_addr.s_addr = 0;
3106 } else {
3107 if (isdigit(buf[0])) {
3108 if (!inet_aton(buf, &saddr->sin_addr))
3109 return -1;
3110 } else {
3111 if ((he = gethostbyname(buf)) == NULL)
3112 return - 1;
3113 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3116 port = strtol(p, (char **)&r, 0);
3117 if (r == p)
3118 return -1;
3119 saddr->sin_port = htons(port);
3120 return 0;
3123 #ifndef _WIN32
3124 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3126 const char *p;
3127 int len;
3129 len = MIN(108, strlen(str));
3130 p = strchr(str, ',');
3131 if (p)
3132 len = MIN(len, p - str);
3134 memset(uaddr, 0, sizeof(*uaddr));
3136 uaddr->sun_family = AF_UNIX;
3137 memcpy(uaddr->sun_path, str, len);
3139 return 0;
3141 #endif
3143 /* find or alloc a new VLAN */
3144 VLANState *qemu_find_vlan(int id)
3146 VLANState **pvlan, *vlan;
3147 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3148 if (vlan->id == id)
3149 return vlan;
3151 vlan = qemu_mallocz(sizeof(VLANState));
3152 if (!vlan)
3153 return NULL;
3154 vlan->id = id;
3155 vlan->next = NULL;
3156 pvlan = &first_vlan;
3157 while (*pvlan != NULL)
3158 pvlan = &(*pvlan)->next;
3159 *pvlan = vlan;
3160 return vlan;
3163 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3164 IOReadHandler *fd_read,
3165 IOCanRWHandler *fd_can_read,
3166 void *opaque)
3168 VLANClientState *vc, **pvc;
3169 vc = qemu_mallocz(sizeof(VLANClientState));
3170 if (!vc)
3171 return NULL;
3172 vc->fd_read = fd_read;
3173 vc->fd_can_read = fd_can_read;
3174 vc->opaque = opaque;
3175 vc->vlan = vlan;
3177 vc->next = NULL;
3178 pvc = &vlan->first_client;
3179 while (*pvc != NULL)
3180 pvc = &(*pvc)->next;
3181 *pvc = vc;
3182 return vc;
3185 int qemu_can_send_packet(VLANClientState *vc1)
3187 VLANState *vlan = vc1->vlan;
3188 VLANClientState *vc;
3190 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3191 if (vc != vc1) {
3192 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3193 return 0;
3196 return 1;
3199 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3201 VLANState *vlan = vc1->vlan;
3202 VLANClientState *vc;
3204 #if 0
3205 printf("vlan %d send:\n", vlan->id);
3206 hex_dump(stdout, buf, size);
3207 #endif
3208 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3209 if (vc != vc1) {
3210 vc->fd_read(vc->opaque, buf, size);
3215 #if defined(CONFIG_SLIRP)
3217 /* slirp network adapter */
3219 static int slirp_inited;
3220 static VLANClientState *slirp_vc;
3222 int slirp_can_output(void)
3224 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3227 void slirp_output(const uint8_t *pkt, int pkt_len)
3229 #if 0
3230 printf("slirp output:\n");
3231 hex_dump(stdout, pkt, pkt_len);
3232 #endif
3233 if (!slirp_vc)
3234 return;
3235 qemu_send_packet(slirp_vc, pkt, pkt_len);
3238 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3240 #if 0
3241 printf("slirp input:\n");
3242 hex_dump(stdout, buf, size);
3243 #endif
3244 slirp_input(buf, size);
3247 static int net_slirp_init(VLANState *vlan)
3249 if (!slirp_inited) {
3250 slirp_inited = 1;
3251 slirp_init();
3253 slirp_vc = qemu_new_vlan_client(vlan,
3254 slirp_receive, NULL, NULL);
3255 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3256 return 0;
3259 static void net_slirp_redir(const char *redir_str)
3261 int is_udp;
3262 char buf[256], *r;
3263 const char *p;
3264 struct in_addr guest_addr;
3265 int host_port, guest_port;
3267 if (!slirp_inited) {
3268 slirp_inited = 1;
3269 slirp_init();
3272 p = redir_str;
3273 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3274 goto fail;
3275 if (!strcmp(buf, "tcp")) {
3276 is_udp = 0;
3277 } else if (!strcmp(buf, "udp")) {
3278 is_udp = 1;
3279 } else {
3280 goto fail;
3283 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3284 goto fail;
3285 host_port = strtol(buf, &r, 0);
3286 if (r == buf)
3287 goto fail;
3289 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3290 goto fail;
3291 if (buf[0] == '\0') {
3292 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3294 if (!inet_aton(buf, &guest_addr))
3295 goto fail;
3297 guest_port = strtol(p, &r, 0);
3298 if (r == p)
3299 goto fail;
3301 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3302 fprintf(stderr, "qemu: could not set up redirection\n");
3303 exit(1);
3305 return;
3306 fail:
3307 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3308 exit(1);
3311 #ifndef _WIN32
3313 char smb_dir[1024];
3315 static void smb_exit(void)
3317 DIR *d;
3318 struct dirent *de;
3319 char filename[1024];
3321 /* erase all the files in the directory */
3322 d = opendir(smb_dir);
3323 for(;;) {
3324 de = readdir(d);
3325 if (!de)
3326 break;
3327 if (strcmp(de->d_name, ".") != 0 &&
3328 strcmp(de->d_name, "..") != 0) {
3329 snprintf(filename, sizeof(filename), "%s/%s",
3330 smb_dir, de->d_name);
3331 unlink(filename);
3334 closedir(d);
3335 rmdir(smb_dir);
3338 /* automatic user mode samba server configuration */
3339 void net_slirp_smb(const char *exported_dir)
3341 char smb_conf[1024];
3342 char smb_cmdline[1024];
3343 FILE *f;
3345 if (!slirp_inited) {
3346 slirp_inited = 1;
3347 slirp_init();
3350 /* XXX: better tmp dir construction */
3351 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3352 if (mkdir(smb_dir, 0700) < 0) {
3353 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3354 exit(1);
3356 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3358 f = fopen(smb_conf, "w");
3359 if (!f) {
3360 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3361 exit(1);
3363 fprintf(f,
3364 "[global]\n"
3365 "private dir=%s\n"
3366 "smb ports=0\n"
3367 "socket address=127.0.0.1\n"
3368 "pid directory=%s\n"
3369 "lock directory=%s\n"
3370 "log file=%s/log.smbd\n"
3371 "smb passwd file=%s/smbpasswd\n"
3372 "security = share\n"
3373 "[qemu]\n"
3374 "path=%s\n"
3375 "read only=no\n"
3376 "guest ok=yes\n",
3377 smb_dir,
3378 smb_dir,
3379 smb_dir,
3380 smb_dir,
3381 smb_dir,
3382 exported_dir
3384 fclose(f);
3385 atexit(smb_exit);
3387 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3388 SMBD_COMMAND, smb_conf);
3390 slirp_add_exec(0, smb_cmdline, 4, 139);
3393 #endif /* !defined(_WIN32) */
3395 #endif /* CONFIG_SLIRP */
3397 #if !defined(_WIN32)
3399 typedef struct TAPState {
3400 VLANClientState *vc;
3401 int fd;
3402 } TAPState;
3404 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3406 TAPState *s = opaque;
3407 int ret;
3408 for(;;) {
3409 ret = write(s->fd, buf, size);
3410 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3411 } else {
3412 break;
3417 static void tap_send(void *opaque)
3419 TAPState *s = opaque;
3420 uint8_t buf[4096];
3421 int size;
3423 #ifdef __sun__
3424 struct strbuf sbuf;
3425 int f = 0;
3426 sbuf.maxlen = sizeof(buf);
3427 sbuf.buf = buf;
3428 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3429 #else
3430 size = read(s->fd, buf, sizeof(buf));
3431 #endif
3432 if (size > 0) {
3433 qemu_send_packet(s->vc, buf, size);
3437 /* fd support */
3439 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3441 TAPState *s;
3443 s = qemu_mallocz(sizeof(TAPState));
3444 if (!s)
3445 return NULL;
3446 s->fd = fd;
3447 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3448 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3449 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3450 return s;
3453 #ifdef _BSD
3454 static int tap_open(char *ifname, int ifname_size)
3456 int fd;
3457 char *dev;
3458 struct stat s;
3460 fd = open("/dev/tap", O_RDWR);
3461 if (fd < 0) {
3462 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3463 return -1;
3466 fstat(fd, &s);
3467 dev = devname(s.st_rdev, S_IFCHR);
3468 pstrcpy(ifname, ifname_size, dev);
3470 fcntl(fd, F_SETFL, O_NONBLOCK);
3471 return fd;
3473 #elif defined(__sun__)
3474 #define TUNNEWPPA (('T'<<16) | 0x0001)
3476 * Allocate TAP device, returns opened fd.
3477 * Stores dev name in the first arg(must be large enough).
3479 int tap_alloc(char *dev)
3481 int tap_fd, if_fd, ppa = -1;
3482 static int ip_fd = 0;
3483 char *ptr;
3485 static int arp_fd = 0;
3486 int ip_muxid, arp_muxid;
3487 struct strioctl strioc_if, strioc_ppa;
3488 int link_type = I_PLINK;;
3489 struct lifreq ifr;
3490 char actual_name[32] = "";
3492 memset(&ifr, 0x0, sizeof(ifr));
3494 if( *dev ){
3495 ptr = dev;
3496 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3497 ppa = atoi(ptr);
3500 /* Check if IP device was opened */
3501 if( ip_fd )
3502 close(ip_fd);
3504 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3505 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3506 return -1;
3509 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3510 syslog(LOG_ERR, "Can't open /dev/tap");
3511 return -1;
3514 /* Assign a new PPA and get its unit number. */
3515 strioc_ppa.ic_cmd = TUNNEWPPA;
3516 strioc_ppa.ic_timout = 0;
3517 strioc_ppa.ic_len = sizeof(ppa);
3518 strioc_ppa.ic_dp = (char *)&ppa;
3519 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3520 syslog (LOG_ERR, "Can't assign new interface");
3522 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3523 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3524 return -1;
3526 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3527 syslog(LOG_ERR, "Can't push IP module");
3528 return -1;
3531 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3532 syslog(LOG_ERR, "Can't get flags\n");
3534 snprintf (actual_name, 32, "tap%d", ppa);
3535 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3537 ifr.lifr_ppa = ppa;
3538 /* Assign ppa according to the unit number returned by tun device */
3540 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3541 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3542 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3543 syslog (LOG_ERR, "Can't get flags\n");
3544 /* Push arp module to if_fd */
3545 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3546 syslog (LOG_ERR, "Can't push ARP module (2)");
3548 /* Push arp module to ip_fd */
3549 if (ioctl (ip_fd, I_POP, NULL) < 0)
3550 syslog (LOG_ERR, "I_POP failed\n");
3551 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3552 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3553 /* Open arp_fd */
3554 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3555 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3557 /* Set ifname to arp */
3558 strioc_if.ic_cmd = SIOCSLIFNAME;
3559 strioc_if.ic_timout = 0;
3560 strioc_if.ic_len = sizeof(ifr);
3561 strioc_if.ic_dp = (char *)&ifr;
3562 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3563 syslog (LOG_ERR, "Can't set ifname to arp\n");
3566 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3567 syslog(LOG_ERR, "Can't link TAP device to IP");
3568 return -1;
3571 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3572 syslog (LOG_ERR, "Can't link TAP device to ARP");
3574 close (if_fd);
3576 memset(&ifr, 0x0, sizeof(ifr));
3577 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3578 ifr.lifr_ip_muxid = ip_muxid;
3579 ifr.lifr_arp_muxid = arp_muxid;
3581 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3583 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3584 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3585 syslog (LOG_ERR, "Can't set multiplexor id");
3588 sprintf(dev, "tap%d", ppa);
3589 return tap_fd;
3592 static int tap_open(char *ifname, int ifname_size)
3594 char dev[10]="";
3595 int fd;
3596 if( (fd = tap_alloc(dev)) < 0 ){
3597 fprintf(stderr, "Cannot allocate TAP device\n");
3598 return -1;
3600 pstrcpy(ifname, ifname_size, dev);
3601 fcntl(fd, F_SETFL, O_NONBLOCK);
3602 return fd;
3604 #else
3605 static int tap_open(char *ifname, int ifname_size)
3607 struct ifreq ifr;
3608 int fd, ret;
3610 fd = open("/dev/net/tun", O_RDWR);
3611 if (fd < 0) {
3612 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3613 return -1;
3615 memset(&ifr, 0, sizeof(ifr));
3616 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3617 if (ifname[0] != '\0')
3618 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3619 else
3620 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3621 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3622 if (ret != 0) {
3623 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3624 close(fd);
3625 return -1;
3627 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3628 fcntl(fd, F_SETFL, O_NONBLOCK);
3629 return fd;
3631 #endif
3633 static int net_tap_init(VLANState *vlan, const char *ifname1,
3634 const char *setup_script)
3636 TAPState *s;
3637 int pid, status, fd;
3638 char *args[3];
3639 char **parg;
3640 char ifname[128];
3642 if (ifname1 != NULL)
3643 pstrcpy(ifname, sizeof(ifname), ifname1);
3644 else
3645 ifname[0] = '\0';
3646 fd = tap_open(ifname, sizeof(ifname));
3647 if (fd < 0)
3648 return -1;
3650 if (!setup_script || !strcmp(setup_script, "no"))
3651 setup_script = "";
3652 if (setup_script[0] != '\0') {
3653 /* try to launch network init script */
3654 pid = fork();
3655 if (pid >= 0) {
3656 if (pid == 0) {
3657 int open_max = sysconf (_SC_OPEN_MAX), i;
3658 for (i = 0; i < open_max; i++)
3659 if (i != STDIN_FILENO &&
3660 i != STDOUT_FILENO &&
3661 i != STDERR_FILENO &&
3662 i != fd)
3663 close(i);
3665 parg = args;
3666 *parg++ = (char *)setup_script;
3667 *parg++ = ifname;
3668 *parg++ = NULL;
3669 execv(setup_script, args);
3670 _exit(1);
3672 while (waitpid(pid, &status, 0) != pid);
3673 if (!WIFEXITED(status) ||
3674 WEXITSTATUS(status) != 0) {
3675 fprintf(stderr, "%s: could not launch network script\n",
3676 setup_script);
3677 return -1;
3681 s = net_tap_fd_init(vlan, fd);
3682 if (!s)
3683 return -1;
3684 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3685 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3686 return 0;
3689 #endif /* !_WIN32 */
3691 /* network connection */
3692 typedef struct NetSocketState {
3693 VLANClientState *vc;
3694 int fd;
3695 int state; /* 0 = getting length, 1 = getting data */
3696 int index;
3697 int packet_len;
3698 uint8_t buf[4096];
3699 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3700 } NetSocketState;
3702 typedef struct NetSocketListenState {
3703 VLANState *vlan;
3704 int fd;
3705 } NetSocketListenState;
3707 /* XXX: we consider we can send the whole packet without blocking */
3708 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3710 NetSocketState *s = opaque;
3711 uint32_t len;
3712 len = htonl(size);
3714 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3715 send_all(s->fd, buf, size);
3718 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3720 NetSocketState *s = opaque;
3721 sendto(s->fd, buf, size, 0,
3722 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3725 static void net_socket_send(void *opaque)
3727 NetSocketState *s = opaque;
3728 int l, size, err;
3729 uint8_t buf1[4096];
3730 const uint8_t *buf;
3732 size = recv(s->fd, buf1, sizeof(buf1), 0);
3733 if (size < 0) {
3734 err = socket_error();
3735 if (err != EWOULDBLOCK)
3736 goto eoc;
3737 } else if (size == 0) {
3738 /* end of connection */
3739 eoc:
3740 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3741 closesocket(s->fd);
3742 return;
3744 buf = buf1;
3745 while (size > 0) {
3746 /* reassemble a packet from the network */
3747 switch(s->state) {
3748 case 0:
3749 l = 4 - s->index;
3750 if (l > size)
3751 l = size;
3752 memcpy(s->buf + s->index, buf, l);
3753 buf += l;
3754 size -= l;
3755 s->index += l;
3756 if (s->index == 4) {
3757 /* got length */
3758 s->packet_len = ntohl(*(uint32_t *)s->buf);
3759 s->index = 0;
3760 s->state = 1;
3762 break;
3763 case 1:
3764 l = s->packet_len - s->index;
3765 if (l > size)
3766 l = size;
3767 memcpy(s->buf + s->index, buf, l);
3768 s->index += l;
3769 buf += l;
3770 size -= l;
3771 if (s->index >= s->packet_len) {
3772 qemu_send_packet(s->vc, s->buf, s->packet_len);
3773 s->index = 0;
3774 s->state = 0;
3776 break;
3781 static void net_socket_send_dgram(void *opaque)
3783 NetSocketState *s = opaque;
3784 int size;
3786 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3787 if (size < 0)
3788 return;
3789 if (size == 0) {
3790 /* end of connection */
3791 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3792 return;
3794 qemu_send_packet(s->vc, s->buf, size);
3797 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3799 struct ip_mreq imr;
3800 int fd;
3801 int val, ret;
3802 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3803 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3804 inet_ntoa(mcastaddr->sin_addr),
3805 (int)ntohl(mcastaddr->sin_addr.s_addr));
3806 return -1;
3809 fd = socket(PF_INET, SOCK_DGRAM, 0);
3810 if (fd < 0) {
3811 perror("socket(PF_INET, SOCK_DGRAM)");
3812 return -1;
3815 val = 1;
3816 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3817 (const char *)&val, sizeof(val));
3818 if (ret < 0) {
3819 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3820 goto fail;
3823 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3824 if (ret < 0) {
3825 perror("bind");
3826 goto fail;
3829 /* Add host to multicast group */
3830 imr.imr_multiaddr = mcastaddr->sin_addr;
3831 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3833 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3834 (const char *)&imr, sizeof(struct ip_mreq));
3835 if (ret < 0) {
3836 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3837 goto fail;
3840 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3841 val = 1;
3842 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3843 (const char *)&val, sizeof(val));
3844 if (ret < 0) {
3845 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3846 goto fail;
3849 socket_set_nonblock(fd);
3850 return fd;
3851 fail:
3852 if (fd >= 0)
3853 closesocket(fd);
3854 return -1;
3857 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3858 int is_connected)
3860 struct sockaddr_in saddr;
3861 int newfd;
3862 socklen_t saddr_len;
3863 NetSocketState *s;
3865 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3866 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3867 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3870 if (is_connected) {
3871 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3872 /* must be bound */
3873 if (saddr.sin_addr.s_addr==0) {
3874 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3875 fd);
3876 return NULL;
3878 /* clone dgram socket */
3879 newfd = net_socket_mcast_create(&saddr);
3880 if (newfd < 0) {
3881 /* error already reported by net_socket_mcast_create() */
3882 close(fd);
3883 return NULL;
3885 /* clone newfd to fd, close newfd */
3886 dup2(newfd, fd);
3887 close(newfd);
3889 } else {
3890 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3891 fd, strerror(errno));
3892 return NULL;
3896 s = qemu_mallocz(sizeof(NetSocketState));
3897 if (!s)
3898 return NULL;
3899 s->fd = fd;
3901 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3902 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3904 /* mcast: save bound address as dst */
3905 if (is_connected) s->dgram_dst=saddr;
3907 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3908 "socket: fd=%d (%s mcast=%s:%d)",
3909 fd, is_connected? "cloned" : "",
3910 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3911 return s;
3914 static void net_socket_connect(void *opaque)
3916 NetSocketState *s = opaque;
3917 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3920 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3921 int is_connected)
3923 NetSocketState *s;
3924 s = qemu_mallocz(sizeof(NetSocketState));
3925 if (!s)
3926 return NULL;
3927 s->fd = fd;
3928 s->vc = qemu_new_vlan_client(vlan,
3929 net_socket_receive, NULL, s);
3930 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3931 "socket: fd=%d", fd);
3932 if (is_connected) {
3933 net_socket_connect(s);
3934 } else {
3935 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3937 return s;
3940 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3941 int is_connected)
3943 int so_type=-1, optlen=sizeof(so_type);
3945 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3946 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3947 return NULL;
3949 switch(so_type) {
3950 case SOCK_DGRAM:
3951 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3952 case SOCK_STREAM:
3953 return net_socket_fd_init_stream(vlan, fd, is_connected);
3954 default:
3955 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3956 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3957 return net_socket_fd_init_stream(vlan, fd, is_connected);
3959 return NULL;
3962 static void net_socket_accept(void *opaque)
3964 NetSocketListenState *s = opaque;
3965 NetSocketState *s1;
3966 struct sockaddr_in saddr;
3967 socklen_t len;
3968 int fd;
3970 for(;;) {
3971 len = sizeof(saddr);
3972 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3973 if (fd < 0 && errno != EINTR) {
3974 return;
3975 } else if (fd >= 0) {
3976 break;
3979 s1 = net_socket_fd_init(s->vlan, fd, 1);
3980 if (!s1) {
3981 closesocket(fd);
3982 } else {
3983 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3984 "socket: connection from %s:%d",
3985 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3989 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3991 NetSocketListenState *s;
3992 int fd, val, ret;
3993 struct sockaddr_in saddr;
3995 if (parse_host_port(&saddr, host_str) < 0)
3996 return -1;
3998 s = qemu_mallocz(sizeof(NetSocketListenState));
3999 if (!s)
4000 return -1;
4002 fd = socket(PF_INET, SOCK_STREAM, 0);
4003 if (fd < 0) {
4004 perror("socket");
4005 return -1;
4007 socket_set_nonblock(fd);
4009 /* allow fast reuse */
4010 val = 1;
4011 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4013 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4014 if (ret < 0) {
4015 perror("bind");
4016 return -1;
4018 ret = listen(fd, 0);
4019 if (ret < 0) {
4020 perror("listen");
4021 return -1;
4023 s->vlan = vlan;
4024 s->fd = fd;
4025 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4026 return 0;
4029 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4031 NetSocketState *s;
4032 int fd, connected, ret, err;
4033 struct sockaddr_in saddr;
4035 if (parse_host_port(&saddr, host_str) < 0)
4036 return -1;
4038 fd = socket(PF_INET, SOCK_STREAM, 0);
4039 if (fd < 0) {
4040 perror("socket");
4041 return -1;
4043 socket_set_nonblock(fd);
4045 connected = 0;
4046 for(;;) {
4047 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4048 if (ret < 0) {
4049 err = socket_error();
4050 if (err == EINTR || err == EWOULDBLOCK) {
4051 } else if (err == EINPROGRESS) {
4052 break;
4053 #ifdef _WIN32
4054 } else if (err == WSAEALREADY) {
4055 break;
4056 #endif
4057 } else {
4058 perror("connect");
4059 closesocket(fd);
4060 return -1;
4062 } else {
4063 connected = 1;
4064 break;
4067 s = net_socket_fd_init(vlan, fd, connected);
4068 if (!s)
4069 return -1;
4070 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4071 "socket: connect to %s:%d",
4072 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4073 return 0;
4076 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4078 NetSocketState *s;
4079 int fd;
4080 struct sockaddr_in saddr;
4082 if (parse_host_port(&saddr, host_str) < 0)
4083 return -1;
4086 fd = net_socket_mcast_create(&saddr);
4087 if (fd < 0)
4088 return -1;
4090 s = net_socket_fd_init(vlan, fd, 0);
4091 if (!s)
4092 return -1;
4094 s->dgram_dst = saddr;
4096 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4097 "socket: mcast=%s:%d",
4098 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4099 return 0;
4103 static int get_param_value(char *buf, int buf_size,
4104 const char *tag, const char *str)
4106 const char *p;
4107 char *q;
4108 char option[128];
4110 p = str;
4111 for(;;) {
4112 q = option;
4113 while (*p != '\0' && *p != '=') {
4114 if ((q - option) < sizeof(option) - 1)
4115 *q++ = *p;
4116 p++;
4118 *q = '\0';
4119 if (*p != '=')
4120 break;
4121 p++;
4122 if (!strcmp(tag, option)) {
4123 q = buf;
4124 while (*p != '\0' && *p != ',') {
4125 if ((q - buf) < buf_size - 1)
4126 *q++ = *p;
4127 p++;
4129 *q = '\0';
4130 return q - buf;
4131 } else {
4132 while (*p != '\0' && *p != ',') {
4133 p++;
4136 if (*p != ',')
4137 break;
4138 p++;
4140 return 0;
4143 static int net_client_init(const char *str)
4145 const char *p;
4146 char *q;
4147 char device[64];
4148 char buf[1024];
4149 int vlan_id, ret;
4150 VLANState *vlan;
4152 p = str;
4153 q = device;
4154 while (*p != '\0' && *p != ',') {
4155 if ((q - device) < sizeof(device) - 1)
4156 *q++ = *p;
4157 p++;
4159 *q = '\0';
4160 if (*p == ',')
4161 p++;
4162 vlan_id = 0;
4163 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4164 vlan_id = strtol(buf, NULL, 0);
4166 vlan = qemu_find_vlan(vlan_id);
4167 if (!vlan) {
4168 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4169 return -1;
4171 if (!strcmp(device, "nic")) {
4172 NICInfo *nd;
4173 uint8_t *macaddr;
4175 if (nb_nics >= MAX_NICS) {
4176 fprintf(stderr, "Too Many NICs\n");
4177 return -1;
4179 nd = &nd_table[nb_nics];
4180 macaddr = nd->macaddr;
4181 macaddr[0] = 0x52;
4182 macaddr[1] = 0x54;
4183 macaddr[2] = 0x00;
4184 macaddr[3] = 0x12;
4185 macaddr[4] = 0x34;
4186 macaddr[5] = 0x56 + nb_nics;
4188 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4189 if (parse_macaddr(macaddr, buf) < 0) {
4190 fprintf(stderr, "invalid syntax for ethernet address\n");
4191 return -1;
4194 if (get_param_value(buf, sizeof(buf), "model", p)) {
4195 nd->model = strdup(buf);
4197 nd->vlan = vlan;
4198 nb_nics++;
4199 vlan->nb_guest_devs++;
4200 ret = 0;
4201 } else
4202 if (!strcmp(device, "none")) {
4203 /* does nothing. It is needed to signal that no network cards
4204 are wanted */
4205 ret = 0;
4206 } else
4207 #ifdef CONFIG_SLIRP
4208 if (!strcmp(device, "user")) {
4209 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4210 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4212 vlan->nb_host_devs++;
4213 ret = net_slirp_init(vlan);
4214 } else
4215 #endif
4216 #ifdef _WIN32
4217 if (!strcmp(device, "tap")) {
4218 char ifname[64];
4219 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4220 fprintf(stderr, "tap: no interface name\n");
4221 return -1;
4223 vlan->nb_host_devs++;
4224 ret = tap_win32_init(vlan, ifname);
4225 } else
4226 #else
4227 if (!strcmp(device, "tap")) {
4228 char ifname[64];
4229 char setup_script[1024];
4230 int fd;
4231 vlan->nb_host_devs++;
4232 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4233 fd = strtol(buf, NULL, 0);
4234 ret = -1;
4235 if (net_tap_fd_init(vlan, fd))
4236 ret = 0;
4237 } else {
4238 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4239 ifname[0] = '\0';
4241 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4242 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4244 ret = net_tap_init(vlan, ifname, setup_script);
4246 } else
4247 #endif
4248 if (!strcmp(device, "socket")) {
4249 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4250 int fd;
4251 fd = strtol(buf, NULL, 0);
4252 ret = -1;
4253 if (net_socket_fd_init(vlan, fd, 1))
4254 ret = 0;
4255 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4256 ret = net_socket_listen_init(vlan, buf);
4257 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4258 ret = net_socket_connect_init(vlan, buf);
4259 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4260 ret = net_socket_mcast_init(vlan, buf);
4261 } else {
4262 fprintf(stderr, "Unknown socket options: %s\n", p);
4263 return -1;
4265 vlan->nb_host_devs++;
4266 } else
4268 fprintf(stderr, "Unknown network device: %s\n", device);
4269 return -1;
4271 if (ret < 0) {
4272 fprintf(stderr, "Could not initialize device '%s'\n", device);
4275 return ret;
4278 void do_info_network(void)
4280 VLANState *vlan;
4281 VLANClientState *vc;
4283 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4284 term_printf("VLAN %d devices:\n", vlan->id);
4285 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4286 term_printf(" %s\n", vc->info_str);
4290 /***********************************************************/
4291 /* USB devices */
4293 static USBPort *used_usb_ports;
4294 static USBPort *free_usb_ports;
4296 /* ??? Maybe change this to register a hub to keep track of the topology. */
4297 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4298 usb_attachfn attach)
4300 port->opaque = opaque;
4301 port->index = index;
4302 port->attach = attach;
4303 port->next = free_usb_ports;
4304 free_usb_ports = port;
4307 static int usb_device_add(const char *devname)
4309 const char *p;
4310 USBDevice *dev;
4311 USBPort *port;
4313 if (!free_usb_ports)
4314 return -1;
4316 if (strstart(devname, "host:", &p)) {
4317 dev = usb_host_device_open(p);
4318 } else if (!strcmp(devname, "mouse")) {
4319 dev = usb_mouse_init();
4320 } else if (!strcmp(devname, "tablet")) {
4321 dev = usb_tablet_init();
4322 } else if (strstart(devname, "disk:", &p)) {
4323 dev = usb_msd_init(p);
4324 } else {
4325 return -1;
4327 if (!dev)
4328 return -1;
4330 /* Find a USB port to add the device to. */
4331 port = free_usb_ports;
4332 if (!port->next) {
4333 USBDevice *hub;
4335 /* Create a new hub and chain it on. */
4336 free_usb_ports = NULL;
4337 port->next = used_usb_ports;
4338 used_usb_ports = port;
4340 hub = usb_hub_init(VM_USB_HUB_SIZE);
4341 usb_attach(port, hub);
4342 port = free_usb_ports;
4345 free_usb_ports = port->next;
4346 port->next = used_usb_ports;
4347 used_usb_ports = port;
4348 usb_attach(port, dev);
4349 return 0;
4352 static int usb_device_del(const char *devname)
4354 USBPort *port;
4355 USBPort **lastp;
4356 USBDevice *dev;
4357 int bus_num, addr;
4358 const char *p;
4360 if (!used_usb_ports)
4361 return -1;
4363 p = strchr(devname, '.');
4364 if (!p)
4365 return -1;
4366 bus_num = strtoul(devname, NULL, 0);
4367 addr = strtoul(p + 1, NULL, 0);
4368 if (bus_num != 0)
4369 return -1;
4371 lastp = &used_usb_ports;
4372 port = used_usb_ports;
4373 while (port && port->dev->addr != addr) {
4374 lastp = &port->next;
4375 port = port->next;
4378 if (!port)
4379 return -1;
4381 dev = port->dev;
4382 *lastp = port->next;
4383 usb_attach(port, NULL);
4384 dev->handle_destroy(dev);
4385 port->next = free_usb_ports;
4386 free_usb_ports = port;
4387 return 0;
4390 void do_usb_add(const char *devname)
4392 int ret;
4393 ret = usb_device_add(devname);
4394 if (ret < 0)
4395 term_printf("Could not add USB device '%s'\n", devname);
4398 void do_usb_del(const char *devname)
4400 int ret;
4401 ret = usb_device_del(devname);
4402 if (ret < 0)
4403 term_printf("Could not remove USB device '%s'\n", devname);
4406 void usb_info(void)
4408 USBDevice *dev;
4409 USBPort *port;
4410 const char *speed_str;
4412 if (!usb_enabled) {
4413 term_printf("USB support not enabled\n");
4414 return;
4417 for (port = used_usb_ports; port; port = port->next) {
4418 dev = port->dev;
4419 if (!dev)
4420 continue;
4421 switch(dev->speed) {
4422 case USB_SPEED_LOW:
4423 speed_str = "1.5";
4424 break;
4425 case USB_SPEED_FULL:
4426 speed_str = "12";
4427 break;
4428 case USB_SPEED_HIGH:
4429 speed_str = "480";
4430 break;
4431 default:
4432 speed_str = "?";
4433 break;
4435 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4436 0, dev->addr, speed_str, dev->devname);
4440 /***********************************************************/
4441 /* PCMCIA/Cardbus */
4443 static struct pcmcia_socket_entry_s {
4444 struct pcmcia_socket_s *socket;
4445 struct pcmcia_socket_entry_s *next;
4446 } *pcmcia_sockets = 0;
4448 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4450 struct pcmcia_socket_entry_s *entry;
4452 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4453 entry->socket = socket;
4454 entry->next = pcmcia_sockets;
4455 pcmcia_sockets = entry;
4458 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4460 struct pcmcia_socket_entry_s *entry, **ptr;
4462 ptr = &pcmcia_sockets;
4463 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4464 if (entry->socket == socket) {
4465 *ptr = entry->next;
4466 qemu_free(entry);
4470 void pcmcia_info(void)
4472 struct pcmcia_socket_entry_s *iter;
4473 if (!pcmcia_sockets)
4474 term_printf("No PCMCIA sockets\n");
4476 for (iter = pcmcia_sockets; iter; iter = iter->next)
4477 term_printf("%s: %s\n", iter->socket->slot_string,
4478 iter->socket->attached ? iter->socket->card_string :
4479 "Empty");
4482 /***********************************************************/
4483 /* I/O handling */
4485 #define MAX_IO_HANDLERS 64
4487 typedef struct IOHandlerRecord {
4488 int fd;
4489 IOCanRWHandler *fd_read_poll;
4490 IOHandler *fd_read;
4491 IOHandler *fd_write;
4492 int deleted;
4493 void *opaque;
4494 /* temporary data */
4495 struct pollfd *ufd;
4496 struct IOHandlerRecord *next;
4497 } IOHandlerRecord;
4499 static IOHandlerRecord *first_io_handler;
4501 /* XXX: fd_read_poll should be suppressed, but an API change is
4502 necessary in the character devices to suppress fd_can_read(). */
4503 int qemu_set_fd_handler2(int fd,
4504 IOCanRWHandler *fd_read_poll,
4505 IOHandler *fd_read,
4506 IOHandler *fd_write,
4507 void *opaque)
4509 IOHandlerRecord **pioh, *ioh;
4511 if (!fd_read && !fd_write) {
4512 pioh = &first_io_handler;
4513 for(;;) {
4514 ioh = *pioh;
4515 if (ioh == NULL)
4516 break;
4517 if (ioh->fd == fd) {
4518 ioh->deleted = 1;
4519 break;
4521 pioh = &ioh->next;
4523 } else {
4524 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4525 if (ioh->fd == fd)
4526 goto found;
4528 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4529 if (!ioh)
4530 return -1;
4531 ioh->next = first_io_handler;
4532 first_io_handler = ioh;
4533 found:
4534 ioh->fd = fd;
4535 ioh->fd_read_poll = fd_read_poll;
4536 ioh->fd_read = fd_read;
4537 ioh->fd_write = fd_write;
4538 ioh->opaque = opaque;
4539 ioh->deleted = 0;
4541 return 0;
4544 int qemu_set_fd_handler(int fd,
4545 IOHandler *fd_read,
4546 IOHandler *fd_write,
4547 void *opaque)
4549 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4552 /***********************************************************/
4553 /* Polling handling */
4555 typedef struct PollingEntry {
4556 PollingFunc *func;
4557 void *opaque;
4558 struct PollingEntry *next;
4559 } PollingEntry;
4561 static PollingEntry *first_polling_entry;
4563 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4565 PollingEntry **ppe, *pe;
4566 pe = qemu_mallocz(sizeof(PollingEntry));
4567 if (!pe)
4568 return -1;
4569 pe->func = func;
4570 pe->opaque = opaque;
4571 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4572 *ppe = pe;
4573 return 0;
4576 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4578 PollingEntry **ppe, *pe;
4579 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4580 pe = *ppe;
4581 if (pe->func == func && pe->opaque == opaque) {
4582 *ppe = pe->next;
4583 qemu_free(pe);
4584 break;
4589 #ifdef _WIN32
4590 /***********************************************************/
4591 /* Wait objects support */
4592 typedef struct WaitObjects {
4593 int num;
4594 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4595 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4596 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4597 } WaitObjects;
4599 static WaitObjects wait_objects = {0};
4601 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4603 WaitObjects *w = &wait_objects;
4605 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4606 return -1;
4607 w->events[w->num] = handle;
4608 w->func[w->num] = func;
4609 w->opaque[w->num] = opaque;
4610 w->num++;
4611 return 0;
4614 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4616 int i, found;
4617 WaitObjects *w = &wait_objects;
4619 found = 0;
4620 for (i = 0; i < w->num; i++) {
4621 if (w->events[i] == handle)
4622 found = 1;
4623 if (found) {
4624 w->events[i] = w->events[i + 1];
4625 w->func[i] = w->func[i + 1];
4626 w->opaque[i] = w->opaque[i + 1];
4629 if (found)
4630 w->num--;
4632 #endif
4634 /***********************************************************/
4635 /* savevm/loadvm support */
4637 #define IO_BUF_SIZE 32768
4639 struct QEMUFile {
4640 FILE *outfile;
4641 BlockDriverState *bs;
4642 int is_file;
4643 int is_writable;
4644 int64_t base_offset;
4645 int64_t buf_offset; /* start of buffer when writing, end of buffer
4646 when reading */
4647 int buf_index;
4648 int buf_size; /* 0 when writing */
4649 uint8_t buf[IO_BUF_SIZE];
4652 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4654 QEMUFile *f;
4656 f = qemu_mallocz(sizeof(QEMUFile));
4657 if (!f)
4658 return NULL;
4659 if (!strcmp(mode, "wb")) {
4660 f->is_writable = 1;
4661 } else if (!strcmp(mode, "rb")) {
4662 f->is_writable = 0;
4663 } else {
4664 goto fail;
4666 f->outfile = fopen(filename, mode);
4667 if (!f->outfile)
4668 goto fail;
4669 f->is_file = 1;
4670 return f;
4671 fail:
4672 if (f->outfile)
4673 fclose(f->outfile);
4674 qemu_free(f);
4675 return NULL;
4678 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4680 QEMUFile *f;
4682 f = qemu_mallocz(sizeof(QEMUFile));
4683 if (!f)
4684 return NULL;
4685 f->is_file = 0;
4686 f->bs = bs;
4687 f->is_writable = is_writable;
4688 f->base_offset = offset;
4689 return f;
4692 void qemu_fflush(QEMUFile *f)
4694 if (!f->is_writable)
4695 return;
4696 if (f->buf_index > 0) {
4697 if (f->is_file) {
4698 fseek(f->outfile, f->buf_offset, SEEK_SET);
4699 fwrite(f->buf, 1, f->buf_index, f->outfile);
4700 } else {
4701 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4702 f->buf, f->buf_index);
4704 f->buf_offset += f->buf_index;
4705 f->buf_index = 0;
4709 static void qemu_fill_buffer(QEMUFile *f)
4711 int len;
4713 if (f->is_writable)
4714 return;
4715 if (f->is_file) {
4716 fseek(f->outfile, f->buf_offset, SEEK_SET);
4717 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4718 if (len < 0)
4719 len = 0;
4720 } else {
4721 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4722 f->buf, IO_BUF_SIZE);
4723 if (len < 0)
4724 len = 0;
4726 f->buf_index = 0;
4727 f->buf_size = len;
4728 f->buf_offset += len;
4731 void qemu_fclose(QEMUFile *f)
4733 if (f->is_writable)
4734 qemu_fflush(f);
4735 if (f->is_file) {
4736 fclose(f->outfile);
4738 qemu_free(f);
4741 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4743 int l;
4744 while (size > 0) {
4745 l = IO_BUF_SIZE - f->buf_index;
4746 if (l > size)
4747 l = size;
4748 memcpy(f->buf + f->buf_index, buf, l);
4749 f->buf_index += l;
4750 buf += l;
4751 size -= l;
4752 if (f->buf_index >= IO_BUF_SIZE)
4753 qemu_fflush(f);
4757 void qemu_put_byte(QEMUFile *f, int v)
4759 f->buf[f->buf_index++] = v;
4760 if (f->buf_index >= IO_BUF_SIZE)
4761 qemu_fflush(f);
4764 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4766 int size, l;
4768 size = size1;
4769 while (size > 0) {
4770 l = f->buf_size - f->buf_index;
4771 if (l == 0) {
4772 qemu_fill_buffer(f);
4773 l = f->buf_size - f->buf_index;
4774 if (l == 0)
4775 break;
4777 if (l > size)
4778 l = size;
4779 memcpy(buf, f->buf + f->buf_index, l);
4780 f->buf_index += l;
4781 buf += l;
4782 size -= l;
4784 return size1 - size;
4787 int qemu_get_byte(QEMUFile *f)
4789 if (f->buf_index >= f->buf_size) {
4790 qemu_fill_buffer(f);
4791 if (f->buf_index >= f->buf_size)
4792 return 0;
4794 return f->buf[f->buf_index++];
4797 int64_t qemu_ftell(QEMUFile *f)
4799 return f->buf_offset - f->buf_size + f->buf_index;
4802 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4804 if (whence == SEEK_SET) {
4805 /* nothing to do */
4806 } else if (whence == SEEK_CUR) {
4807 pos += qemu_ftell(f);
4808 } else {
4809 /* SEEK_END not supported */
4810 return -1;
4812 if (f->is_writable) {
4813 qemu_fflush(f);
4814 f->buf_offset = pos;
4815 } else {
4816 f->buf_offset = pos;
4817 f->buf_index = 0;
4818 f->buf_size = 0;
4820 return pos;
4823 void qemu_put_be16(QEMUFile *f, unsigned int v)
4825 qemu_put_byte(f, v >> 8);
4826 qemu_put_byte(f, v);
4829 void qemu_put_be32(QEMUFile *f, unsigned int v)
4831 qemu_put_byte(f, v >> 24);
4832 qemu_put_byte(f, v >> 16);
4833 qemu_put_byte(f, v >> 8);
4834 qemu_put_byte(f, v);
4837 void qemu_put_be64(QEMUFile *f, uint64_t v)
4839 qemu_put_be32(f, v >> 32);
4840 qemu_put_be32(f, v);
4843 unsigned int qemu_get_be16(QEMUFile *f)
4845 unsigned int v;
4846 v = qemu_get_byte(f) << 8;
4847 v |= qemu_get_byte(f);
4848 return v;
4851 unsigned int qemu_get_be32(QEMUFile *f)
4853 unsigned int v;
4854 v = qemu_get_byte(f) << 24;
4855 v |= qemu_get_byte(f) << 16;
4856 v |= qemu_get_byte(f) << 8;
4857 v |= qemu_get_byte(f);
4858 return v;
4861 uint64_t qemu_get_be64(QEMUFile *f)
4863 uint64_t v;
4864 v = (uint64_t)qemu_get_be32(f) << 32;
4865 v |= qemu_get_be32(f);
4866 return v;
4869 typedef struct SaveStateEntry {
4870 char idstr[256];
4871 int instance_id;
4872 int version_id;
4873 SaveStateHandler *save_state;
4874 LoadStateHandler *load_state;
4875 void *opaque;
4876 struct SaveStateEntry *next;
4877 } SaveStateEntry;
4879 static SaveStateEntry *first_se;
4881 int register_savevm(const char *idstr,
4882 int instance_id,
4883 int version_id,
4884 SaveStateHandler *save_state,
4885 LoadStateHandler *load_state,
4886 void *opaque)
4888 SaveStateEntry *se, **pse;
4890 se = qemu_malloc(sizeof(SaveStateEntry));
4891 if (!se)
4892 return -1;
4893 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4894 se->instance_id = instance_id;
4895 se->version_id = version_id;
4896 se->save_state = save_state;
4897 se->load_state = load_state;
4898 se->opaque = opaque;
4899 se->next = NULL;
4901 /* add at the end of list */
4902 pse = &first_se;
4903 while (*pse != NULL)
4904 pse = &(*pse)->next;
4905 *pse = se;
4906 return 0;
4909 #define QEMU_VM_FILE_MAGIC 0x5145564d
4910 #define QEMU_VM_FILE_VERSION 0x00000002
4912 int qemu_savevm_state(QEMUFile *f)
4914 SaveStateEntry *se;
4915 int len, ret;
4916 int64_t cur_pos, len_pos, total_len_pos;
4918 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4919 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4920 total_len_pos = qemu_ftell(f);
4921 qemu_put_be64(f, 0); /* total size */
4923 for(se = first_se; se != NULL; se = se->next) {
4924 /* ID string */
4925 len = strlen(se->idstr);
4926 qemu_put_byte(f, len);
4927 qemu_put_buffer(f, se->idstr, len);
4929 qemu_put_be32(f, se->instance_id);
4930 qemu_put_be32(f, se->version_id);
4932 /* record size: filled later */
4933 len_pos = qemu_ftell(f);
4934 qemu_put_be32(f, 0);
4936 se->save_state(f, se->opaque);
4938 /* fill record size */
4939 cur_pos = qemu_ftell(f);
4940 len = cur_pos - len_pos - 4;
4941 qemu_fseek(f, len_pos, SEEK_SET);
4942 qemu_put_be32(f, len);
4943 qemu_fseek(f, cur_pos, SEEK_SET);
4945 cur_pos = qemu_ftell(f);
4946 qemu_fseek(f, total_len_pos, SEEK_SET);
4947 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4948 qemu_fseek(f, cur_pos, SEEK_SET);
4950 ret = 0;
4951 return ret;
4954 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4956 SaveStateEntry *se;
4958 for(se = first_se; se != NULL; se = se->next) {
4959 if (!strcmp(se->idstr, idstr) &&
4960 instance_id == se->instance_id)
4961 return se;
4963 return NULL;
4966 int qemu_loadvm_state(QEMUFile *f)
4968 SaveStateEntry *se;
4969 int len, ret, instance_id, record_len, version_id;
4970 int64_t total_len, end_pos, cur_pos;
4971 unsigned int v;
4972 char idstr[256];
4974 v = qemu_get_be32(f);
4975 if (v != QEMU_VM_FILE_MAGIC)
4976 goto fail;
4977 v = qemu_get_be32(f);
4978 if (v != QEMU_VM_FILE_VERSION) {
4979 fail:
4980 ret = -1;
4981 goto the_end;
4983 total_len = qemu_get_be64(f);
4984 end_pos = total_len + qemu_ftell(f);
4985 for(;;) {
4986 if (qemu_ftell(f) >= end_pos)
4987 break;
4988 len = qemu_get_byte(f);
4989 qemu_get_buffer(f, idstr, len);
4990 idstr[len] = '\0';
4991 instance_id = qemu_get_be32(f);
4992 version_id = qemu_get_be32(f);
4993 record_len = qemu_get_be32(f);
4994 #if 0
4995 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4996 idstr, instance_id, version_id, record_len);
4997 #endif
4998 cur_pos = qemu_ftell(f);
4999 se = find_se(idstr, instance_id);
5000 if (!se) {
5001 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5002 instance_id, idstr);
5003 } else {
5004 ret = se->load_state(f, se->opaque, version_id);
5005 if (ret < 0) {
5006 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5007 instance_id, idstr);
5010 /* always seek to exact end of record */
5011 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5013 ret = 0;
5014 the_end:
5015 return ret;
5018 /* device can contain snapshots */
5019 static int bdrv_can_snapshot(BlockDriverState *bs)
5021 return (bs &&
5022 !bdrv_is_removable(bs) &&
5023 !bdrv_is_read_only(bs));
5026 /* device must be snapshots in order to have a reliable snapshot */
5027 static int bdrv_has_snapshot(BlockDriverState *bs)
5029 return (bs &&
5030 !bdrv_is_removable(bs) &&
5031 !bdrv_is_read_only(bs));
5034 static BlockDriverState *get_bs_snapshots(void)
5036 BlockDriverState *bs;
5037 int i;
5039 if (bs_snapshots)
5040 return bs_snapshots;
5041 for(i = 0; i <= MAX_DISKS; i++) {
5042 bs = bs_table[i];
5043 if (bdrv_can_snapshot(bs))
5044 goto ok;
5046 return NULL;
5048 bs_snapshots = bs;
5049 return bs;
5052 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5053 const char *name)
5055 QEMUSnapshotInfo *sn_tab, *sn;
5056 int nb_sns, i, ret;
5058 ret = -ENOENT;
5059 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5060 if (nb_sns < 0)
5061 return ret;
5062 for(i = 0; i < nb_sns; i++) {
5063 sn = &sn_tab[i];
5064 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5065 *sn_info = *sn;
5066 ret = 0;
5067 break;
5070 qemu_free(sn_tab);
5071 return ret;
5074 void do_savevm(const char *name)
5076 BlockDriverState *bs, *bs1;
5077 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5078 int must_delete, ret, i;
5079 BlockDriverInfo bdi1, *bdi = &bdi1;
5080 QEMUFile *f;
5081 int saved_vm_running;
5082 #ifdef _WIN32
5083 struct _timeb tb;
5084 #else
5085 struct timeval tv;
5086 #endif
5088 bs = get_bs_snapshots();
5089 if (!bs) {
5090 term_printf("No block device can accept snapshots\n");
5091 return;
5094 /* ??? Should this occur after vm_stop? */
5095 qemu_aio_flush();
5097 saved_vm_running = vm_running;
5098 vm_stop(0);
5100 must_delete = 0;
5101 if (name) {
5102 ret = bdrv_snapshot_find(bs, old_sn, name);
5103 if (ret >= 0) {
5104 must_delete = 1;
5107 memset(sn, 0, sizeof(*sn));
5108 if (must_delete) {
5109 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5110 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5111 } else {
5112 if (name)
5113 pstrcpy(sn->name, sizeof(sn->name), name);
5116 /* fill auxiliary fields */
5117 #ifdef _WIN32
5118 _ftime(&tb);
5119 sn->date_sec = tb.time;
5120 sn->date_nsec = tb.millitm * 1000000;
5121 #else
5122 gettimeofday(&tv, NULL);
5123 sn->date_sec = tv.tv_sec;
5124 sn->date_nsec = tv.tv_usec * 1000;
5125 #endif
5126 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5128 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5129 term_printf("Device %s does not support VM state snapshots\n",
5130 bdrv_get_device_name(bs));
5131 goto the_end;
5134 /* save the VM state */
5135 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5136 if (!f) {
5137 term_printf("Could not open VM state file\n");
5138 goto the_end;
5140 ret = qemu_savevm_state(f);
5141 sn->vm_state_size = qemu_ftell(f);
5142 qemu_fclose(f);
5143 if (ret < 0) {
5144 term_printf("Error %d while writing VM\n", ret);
5145 goto the_end;
5148 /* create the snapshots */
5150 for(i = 0; i < MAX_DISKS; i++) {
5151 bs1 = bs_table[i];
5152 if (bdrv_has_snapshot(bs1)) {
5153 if (must_delete) {
5154 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5155 if (ret < 0) {
5156 term_printf("Error while deleting snapshot on '%s'\n",
5157 bdrv_get_device_name(bs1));
5160 ret = bdrv_snapshot_create(bs1, sn);
5161 if (ret < 0) {
5162 term_printf("Error while creating snapshot on '%s'\n",
5163 bdrv_get_device_name(bs1));
5168 the_end:
5169 if (saved_vm_running)
5170 vm_start();
5173 void do_loadvm(const char *name)
5175 BlockDriverState *bs, *bs1;
5176 BlockDriverInfo bdi1, *bdi = &bdi1;
5177 QEMUFile *f;
5178 int i, ret;
5179 int saved_vm_running;
5181 bs = get_bs_snapshots();
5182 if (!bs) {
5183 term_printf("No block device supports snapshots\n");
5184 return;
5187 /* Flush all IO requests so they don't interfere with the new state. */
5188 qemu_aio_flush();
5190 saved_vm_running = vm_running;
5191 vm_stop(0);
5193 for(i = 0; i <= MAX_DISKS; i++) {
5194 bs1 = bs_table[i];
5195 if (bdrv_has_snapshot(bs1)) {
5196 ret = bdrv_snapshot_goto(bs1, name);
5197 if (ret < 0) {
5198 if (bs != bs1)
5199 term_printf("Warning: ");
5200 switch(ret) {
5201 case -ENOTSUP:
5202 term_printf("Snapshots not supported on device '%s'\n",
5203 bdrv_get_device_name(bs1));
5204 break;
5205 case -ENOENT:
5206 term_printf("Could not find snapshot '%s' on device '%s'\n",
5207 name, bdrv_get_device_name(bs1));
5208 break;
5209 default:
5210 term_printf("Error %d while activating snapshot on '%s'\n",
5211 ret, bdrv_get_device_name(bs1));
5212 break;
5214 /* fatal on snapshot block device */
5215 if (bs == bs1)
5216 goto the_end;
5221 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5222 term_printf("Device %s does not support VM state snapshots\n",
5223 bdrv_get_device_name(bs));
5224 return;
5227 /* restore the VM state */
5228 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5229 if (!f) {
5230 term_printf("Could not open VM state file\n");
5231 goto the_end;
5233 ret = qemu_loadvm_state(f);
5234 qemu_fclose(f);
5235 if (ret < 0) {
5236 term_printf("Error %d while loading VM state\n", ret);
5238 the_end:
5239 if (saved_vm_running)
5240 vm_start();
5243 void do_delvm(const char *name)
5245 BlockDriverState *bs, *bs1;
5246 int i, ret;
5248 bs = get_bs_snapshots();
5249 if (!bs) {
5250 term_printf("No block device supports snapshots\n");
5251 return;
5254 for(i = 0; i <= MAX_DISKS; i++) {
5255 bs1 = bs_table[i];
5256 if (bdrv_has_snapshot(bs1)) {
5257 ret = bdrv_snapshot_delete(bs1, name);
5258 if (ret < 0) {
5259 if (ret == -ENOTSUP)
5260 term_printf("Snapshots not supported on device '%s'\n",
5261 bdrv_get_device_name(bs1));
5262 else
5263 term_printf("Error %d while deleting snapshot on '%s'\n",
5264 ret, bdrv_get_device_name(bs1));
5270 void do_info_snapshots(void)
5272 BlockDriverState *bs, *bs1;
5273 QEMUSnapshotInfo *sn_tab, *sn;
5274 int nb_sns, i;
5275 char buf[256];
5277 bs = get_bs_snapshots();
5278 if (!bs) {
5279 term_printf("No available block device supports snapshots\n");
5280 return;
5282 term_printf("Snapshot devices:");
5283 for(i = 0; i <= MAX_DISKS; i++) {
5284 bs1 = bs_table[i];
5285 if (bdrv_has_snapshot(bs1)) {
5286 if (bs == bs1)
5287 term_printf(" %s", bdrv_get_device_name(bs1));
5290 term_printf("\n");
5292 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5293 if (nb_sns < 0) {
5294 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5295 return;
5297 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5298 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5299 for(i = 0; i < nb_sns; i++) {
5300 sn = &sn_tab[i];
5301 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5303 qemu_free(sn_tab);
5306 /***********************************************************/
5307 /* cpu save/restore */
5309 #if defined(TARGET_I386)
5311 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5313 qemu_put_be32(f, dt->selector);
5314 qemu_put_betl(f, dt->base);
5315 qemu_put_be32(f, dt->limit);
5316 qemu_put_be32(f, dt->flags);
5319 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5321 dt->selector = qemu_get_be32(f);
5322 dt->base = qemu_get_betl(f);
5323 dt->limit = qemu_get_be32(f);
5324 dt->flags = qemu_get_be32(f);
5327 void cpu_save(QEMUFile *f, void *opaque)
5329 CPUState *env = opaque;
5330 uint16_t fptag, fpus, fpuc, fpregs_format;
5331 uint32_t hflags;
5332 int i;
5334 for(i = 0; i < CPU_NB_REGS; i++)
5335 qemu_put_betls(f, &env->regs[i]);
5336 qemu_put_betls(f, &env->eip);
5337 qemu_put_betls(f, &env->eflags);
5338 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5339 qemu_put_be32s(f, &hflags);
5341 /* FPU */
5342 fpuc = env->fpuc;
5343 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5344 fptag = 0;
5345 for(i = 0; i < 8; i++) {
5346 fptag |= ((!env->fptags[i]) << i);
5349 qemu_put_be16s(f, &fpuc);
5350 qemu_put_be16s(f, &fpus);
5351 qemu_put_be16s(f, &fptag);
5353 #ifdef USE_X86LDOUBLE
5354 fpregs_format = 0;
5355 #else
5356 fpregs_format = 1;
5357 #endif
5358 qemu_put_be16s(f, &fpregs_format);
5360 for(i = 0; i < 8; i++) {
5361 #ifdef USE_X86LDOUBLE
5363 uint64_t mant;
5364 uint16_t exp;
5365 /* we save the real CPU data (in case of MMX usage only 'mant'
5366 contains the MMX register */
5367 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5368 qemu_put_be64(f, mant);
5369 qemu_put_be16(f, exp);
5371 #else
5372 /* if we use doubles for float emulation, we save the doubles to
5373 avoid losing information in case of MMX usage. It can give
5374 problems if the image is restored on a CPU where long
5375 doubles are used instead. */
5376 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5377 #endif
5380 for(i = 0; i < 6; i++)
5381 cpu_put_seg(f, &env->segs[i]);
5382 cpu_put_seg(f, &env->ldt);
5383 cpu_put_seg(f, &env->tr);
5384 cpu_put_seg(f, &env->gdt);
5385 cpu_put_seg(f, &env->idt);
5387 qemu_put_be32s(f, &env->sysenter_cs);
5388 qemu_put_be32s(f, &env->sysenter_esp);
5389 qemu_put_be32s(f, &env->sysenter_eip);
5391 qemu_put_betls(f, &env->cr[0]);
5392 qemu_put_betls(f, &env->cr[2]);
5393 qemu_put_betls(f, &env->cr[3]);
5394 qemu_put_betls(f, &env->cr[4]);
5396 for(i = 0; i < 8; i++)
5397 qemu_put_betls(f, &env->dr[i]);
5399 /* MMU */
5400 qemu_put_be32s(f, &env->a20_mask);
5402 /* XMM */
5403 qemu_put_be32s(f, &env->mxcsr);
5404 for(i = 0; i < CPU_NB_REGS; i++) {
5405 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5406 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5409 #ifdef TARGET_X86_64
5410 qemu_put_be64s(f, &env->efer);
5411 qemu_put_be64s(f, &env->star);
5412 qemu_put_be64s(f, &env->lstar);
5413 qemu_put_be64s(f, &env->cstar);
5414 qemu_put_be64s(f, &env->fmask);
5415 qemu_put_be64s(f, &env->kernelgsbase);
5416 #endif
5417 qemu_put_be32s(f, &env->smbase);
5420 #ifdef USE_X86LDOUBLE
5421 /* XXX: add that in a FPU generic layer */
5422 union x86_longdouble {
5423 uint64_t mant;
5424 uint16_t exp;
5427 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5428 #define EXPBIAS1 1023
5429 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5430 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5432 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5434 int e;
5435 /* mantissa */
5436 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5437 /* exponent + sign */
5438 e = EXPD1(temp) - EXPBIAS1 + 16383;
5439 e |= SIGND1(temp) >> 16;
5440 p->exp = e;
5442 #endif
5444 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5446 CPUState *env = opaque;
5447 int i, guess_mmx;
5448 uint32_t hflags;
5449 uint16_t fpus, fpuc, fptag, fpregs_format;
5451 if (version_id != 3 && version_id != 4)
5452 return -EINVAL;
5453 for(i = 0; i < CPU_NB_REGS; i++)
5454 qemu_get_betls(f, &env->regs[i]);
5455 qemu_get_betls(f, &env->eip);
5456 qemu_get_betls(f, &env->eflags);
5457 qemu_get_be32s(f, &hflags);
5459 qemu_get_be16s(f, &fpuc);
5460 qemu_get_be16s(f, &fpus);
5461 qemu_get_be16s(f, &fptag);
5462 qemu_get_be16s(f, &fpregs_format);
5464 /* NOTE: we cannot always restore the FPU state if the image come
5465 from a host with a different 'USE_X86LDOUBLE' define. We guess
5466 if we are in an MMX state to restore correctly in that case. */
5467 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5468 for(i = 0; i < 8; i++) {
5469 uint64_t mant;
5470 uint16_t exp;
5472 switch(fpregs_format) {
5473 case 0:
5474 mant = qemu_get_be64(f);
5475 exp = qemu_get_be16(f);
5476 #ifdef USE_X86LDOUBLE
5477 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5478 #else
5479 /* difficult case */
5480 if (guess_mmx)
5481 env->fpregs[i].mmx.MMX_Q(0) = mant;
5482 else
5483 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5484 #endif
5485 break;
5486 case 1:
5487 mant = qemu_get_be64(f);
5488 #ifdef USE_X86LDOUBLE
5490 union x86_longdouble *p;
5491 /* difficult case */
5492 p = (void *)&env->fpregs[i];
5493 if (guess_mmx) {
5494 p->mant = mant;
5495 p->exp = 0xffff;
5496 } else {
5497 fp64_to_fp80(p, mant);
5500 #else
5501 env->fpregs[i].mmx.MMX_Q(0) = mant;
5502 #endif
5503 break;
5504 default:
5505 return -EINVAL;
5509 env->fpuc = fpuc;
5510 /* XXX: restore FPU round state */
5511 env->fpstt = (fpus >> 11) & 7;
5512 env->fpus = fpus & ~0x3800;
5513 fptag ^= 0xff;
5514 for(i = 0; i < 8; i++) {
5515 env->fptags[i] = (fptag >> i) & 1;
5518 for(i = 0; i < 6; i++)
5519 cpu_get_seg(f, &env->segs[i]);
5520 cpu_get_seg(f, &env->ldt);
5521 cpu_get_seg(f, &env->tr);
5522 cpu_get_seg(f, &env->gdt);
5523 cpu_get_seg(f, &env->idt);
5525 qemu_get_be32s(f, &env->sysenter_cs);
5526 qemu_get_be32s(f, &env->sysenter_esp);
5527 qemu_get_be32s(f, &env->sysenter_eip);
5529 qemu_get_betls(f, &env->cr[0]);
5530 qemu_get_betls(f, &env->cr[2]);
5531 qemu_get_betls(f, &env->cr[3]);
5532 qemu_get_betls(f, &env->cr[4]);
5534 for(i = 0; i < 8; i++)
5535 qemu_get_betls(f, &env->dr[i]);
5537 /* MMU */
5538 qemu_get_be32s(f, &env->a20_mask);
5540 qemu_get_be32s(f, &env->mxcsr);
5541 for(i = 0; i < CPU_NB_REGS; i++) {
5542 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5543 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5546 #ifdef TARGET_X86_64
5547 qemu_get_be64s(f, &env->efer);
5548 qemu_get_be64s(f, &env->star);
5549 qemu_get_be64s(f, &env->lstar);
5550 qemu_get_be64s(f, &env->cstar);
5551 qemu_get_be64s(f, &env->fmask);
5552 qemu_get_be64s(f, &env->kernelgsbase);
5553 #endif
5554 if (version_id >= 4)
5555 qemu_get_be32s(f, &env->smbase);
5557 /* XXX: compute hflags from scratch, except for CPL and IIF */
5558 env->hflags = hflags;
5559 tlb_flush(env, 1);
5560 return 0;
5563 #elif defined(TARGET_PPC)
5564 void cpu_save(QEMUFile *f, void *opaque)
5568 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5570 return 0;
5573 #elif defined(TARGET_MIPS)
5574 void cpu_save(QEMUFile *f, void *opaque)
5578 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5580 return 0;
5583 #elif defined(TARGET_SPARC)
5584 void cpu_save(QEMUFile *f, void *opaque)
5586 CPUState *env = opaque;
5587 int i;
5588 uint32_t tmp;
5590 for(i = 0; i < 8; i++)
5591 qemu_put_betls(f, &env->gregs[i]);
5592 for(i = 0; i < NWINDOWS * 16; i++)
5593 qemu_put_betls(f, &env->regbase[i]);
5595 /* FPU */
5596 for(i = 0; i < TARGET_FPREGS; i++) {
5597 union {
5598 float32 f;
5599 uint32_t i;
5600 } u;
5601 u.f = env->fpr[i];
5602 qemu_put_be32(f, u.i);
5605 qemu_put_betls(f, &env->pc);
5606 qemu_put_betls(f, &env->npc);
5607 qemu_put_betls(f, &env->y);
5608 tmp = GET_PSR(env);
5609 qemu_put_be32(f, tmp);
5610 qemu_put_betls(f, &env->fsr);
5611 qemu_put_betls(f, &env->tbr);
5612 #ifndef TARGET_SPARC64
5613 qemu_put_be32s(f, &env->wim);
5614 /* MMU */
5615 for(i = 0; i < 16; i++)
5616 qemu_put_be32s(f, &env->mmuregs[i]);
5617 #endif
5620 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5622 CPUState *env = opaque;
5623 int i;
5624 uint32_t tmp;
5626 for(i = 0; i < 8; i++)
5627 qemu_get_betls(f, &env->gregs[i]);
5628 for(i = 0; i < NWINDOWS * 16; i++)
5629 qemu_get_betls(f, &env->regbase[i]);
5631 /* FPU */
5632 for(i = 0; i < TARGET_FPREGS; i++) {
5633 union {
5634 float32 f;
5635 uint32_t i;
5636 } u;
5637 u.i = qemu_get_be32(f);
5638 env->fpr[i] = u.f;
5641 qemu_get_betls(f, &env->pc);
5642 qemu_get_betls(f, &env->npc);
5643 qemu_get_betls(f, &env->y);
5644 tmp = qemu_get_be32(f);
5645 env->cwp = 0; /* needed to ensure that the wrapping registers are
5646 correctly updated */
5647 PUT_PSR(env, tmp);
5648 qemu_get_betls(f, &env->fsr);
5649 qemu_get_betls(f, &env->tbr);
5650 #ifndef TARGET_SPARC64
5651 qemu_get_be32s(f, &env->wim);
5652 /* MMU */
5653 for(i = 0; i < 16; i++)
5654 qemu_get_be32s(f, &env->mmuregs[i]);
5655 #endif
5656 tlb_flush(env, 1);
5657 return 0;
5660 #elif defined(TARGET_ARM)
5662 void cpu_save(QEMUFile *f, void *opaque)
5664 int i;
5665 CPUARMState *env = (CPUARMState *)opaque;
5667 for (i = 0; i < 16; i++) {
5668 qemu_put_be32(f, env->regs[i]);
5670 qemu_put_be32(f, cpsr_read(env));
5671 qemu_put_be32(f, env->spsr);
5672 for (i = 0; i < 6; i++) {
5673 qemu_put_be32(f, env->banked_spsr[i]);
5674 qemu_put_be32(f, env->banked_r13[i]);
5675 qemu_put_be32(f, env->banked_r14[i]);
5677 for (i = 0; i < 5; i++) {
5678 qemu_put_be32(f, env->usr_regs[i]);
5679 qemu_put_be32(f, env->fiq_regs[i]);
5681 qemu_put_be32(f, env->cp15.c0_cpuid);
5682 qemu_put_be32(f, env->cp15.c0_cachetype);
5683 qemu_put_be32(f, env->cp15.c1_sys);
5684 qemu_put_be32(f, env->cp15.c1_coproc);
5685 qemu_put_be32(f, env->cp15.c2_base);
5686 qemu_put_be32(f, env->cp15.c2_data);
5687 qemu_put_be32(f, env->cp15.c2_insn);
5688 qemu_put_be32(f, env->cp15.c3);
5689 qemu_put_be32(f, env->cp15.c5_insn);
5690 qemu_put_be32(f, env->cp15.c5_data);
5691 for (i = 0; i < 8; i++) {
5692 qemu_put_be32(f, env->cp15.c6_region[i]);
5694 qemu_put_be32(f, env->cp15.c6_insn);
5695 qemu_put_be32(f, env->cp15.c6_data);
5696 qemu_put_be32(f, env->cp15.c9_insn);
5697 qemu_put_be32(f, env->cp15.c9_data);
5698 qemu_put_be32(f, env->cp15.c13_fcse);
5699 qemu_put_be32(f, env->cp15.c13_context);
5700 qemu_put_be32(f, env->cp15.c15_cpar);
5702 qemu_put_be32(f, env->features);
5704 if (arm_feature(env, ARM_FEATURE_VFP)) {
5705 for (i = 0; i < 16; i++) {
5706 CPU_DoubleU u;
5707 u.d = env->vfp.regs[i];
5708 qemu_put_be32(f, u.l.upper);
5709 qemu_put_be32(f, u.l.lower);
5711 for (i = 0; i < 16; i++) {
5712 qemu_put_be32(f, env->vfp.xregs[i]);
5715 /* TODO: Should use proper FPSCR access functions. */
5716 qemu_put_be32(f, env->vfp.vec_len);
5717 qemu_put_be32(f, env->vfp.vec_stride);
5720 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5721 for (i = 0; i < 16; i++) {
5722 qemu_put_be64(f, env->iwmmxt.regs[i]);
5724 for (i = 0; i < 16; i++) {
5725 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5730 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5732 CPUARMState *env = (CPUARMState *)opaque;
5733 int i;
5735 if (version_id != 0)
5736 return -EINVAL;
5738 for (i = 0; i < 16; i++) {
5739 env->regs[i] = qemu_get_be32(f);
5741 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5742 env->spsr = qemu_get_be32(f);
5743 for (i = 0; i < 6; i++) {
5744 env->banked_spsr[i] = qemu_get_be32(f);
5745 env->banked_r13[i] = qemu_get_be32(f);
5746 env->banked_r14[i] = qemu_get_be32(f);
5748 for (i = 0; i < 5; i++) {
5749 env->usr_regs[i] = qemu_get_be32(f);
5750 env->fiq_regs[i] = qemu_get_be32(f);
5752 env->cp15.c0_cpuid = qemu_get_be32(f);
5753 env->cp15.c0_cachetype = qemu_get_be32(f);
5754 env->cp15.c1_sys = qemu_get_be32(f);
5755 env->cp15.c1_coproc = qemu_get_be32(f);
5756 env->cp15.c2_base = qemu_get_be32(f);
5757 env->cp15.c2_data = qemu_get_be32(f);
5758 env->cp15.c2_insn = qemu_get_be32(f);
5759 env->cp15.c3 = qemu_get_be32(f);
5760 env->cp15.c5_insn = qemu_get_be32(f);
5761 env->cp15.c5_data = qemu_get_be32(f);
5762 for (i = 0; i < 8; i++) {
5763 env->cp15.c6_region[i] = qemu_get_be32(f);
5765 env->cp15.c6_insn = qemu_get_be32(f);
5766 env->cp15.c6_data = qemu_get_be32(f);
5767 env->cp15.c9_insn = qemu_get_be32(f);
5768 env->cp15.c9_data = qemu_get_be32(f);
5769 env->cp15.c13_fcse = qemu_get_be32(f);
5770 env->cp15.c13_context = qemu_get_be32(f);
5771 env->cp15.c15_cpar = qemu_get_be32(f);
5773 env->features = qemu_get_be32(f);
5775 if (arm_feature(env, ARM_FEATURE_VFP)) {
5776 for (i = 0; i < 16; i++) {
5777 CPU_DoubleU u;
5778 u.l.upper = qemu_get_be32(f);
5779 u.l.lower = qemu_get_be32(f);
5780 env->vfp.regs[i] = u.d;
5782 for (i = 0; i < 16; i++) {
5783 env->vfp.xregs[i] = qemu_get_be32(f);
5786 /* TODO: Should use proper FPSCR access functions. */
5787 env->vfp.vec_len = qemu_get_be32(f);
5788 env->vfp.vec_stride = qemu_get_be32(f);
5791 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5792 for (i = 0; i < 16; i++) {
5793 env->iwmmxt.regs[i] = qemu_get_be64(f);
5795 for (i = 0; i < 16; i++) {
5796 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5800 return 0;
5803 #else
5805 #warning No CPU save/restore functions
5807 #endif
5809 /***********************************************************/
5810 /* ram save/restore */
5812 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5814 int v;
5816 v = qemu_get_byte(f);
5817 switch(v) {
5818 case 0:
5819 if (qemu_get_buffer(f, buf, len) != len)
5820 return -EIO;
5821 break;
5822 case 1:
5823 v = qemu_get_byte(f);
5824 memset(buf, v, len);
5825 break;
5826 default:
5827 return -EINVAL;
5829 return 0;
5832 static int ram_load_v1(QEMUFile *f, void *opaque)
5834 int i, ret;
5836 if (qemu_get_be32(f) != phys_ram_size)
5837 return -EINVAL;
5838 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5839 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5840 if (ret)
5841 return ret;
5843 return 0;
5846 #define BDRV_HASH_BLOCK_SIZE 1024
5847 #define IOBUF_SIZE 4096
5848 #define RAM_CBLOCK_MAGIC 0xfabe
5850 typedef struct RamCompressState {
5851 z_stream zstream;
5852 QEMUFile *f;
5853 uint8_t buf[IOBUF_SIZE];
5854 } RamCompressState;
5856 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5858 int ret;
5859 memset(s, 0, sizeof(*s));
5860 s->f = f;
5861 ret = deflateInit2(&s->zstream, 1,
5862 Z_DEFLATED, 15,
5863 9, Z_DEFAULT_STRATEGY);
5864 if (ret != Z_OK)
5865 return -1;
5866 s->zstream.avail_out = IOBUF_SIZE;
5867 s->zstream.next_out = s->buf;
5868 return 0;
5871 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5873 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5874 qemu_put_be16(s->f, len);
5875 qemu_put_buffer(s->f, buf, len);
5878 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5880 int ret;
5882 s->zstream.avail_in = len;
5883 s->zstream.next_in = (uint8_t *)buf;
5884 while (s->zstream.avail_in > 0) {
5885 ret = deflate(&s->zstream, Z_NO_FLUSH);
5886 if (ret != Z_OK)
5887 return -1;
5888 if (s->zstream.avail_out == 0) {
5889 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5890 s->zstream.avail_out = IOBUF_SIZE;
5891 s->zstream.next_out = s->buf;
5894 return 0;
5897 static void ram_compress_close(RamCompressState *s)
5899 int len, ret;
5901 /* compress last bytes */
5902 for(;;) {
5903 ret = deflate(&s->zstream, Z_FINISH);
5904 if (ret == Z_OK || ret == Z_STREAM_END) {
5905 len = IOBUF_SIZE - s->zstream.avail_out;
5906 if (len > 0) {
5907 ram_put_cblock(s, s->buf, len);
5909 s->zstream.avail_out = IOBUF_SIZE;
5910 s->zstream.next_out = s->buf;
5911 if (ret == Z_STREAM_END)
5912 break;
5913 } else {
5914 goto fail;
5917 fail:
5918 deflateEnd(&s->zstream);
5921 typedef struct RamDecompressState {
5922 z_stream zstream;
5923 QEMUFile *f;
5924 uint8_t buf[IOBUF_SIZE];
5925 } RamDecompressState;
5927 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5929 int ret;
5930 memset(s, 0, sizeof(*s));
5931 s->f = f;
5932 ret = inflateInit(&s->zstream);
5933 if (ret != Z_OK)
5934 return -1;
5935 return 0;
5938 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5940 int ret, clen;
5942 s->zstream.avail_out = len;
5943 s->zstream.next_out = buf;
5944 while (s->zstream.avail_out > 0) {
5945 if (s->zstream.avail_in == 0) {
5946 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5947 return -1;
5948 clen = qemu_get_be16(s->f);
5949 if (clen > IOBUF_SIZE)
5950 return -1;
5951 qemu_get_buffer(s->f, s->buf, clen);
5952 s->zstream.avail_in = clen;
5953 s->zstream.next_in = s->buf;
5955 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5956 if (ret != Z_OK && ret != Z_STREAM_END) {
5957 return -1;
5960 return 0;
5963 static void ram_decompress_close(RamDecompressState *s)
5965 inflateEnd(&s->zstream);
5968 static void ram_save(QEMUFile *f, void *opaque)
5970 int i;
5971 RamCompressState s1, *s = &s1;
5972 uint8_t buf[10];
5974 qemu_put_be32(f, phys_ram_size);
5975 if (ram_compress_open(s, f) < 0)
5976 return;
5977 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5978 #if 0
5979 if (tight_savevm_enabled) {
5980 int64_t sector_num;
5981 int j;
5983 /* find if the memory block is available on a virtual
5984 block device */
5985 sector_num = -1;
5986 for(j = 0; j < MAX_DISKS; j++) {
5987 if (bs_table[j]) {
5988 sector_num = bdrv_hash_find(bs_table[j],
5989 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5990 if (sector_num >= 0)
5991 break;
5994 if (j == MAX_DISKS)
5995 goto normal_compress;
5996 buf[0] = 1;
5997 buf[1] = j;
5998 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5999 ram_compress_buf(s, buf, 10);
6000 } else
6001 #endif
6003 // normal_compress:
6004 buf[0] = 0;
6005 ram_compress_buf(s, buf, 1);
6006 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6009 ram_compress_close(s);
6012 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6014 RamDecompressState s1, *s = &s1;
6015 uint8_t buf[10];
6016 int i;
6018 if (version_id == 1)
6019 return ram_load_v1(f, opaque);
6020 if (version_id != 2)
6021 return -EINVAL;
6022 if (qemu_get_be32(f) != phys_ram_size)
6023 return -EINVAL;
6024 if (ram_decompress_open(s, f) < 0)
6025 return -EINVAL;
6026 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6027 if (ram_decompress_buf(s, buf, 1) < 0) {
6028 fprintf(stderr, "Error while reading ram block header\n");
6029 goto error;
6031 if (buf[0] == 0) {
6032 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6033 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6034 goto error;
6036 } else
6037 #if 0
6038 if (buf[0] == 1) {
6039 int bs_index;
6040 int64_t sector_num;
6042 ram_decompress_buf(s, buf + 1, 9);
6043 bs_index = buf[1];
6044 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6045 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6046 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6047 goto error;
6049 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6050 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6051 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6052 bs_index, sector_num);
6053 goto error;
6055 } else
6056 #endif
6058 error:
6059 printf("Error block header\n");
6060 return -EINVAL;
6063 ram_decompress_close(s);
6064 return 0;
6067 /***********************************************************/
6068 /* bottom halves (can be seen as timers which expire ASAP) */
6070 struct QEMUBH {
6071 QEMUBHFunc *cb;
6072 void *opaque;
6073 int scheduled;
6074 QEMUBH *next;
6077 static QEMUBH *first_bh = NULL;
6079 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6081 QEMUBH *bh;
6082 bh = qemu_mallocz(sizeof(QEMUBH));
6083 if (!bh)
6084 return NULL;
6085 bh->cb = cb;
6086 bh->opaque = opaque;
6087 return bh;
6090 int qemu_bh_poll(void)
6092 QEMUBH *bh, **pbh;
6093 int ret;
6095 ret = 0;
6096 for(;;) {
6097 pbh = &first_bh;
6098 bh = *pbh;
6099 if (!bh)
6100 break;
6101 ret = 1;
6102 *pbh = bh->next;
6103 bh->scheduled = 0;
6104 bh->cb(bh->opaque);
6106 return ret;
6109 void qemu_bh_schedule(QEMUBH *bh)
6111 CPUState *env = cpu_single_env;
6112 if (bh->scheduled)
6113 return;
6114 bh->scheduled = 1;
6115 bh->next = first_bh;
6116 first_bh = bh;
6118 /* stop the currently executing CPU to execute the BH ASAP */
6119 if (env) {
6120 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6124 void qemu_bh_cancel(QEMUBH *bh)
6126 QEMUBH **pbh;
6127 if (bh->scheduled) {
6128 pbh = &first_bh;
6129 while (*pbh != bh)
6130 pbh = &(*pbh)->next;
6131 *pbh = bh->next;
6132 bh->scheduled = 0;
6136 void qemu_bh_delete(QEMUBH *bh)
6138 qemu_bh_cancel(bh);
6139 qemu_free(bh);
6142 /***********************************************************/
6143 /* machine registration */
6145 QEMUMachine *first_machine = NULL;
6147 int qemu_register_machine(QEMUMachine *m)
6149 QEMUMachine **pm;
6150 pm = &first_machine;
6151 while (*pm != NULL)
6152 pm = &(*pm)->next;
6153 m->next = NULL;
6154 *pm = m;
6155 return 0;
6158 QEMUMachine *find_machine(const char *name)
6160 QEMUMachine *m;
6162 for(m = first_machine; m != NULL; m = m->next) {
6163 if (!strcmp(m->name, name))
6164 return m;
6166 return NULL;
6169 /***********************************************************/
6170 /* main execution loop */
6172 void gui_update(void *opaque)
6174 DisplayState *ds = opaque;
6175 ds->dpy_refresh(ds);
6176 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6179 struct vm_change_state_entry {
6180 VMChangeStateHandler *cb;
6181 void *opaque;
6182 LIST_ENTRY (vm_change_state_entry) entries;
6185 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6187 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6188 void *opaque)
6190 VMChangeStateEntry *e;
6192 e = qemu_mallocz(sizeof (*e));
6193 if (!e)
6194 return NULL;
6196 e->cb = cb;
6197 e->opaque = opaque;
6198 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6199 return e;
6202 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6204 LIST_REMOVE (e, entries);
6205 qemu_free (e);
6208 static void vm_state_notify(int running)
6210 VMChangeStateEntry *e;
6212 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6213 e->cb(e->opaque, running);
6217 /* XXX: support several handlers */
6218 static VMStopHandler *vm_stop_cb;
6219 static void *vm_stop_opaque;
6221 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6223 vm_stop_cb = cb;
6224 vm_stop_opaque = opaque;
6225 return 0;
6228 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6230 vm_stop_cb = NULL;
6233 void vm_start(void)
6235 if (!vm_running) {
6236 cpu_enable_ticks();
6237 vm_running = 1;
6238 vm_state_notify(1);
6242 void vm_stop(int reason)
6244 if (vm_running) {
6245 cpu_disable_ticks();
6246 vm_running = 0;
6247 if (reason != 0) {
6248 if (vm_stop_cb) {
6249 vm_stop_cb(vm_stop_opaque, reason);
6252 vm_state_notify(0);
6256 /* reset/shutdown handler */
6258 typedef struct QEMUResetEntry {
6259 QEMUResetHandler *func;
6260 void *opaque;
6261 struct QEMUResetEntry *next;
6262 } QEMUResetEntry;
6264 static QEMUResetEntry *first_reset_entry;
6265 static int reset_requested;
6266 static int shutdown_requested;
6267 static int powerdown_requested;
6269 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6271 QEMUResetEntry **pre, *re;
6273 pre = &first_reset_entry;
6274 while (*pre != NULL)
6275 pre = &(*pre)->next;
6276 re = qemu_mallocz(sizeof(QEMUResetEntry));
6277 re->func = func;
6278 re->opaque = opaque;
6279 re->next = NULL;
6280 *pre = re;
6283 static void qemu_system_reset(void)
6285 QEMUResetEntry *re;
6287 /* reset all devices */
6288 for(re = first_reset_entry; re != NULL; re = re->next) {
6289 re->func(re->opaque);
6293 void qemu_system_reset_request(void)
6295 if (no_reboot) {
6296 shutdown_requested = 1;
6297 } else {
6298 reset_requested = 1;
6300 if (cpu_single_env)
6301 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6304 void qemu_system_shutdown_request(void)
6306 shutdown_requested = 1;
6307 if (cpu_single_env)
6308 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6311 void qemu_system_powerdown_request(void)
6313 powerdown_requested = 1;
6314 if (cpu_single_env)
6315 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6318 void main_loop_wait(int timeout)
6320 IOHandlerRecord *ioh;
6321 fd_set rfds, wfds, xfds;
6322 int ret, nfds;
6323 #ifdef _WIN32
6324 int ret2, i;
6325 #endif
6326 struct timeval tv;
6327 PollingEntry *pe;
6330 /* XXX: need to suppress polling by better using win32 events */
6331 ret = 0;
6332 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6333 ret |= pe->func(pe->opaque);
6335 #ifdef _WIN32
6336 if (ret == 0) {
6337 int err;
6338 WaitObjects *w = &wait_objects;
6340 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6341 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6342 if (w->func[ret - WAIT_OBJECT_0])
6343 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6345 /* Check for additional signaled events */
6346 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6348 /* Check if event is signaled */
6349 ret2 = WaitForSingleObject(w->events[i], 0);
6350 if(ret2 == WAIT_OBJECT_0) {
6351 if (w->func[i])
6352 w->func[i](w->opaque[i]);
6353 } else if (ret2 == WAIT_TIMEOUT) {
6354 } else {
6355 err = GetLastError();
6356 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6359 } else if (ret == WAIT_TIMEOUT) {
6360 } else {
6361 err = GetLastError();
6362 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6365 #endif
6366 /* poll any events */
6367 /* XXX: separate device handlers from system ones */
6368 nfds = -1;
6369 FD_ZERO(&rfds);
6370 FD_ZERO(&wfds);
6371 FD_ZERO(&xfds);
6372 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6373 if (ioh->deleted)
6374 continue;
6375 if (ioh->fd_read &&
6376 (!ioh->fd_read_poll ||
6377 ioh->fd_read_poll(ioh->opaque) != 0)) {
6378 FD_SET(ioh->fd, &rfds);
6379 if (ioh->fd > nfds)
6380 nfds = ioh->fd;
6382 if (ioh->fd_write) {
6383 FD_SET(ioh->fd, &wfds);
6384 if (ioh->fd > nfds)
6385 nfds = ioh->fd;
6389 tv.tv_sec = 0;
6390 #ifdef _WIN32
6391 tv.tv_usec = 0;
6392 #else
6393 tv.tv_usec = timeout * 1000;
6394 #endif
6395 #if defined(CONFIG_SLIRP)
6396 if (slirp_inited) {
6397 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6399 #endif
6400 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6401 if (ret > 0) {
6402 IOHandlerRecord **pioh;
6404 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6405 if (ioh->deleted)
6406 continue;
6407 if (FD_ISSET(ioh->fd, &rfds)) {
6408 ioh->fd_read(ioh->opaque);
6410 if (FD_ISSET(ioh->fd, &wfds)) {
6411 ioh->fd_write(ioh->opaque);
6415 /* remove deleted IO handlers */
6416 pioh = &first_io_handler;
6417 while (*pioh) {
6418 ioh = *pioh;
6419 if (ioh->deleted) {
6420 *pioh = ioh->next;
6421 qemu_free(ioh);
6422 } else
6423 pioh = &ioh->next;
6426 #if defined(CONFIG_SLIRP)
6427 if (slirp_inited) {
6428 if (ret < 0) {
6429 FD_ZERO(&rfds);
6430 FD_ZERO(&wfds);
6431 FD_ZERO(&xfds);
6433 slirp_select_poll(&rfds, &wfds, &xfds);
6435 #endif
6436 qemu_aio_poll();
6438 if (vm_running) {
6439 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6440 qemu_get_clock(vm_clock));
6441 /* run dma transfers, if any */
6442 DMA_run();
6445 /* real time timers */
6446 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6447 qemu_get_clock(rt_clock));
6449 /* Check bottom-halves last in case any of the earlier events triggered
6450 them. */
6451 qemu_bh_poll();
6455 static CPUState *cur_cpu;
6457 int main_loop(void)
6459 int ret, timeout;
6460 #ifdef CONFIG_PROFILER
6461 int64_t ti;
6462 #endif
6463 CPUState *env;
6465 cur_cpu = first_cpu;
6466 for(;;) {
6467 if (vm_running) {
6469 env = cur_cpu;
6470 for(;;) {
6471 /* get next cpu */
6472 env = env->next_cpu;
6473 if (!env)
6474 env = first_cpu;
6475 #ifdef CONFIG_PROFILER
6476 ti = profile_getclock();
6477 #endif
6478 ret = cpu_exec(env);
6479 #ifdef CONFIG_PROFILER
6480 qemu_time += profile_getclock() - ti;
6481 #endif
6482 if (ret == EXCP_HLT) {
6483 /* Give the next CPU a chance to run. */
6484 cur_cpu = env;
6485 continue;
6487 if (ret != EXCP_HALTED)
6488 break;
6489 /* all CPUs are halted ? */
6490 if (env == cur_cpu)
6491 break;
6493 cur_cpu = env;
6495 if (shutdown_requested) {
6496 ret = EXCP_INTERRUPT;
6497 break;
6499 if (reset_requested) {
6500 reset_requested = 0;
6501 qemu_system_reset();
6502 ret = EXCP_INTERRUPT;
6504 if (powerdown_requested) {
6505 powerdown_requested = 0;
6506 qemu_system_powerdown();
6507 ret = EXCP_INTERRUPT;
6509 if (ret == EXCP_DEBUG) {
6510 vm_stop(EXCP_DEBUG);
6512 /* If all cpus are halted then wait until the next IRQ */
6513 /* XXX: use timeout computed from timers */
6514 if (ret == EXCP_HALTED)
6515 timeout = 10;
6516 else
6517 timeout = 0;
6518 } else {
6519 timeout = 10;
6521 #ifdef CONFIG_PROFILER
6522 ti = profile_getclock();
6523 #endif
6524 main_loop_wait(timeout);
6525 #ifdef CONFIG_PROFILER
6526 dev_time += profile_getclock() - ti;
6527 #endif
6529 cpu_disable_ticks();
6530 return ret;
6533 void help(void)
6535 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6536 "usage: %s [options] [disk_image]\n"
6537 "\n"
6538 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6539 "\n"
6540 "Standard options:\n"
6541 "-M machine select emulated machine (-M ? for list)\n"
6542 "-cpu cpu select CPU (-cpu ? for list)\n"
6543 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6544 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6545 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6546 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6547 "-mtdblock file use 'file' as on-board Flash memory image\n"
6548 "-sd file use 'file' as SecureDigital card image\n"
6549 "-pflash file use 'file' as a parallel flash image\n"
6550 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6551 "-snapshot write to temporary files instead of disk image files\n"
6552 #ifdef CONFIG_SDL
6553 "-no-frame open SDL window without a frame and window decorations\n"
6554 "-no-quit disable SDL window close capability\n"
6555 #endif
6556 #ifdef TARGET_I386
6557 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6558 #endif
6559 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6560 "-smp n set the number of CPUs to 'n' [default=1]\n"
6561 "-nographic disable graphical output and redirect serial I/Os to console\n"
6562 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6563 #ifndef _WIN32
6564 "-k language use keyboard layout (for example \"fr\" for French)\n"
6565 #endif
6566 #ifdef HAS_AUDIO
6567 "-audio-help print list of audio drivers and their options\n"
6568 "-soundhw c1,... enable audio support\n"
6569 " and only specified sound cards (comma separated list)\n"
6570 " use -soundhw ? to get the list of supported cards\n"
6571 " use -soundhw all to enable all of them\n"
6572 #endif
6573 "-localtime set the real time clock to local time [default=utc]\n"
6574 "-full-screen start in full screen\n"
6575 #ifdef TARGET_I386
6576 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6577 #endif
6578 "-usb enable the USB driver (will be the default soon)\n"
6579 "-usbdevice name add the host or guest USB device 'name'\n"
6580 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6581 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6582 #endif
6583 "-name string set the name of the guest\n"
6584 "\n"
6585 "Network options:\n"
6586 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6587 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6588 #ifdef CONFIG_SLIRP
6589 "-net user[,vlan=n][,hostname=host]\n"
6590 " connect the user mode network stack to VLAN 'n' and send\n"
6591 " hostname 'host' to DHCP clients\n"
6592 #endif
6593 #ifdef _WIN32
6594 "-net tap[,vlan=n],ifname=name\n"
6595 " connect the host TAP network interface to VLAN 'n'\n"
6596 #else
6597 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6598 " connect the host TAP network interface to VLAN 'n' and use\n"
6599 " the network script 'file' (default=%s);\n"
6600 " use 'script=no' to disable script execution;\n"
6601 " use 'fd=h' to connect to an already opened TAP interface\n"
6602 #endif
6603 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6604 " connect the vlan 'n' to another VLAN using a socket connection\n"
6605 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6606 " connect the vlan 'n' to multicast maddr and port\n"
6607 "-net none use it alone to have zero network devices; if no -net option\n"
6608 " is provided, the default is '-net nic -net user'\n"
6609 "\n"
6610 #ifdef CONFIG_SLIRP
6611 "-tftp dir allow tftp access to files in dir [-net user]\n"
6612 "-bootp file advertise file in BOOTP replies\n"
6613 #ifndef _WIN32
6614 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6615 #endif
6616 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6617 " redirect TCP or UDP connections from host to guest [-net user]\n"
6618 #endif
6619 "\n"
6620 "Linux boot specific:\n"
6621 "-kernel bzImage use 'bzImage' as kernel image\n"
6622 "-append cmdline use 'cmdline' as kernel command line\n"
6623 "-initrd file use 'file' as initial ram disk\n"
6624 "\n"
6625 "Debug/Expert options:\n"
6626 "-monitor dev redirect the monitor to char device 'dev'\n"
6627 "-serial dev redirect the serial port to char device 'dev'\n"
6628 "-parallel dev redirect the parallel port to char device 'dev'\n"
6629 "-pidfile file Write PID to 'file'\n"
6630 "-S freeze CPU at startup (use 'c' to start execution)\n"
6631 "-s wait gdb connection to port\n"
6632 "-p port set gdb connection port [default=%s]\n"
6633 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6634 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6635 " translation (t=none or lba) (usually qemu can guess them)\n"
6636 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6637 #ifdef USE_KQEMU
6638 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6639 "-no-kqemu disable KQEMU kernel module usage\n"
6640 #endif
6641 #ifdef USE_CODE_COPY
6642 "-no-code-copy disable code copy acceleration\n"
6643 #endif
6644 #ifdef TARGET_I386
6645 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6646 " (default is CL-GD5446 PCI VGA)\n"
6647 "-no-acpi disable ACPI\n"
6648 #endif
6649 "-no-reboot exit instead of rebooting\n"
6650 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6651 "-vnc display start a VNC server on display\n"
6652 #ifndef _WIN32
6653 "-daemonize daemonize QEMU after initializing\n"
6654 #endif
6655 "-option-rom rom load a file, rom, into the option ROM space\n"
6656 #ifdef TARGET_SPARC
6657 "-prom-env variable=value set OpenBIOS nvram variables\n"
6658 #endif
6659 "\n"
6660 "During emulation, the following keys are useful:\n"
6661 "ctrl-alt-f toggle full screen\n"
6662 "ctrl-alt-n switch to virtual console 'n'\n"
6663 "ctrl-alt toggle mouse and keyboard grab\n"
6664 "\n"
6665 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6667 "qemu",
6668 DEFAULT_RAM_SIZE,
6669 #ifndef _WIN32
6670 DEFAULT_NETWORK_SCRIPT,
6671 #endif
6672 DEFAULT_GDBSTUB_PORT,
6673 "/tmp/qemu.log");
6674 exit(1);
6677 #define HAS_ARG 0x0001
6679 enum {
6680 QEMU_OPTION_h,
6682 QEMU_OPTION_M,
6683 QEMU_OPTION_cpu,
6684 QEMU_OPTION_fda,
6685 QEMU_OPTION_fdb,
6686 QEMU_OPTION_hda,
6687 QEMU_OPTION_hdb,
6688 QEMU_OPTION_hdc,
6689 QEMU_OPTION_hdd,
6690 QEMU_OPTION_cdrom,
6691 QEMU_OPTION_mtdblock,
6692 QEMU_OPTION_sd,
6693 QEMU_OPTION_pflash,
6694 QEMU_OPTION_boot,
6695 QEMU_OPTION_snapshot,
6696 #ifdef TARGET_I386
6697 QEMU_OPTION_no_fd_bootchk,
6698 #endif
6699 QEMU_OPTION_m,
6700 QEMU_OPTION_nographic,
6701 QEMU_OPTION_portrait,
6702 #ifdef HAS_AUDIO
6703 QEMU_OPTION_audio_help,
6704 QEMU_OPTION_soundhw,
6705 #endif
6707 QEMU_OPTION_net,
6708 QEMU_OPTION_tftp,
6709 QEMU_OPTION_bootp,
6710 QEMU_OPTION_smb,
6711 QEMU_OPTION_redir,
6713 QEMU_OPTION_kernel,
6714 QEMU_OPTION_append,
6715 QEMU_OPTION_initrd,
6717 QEMU_OPTION_S,
6718 QEMU_OPTION_s,
6719 QEMU_OPTION_p,
6720 QEMU_OPTION_d,
6721 QEMU_OPTION_hdachs,
6722 QEMU_OPTION_L,
6723 QEMU_OPTION_no_code_copy,
6724 QEMU_OPTION_k,
6725 QEMU_OPTION_localtime,
6726 QEMU_OPTION_cirrusvga,
6727 QEMU_OPTION_vmsvga,
6728 QEMU_OPTION_g,
6729 QEMU_OPTION_std_vga,
6730 QEMU_OPTION_echr,
6731 QEMU_OPTION_monitor,
6732 QEMU_OPTION_serial,
6733 QEMU_OPTION_parallel,
6734 QEMU_OPTION_loadvm,
6735 QEMU_OPTION_full_screen,
6736 QEMU_OPTION_no_frame,
6737 QEMU_OPTION_no_quit,
6738 QEMU_OPTION_pidfile,
6739 QEMU_OPTION_no_kqemu,
6740 QEMU_OPTION_kernel_kqemu,
6741 QEMU_OPTION_win2k_hack,
6742 QEMU_OPTION_usb,
6743 QEMU_OPTION_usbdevice,
6744 QEMU_OPTION_smp,
6745 QEMU_OPTION_vnc,
6746 QEMU_OPTION_no_acpi,
6747 QEMU_OPTION_no_reboot,
6748 QEMU_OPTION_show_cursor,
6749 QEMU_OPTION_daemonize,
6750 QEMU_OPTION_option_rom,
6751 QEMU_OPTION_semihosting,
6752 QEMU_OPTION_name,
6753 QEMU_OPTION_prom_env,
6756 typedef struct QEMUOption {
6757 const char *name;
6758 int flags;
6759 int index;
6760 } QEMUOption;
6762 const QEMUOption qemu_options[] = {
6763 { "h", 0, QEMU_OPTION_h },
6764 { "help", 0, QEMU_OPTION_h },
6766 { "M", HAS_ARG, QEMU_OPTION_M },
6767 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6768 { "fda", HAS_ARG, QEMU_OPTION_fda },
6769 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6770 { "hda", HAS_ARG, QEMU_OPTION_hda },
6771 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6772 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6773 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6774 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6775 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6776 { "sd", HAS_ARG, QEMU_OPTION_sd },
6777 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6778 { "boot", HAS_ARG, QEMU_OPTION_boot },
6779 { "snapshot", 0, QEMU_OPTION_snapshot },
6780 #ifdef TARGET_I386
6781 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6782 #endif
6783 { "m", HAS_ARG, QEMU_OPTION_m },
6784 { "nographic", 0, QEMU_OPTION_nographic },
6785 { "portrait", 0, QEMU_OPTION_portrait },
6786 { "k", HAS_ARG, QEMU_OPTION_k },
6787 #ifdef HAS_AUDIO
6788 { "audio-help", 0, QEMU_OPTION_audio_help },
6789 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6790 #endif
6792 { "net", HAS_ARG, QEMU_OPTION_net},
6793 #ifdef CONFIG_SLIRP
6794 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6795 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6796 #ifndef _WIN32
6797 { "smb", HAS_ARG, QEMU_OPTION_smb },
6798 #endif
6799 { "redir", HAS_ARG, QEMU_OPTION_redir },
6800 #endif
6802 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6803 { "append", HAS_ARG, QEMU_OPTION_append },
6804 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6806 { "S", 0, QEMU_OPTION_S },
6807 { "s", 0, QEMU_OPTION_s },
6808 { "p", HAS_ARG, QEMU_OPTION_p },
6809 { "d", HAS_ARG, QEMU_OPTION_d },
6810 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6811 { "L", HAS_ARG, QEMU_OPTION_L },
6812 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6813 #ifdef USE_KQEMU
6814 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6815 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6816 #endif
6817 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6818 { "g", 1, QEMU_OPTION_g },
6819 #endif
6820 { "localtime", 0, QEMU_OPTION_localtime },
6821 { "std-vga", 0, QEMU_OPTION_std_vga },
6822 { "echr", 1, QEMU_OPTION_echr },
6823 { "monitor", 1, QEMU_OPTION_monitor },
6824 { "serial", 1, QEMU_OPTION_serial },
6825 { "parallel", 1, QEMU_OPTION_parallel },
6826 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6827 { "full-screen", 0, QEMU_OPTION_full_screen },
6828 #ifdef CONFIG_SDL
6829 { "no-frame", 0, QEMU_OPTION_no_frame },
6830 { "no-quit", 0, QEMU_OPTION_no_quit },
6831 #endif
6832 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6833 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6834 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6835 { "smp", HAS_ARG, QEMU_OPTION_smp },
6836 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6838 /* temporary options */
6839 { "usb", 0, QEMU_OPTION_usb },
6840 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6841 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6842 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6843 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6844 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6845 { "daemonize", 0, QEMU_OPTION_daemonize },
6846 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6847 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6848 { "semihosting", 0, QEMU_OPTION_semihosting },
6849 #endif
6850 { "name", HAS_ARG, QEMU_OPTION_name },
6851 #if defined(TARGET_SPARC)
6852 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6853 #endif
6854 { NULL },
6857 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6859 /* this stack is only used during signal handling */
6860 #define SIGNAL_STACK_SIZE 32768
6862 static uint8_t *signal_stack;
6864 #endif
6866 /* password input */
6868 int qemu_key_check(BlockDriverState *bs, const char *name)
6870 char password[256];
6871 int i;
6873 if (!bdrv_is_encrypted(bs))
6874 return 0;
6876 term_printf("%s is encrypted.\n", name);
6877 for(i = 0; i < 3; i++) {
6878 monitor_readline("Password: ", 1, password, sizeof(password));
6879 if (bdrv_set_key(bs, password) == 0)
6880 return 0;
6881 term_printf("invalid password\n");
6883 return -EPERM;
6886 static BlockDriverState *get_bdrv(int index)
6888 BlockDriverState *bs;
6890 if (index < 4) {
6891 bs = bs_table[index];
6892 } else if (index < 6) {
6893 bs = fd_table[index - 4];
6894 } else {
6895 bs = NULL;
6897 return bs;
6900 static void read_passwords(void)
6902 BlockDriverState *bs;
6903 int i;
6905 for(i = 0; i < 6; i++) {
6906 bs = get_bdrv(i);
6907 if (bs)
6908 qemu_key_check(bs, bdrv_get_device_name(bs));
6912 /* XXX: currently we cannot use simultaneously different CPUs */
6913 void register_machines(void)
6915 #if defined(TARGET_I386)
6916 qemu_register_machine(&pc_machine);
6917 qemu_register_machine(&isapc_machine);
6918 #elif defined(TARGET_PPC)
6919 qemu_register_machine(&heathrow_machine);
6920 qemu_register_machine(&core99_machine);
6921 qemu_register_machine(&prep_machine);
6922 qemu_register_machine(&ref405ep_machine);
6923 qemu_register_machine(&taihu_machine);
6924 #elif defined(TARGET_MIPS)
6925 qemu_register_machine(&mips_machine);
6926 qemu_register_machine(&mips_malta_machine);
6927 qemu_register_machine(&mips_pica61_machine);
6928 #elif defined(TARGET_SPARC)
6929 #ifdef TARGET_SPARC64
6930 qemu_register_machine(&sun4u_machine);
6931 #else
6932 qemu_register_machine(&ss5_machine);
6933 qemu_register_machine(&ss10_machine);
6934 #endif
6935 #elif defined(TARGET_ARM)
6936 qemu_register_machine(&integratorcp_machine);
6937 qemu_register_machine(&versatilepb_machine);
6938 qemu_register_machine(&versatileab_machine);
6939 qemu_register_machine(&realview_machine);
6940 qemu_register_machine(&akitapda_machine);
6941 qemu_register_machine(&spitzpda_machine);
6942 qemu_register_machine(&borzoipda_machine);
6943 qemu_register_machine(&terrierpda_machine);
6944 #elif defined(TARGET_SH4)
6945 qemu_register_machine(&shix_machine);
6946 #elif defined(TARGET_ALPHA)
6947 /* XXX: TODO */
6948 #elif defined(TARGET_M68K)
6949 qemu_register_machine(&mcf5208evb_machine);
6950 qemu_register_machine(&an5206_machine);
6951 #else
6952 #error unsupported CPU
6953 #endif
6956 #ifdef HAS_AUDIO
6957 struct soundhw soundhw[] = {
6958 #ifdef HAS_AUDIO_CHOICE
6959 #ifdef TARGET_I386
6961 "pcspk",
6962 "PC speaker",
6965 { .init_isa = pcspk_audio_init }
6967 #endif
6969 "sb16",
6970 "Creative Sound Blaster 16",
6973 { .init_isa = SB16_init }
6976 #ifdef CONFIG_ADLIB
6978 "adlib",
6979 #ifdef HAS_YMF262
6980 "Yamaha YMF262 (OPL3)",
6981 #else
6982 "Yamaha YM3812 (OPL2)",
6983 #endif
6986 { .init_isa = Adlib_init }
6988 #endif
6990 #ifdef CONFIG_GUS
6992 "gus",
6993 "Gravis Ultrasound GF1",
6996 { .init_isa = GUS_init }
6998 #endif
7001 "es1370",
7002 "ENSONIQ AudioPCI ES1370",
7005 { .init_pci = es1370_init }
7007 #endif
7009 { NULL, NULL, 0, 0, { NULL } }
7012 static void select_soundhw (const char *optarg)
7014 struct soundhw *c;
7016 if (*optarg == '?') {
7017 show_valid_cards:
7019 printf ("Valid sound card names (comma separated):\n");
7020 for (c = soundhw; c->name; ++c) {
7021 printf ("%-11s %s\n", c->name, c->descr);
7023 printf ("\n-soundhw all will enable all of the above\n");
7024 exit (*optarg != '?');
7026 else {
7027 size_t l;
7028 const char *p;
7029 char *e;
7030 int bad_card = 0;
7032 if (!strcmp (optarg, "all")) {
7033 for (c = soundhw; c->name; ++c) {
7034 c->enabled = 1;
7036 return;
7039 p = optarg;
7040 while (*p) {
7041 e = strchr (p, ',');
7042 l = !e ? strlen (p) : (size_t) (e - p);
7044 for (c = soundhw; c->name; ++c) {
7045 if (!strncmp (c->name, p, l)) {
7046 c->enabled = 1;
7047 break;
7051 if (!c->name) {
7052 if (l > 80) {
7053 fprintf (stderr,
7054 "Unknown sound card name (too big to show)\n");
7056 else {
7057 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7058 (int) l, p);
7060 bad_card = 1;
7062 p += l + (e != NULL);
7065 if (bad_card)
7066 goto show_valid_cards;
7069 #endif
7071 #ifdef _WIN32
7072 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7074 exit(STATUS_CONTROL_C_EXIT);
7075 return TRUE;
7077 #endif
7079 #define MAX_NET_CLIENTS 32
7081 int main(int argc, char **argv)
7083 #ifdef CONFIG_GDBSTUB
7084 int use_gdbstub;
7085 const char *gdbstub_port;
7086 #endif
7087 int i, cdrom_index, pflash_index;
7088 int snapshot, linux_boot;
7089 const char *initrd_filename;
7090 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7091 const char *pflash_filename[MAX_PFLASH];
7092 const char *sd_filename;
7093 const char *mtd_filename;
7094 const char *kernel_filename, *kernel_cmdline;
7095 DisplayState *ds = &display_state;
7096 int cyls, heads, secs, translation;
7097 char net_clients[MAX_NET_CLIENTS][256];
7098 int nb_net_clients;
7099 int optind;
7100 const char *r, *optarg;
7101 CharDriverState *monitor_hd;
7102 char monitor_device[128];
7103 char serial_devices[MAX_SERIAL_PORTS][128];
7104 int serial_device_index;
7105 char parallel_devices[MAX_PARALLEL_PORTS][128];
7106 int parallel_device_index;
7107 const char *loadvm = NULL;
7108 QEMUMachine *machine;
7109 const char *cpu_model;
7110 char usb_devices[MAX_USB_CMDLINE][128];
7111 int usb_devices_index;
7112 int fds[2];
7113 const char *pid_file = NULL;
7114 VLANState *vlan;
7116 LIST_INIT (&vm_change_state_head);
7117 #ifndef _WIN32
7119 struct sigaction act;
7120 sigfillset(&act.sa_mask);
7121 act.sa_flags = 0;
7122 act.sa_handler = SIG_IGN;
7123 sigaction(SIGPIPE, &act, NULL);
7125 #else
7126 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7127 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7128 QEMU to run on a single CPU */
7130 HANDLE h;
7131 DWORD mask, smask;
7132 int i;
7133 h = GetCurrentProcess();
7134 if (GetProcessAffinityMask(h, &mask, &smask)) {
7135 for(i = 0; i < 32; i++) {
7136 if (mask & (1 << i))
7137 break;
7139 if (i != 32) {
7140 mask = 1 << i;
7141 SetProcessAffinityMask(h, mask);
7145 #endif
7147 register_machines();
7148 machine = first_machine;
7149 cpu_model = NULL;
7150 initrd_filename = NULL;
7151 for(i = 0; i < MAX_FD; i++)
7152 fd_filename[i] = NULL;
7153 for(i = 0; i < MAX_DISKS; i++)
7154 hd_filename[i] = NULL;
7155 for(i = 0; i < MAX_PFLASH; i++)
7156 pflash_filename[i] = NULL;
7157 pflash_index = 0;
7158 sd_filename = NULL;
7159 mtd_filename = NULL;
7160 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7161 vga_ram_size = VGA_RAM_SIZE;
7162 #ifdef CONFIG_GDBSTUB
7163 use_gdbstub = 0;
7164 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7165 #endif
7166 snapshot = 0;
7167 nographic = 0;
7168 kernel_filename = NULL;
7169 kernel_cmdline = "";
7170 #ifdef TARGET_PPC
7171 cdrom_index = 1;
7172 #else
7173 cdrom_index = 2;
7174 #endif
7175 cyls = heads = secs = 0;
7176 translation = BIOS_ATA_TRANSLATION_AUTO;
7177 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7179 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7180 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7181 serial_devices[i][0] = '\0';
7182 serial_device_index = 0;
7184 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7185 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7186 parallel_devices[i][0] = '\0';
7187 parallel_device_index = 0;
7189 usb_devices_index = 0;
7191 nb_net_clients = 0;
7193 nb_nics = 0;
7194 /* default mac address of the first network interface */
7196 optind = 1;
7197 for(;;) {
7198 if (optind >= argc)
7199 break;
7200 r = argv[optind];
7201 if (r[0] != '-') {
7202 hd_filename[0] = argv[optind++];
7203 } else {
7204 const QEMUOption *popt;
7206 optind++;
7207 /* Treat --foo the same as -foo. */
7208 if (r[1] == '-')
7209 r++;
7210 popt = qemu_options;
7211 for(;;) {
7212 if (!popt->name) {
7213 fprintf(stderr, "%s: invalid option -- '%s'\n",
7214 argv[0], r);
7215 exit(1);
7217 if (!strcmp(popt->name, r + 1))
7218 break;
7219 popt++;
7221 if (popt->flags & HAS_ARG) {
7222 if (optind >= argc) {
7223 fprintf(stderr, "%s: option '%s' requires an argument\n",
7224 argv[0], r);
7225 exit(1);
7227 optarg = argv[optind++];
7228 } else {
7229 optarg = NULL;
7232 switch(popt->index) {
7233 case QEMU_OPTION_M:
7234 machine = find_machine(optarg);
7235 if (!machine) {
7236 QEMUMachine *m;
7237 printf("Supported machines are:\n");
7238 for(m = first_machine; m != NULL; m = m->next) {
7239 printf("%-10s %s%s\n",
7240 m->name, m->desc,
7241 m == first_machine ? " (default)" : "");
7243 exit(1);
7245 break;
7246 case QEMU_OPTION_cpu:
7247 /* hw initialization will check this */
7248 if (optarg[0] == '?') {
7249 #if defined(TARGET_PPC)
7250 ppc_cpu_list(stdout, &fprintf);
7251 #elif defined(TARGET_ARM)
7252 arm_cpu_list();
7253 #elif defined(TARGET_MIPS)
7254 mips_cpu_list(stdout, &fprintf);
7255 #elif defined(TARGET_SPARC)
7256 sparc_cpu_list(stdout, &fprintf);
7257 #endif
7258 exit(1);
7259 } else {
7260 cpu_model = optarg;
7262 break;
7263 case QEMU_OPTION_initrd:
7264 initrd_filename = optarg;
7265 break;
7266 case QEMU_OPTION_hda:
7267 case QEMU_OPTION_hdb:
7268 case QEMU_OPTION_hdc:
7269 case QEMU_OPTION_hdd:
7271 int hd_index;
7272 hd_index = popt->index - QEMU_OPTION_hda;
7273 hd_filename[hd_index] = optarg;
7274 if (hd_index == cdrom_index)
7275 cdrom_index = -1;
7277 break;
7278 case QEMU_OPTION_mtdblock:
7279 mtd_filename = optarg;
7280 break;
7281 case QEMU_OPTION_sd:
7282 sd_filename = optarg;
7283 break;
7284 case QEMU_OPTION_pflash:
7285 if (pflash_index >= MAX_PFLASH) {
7286 fprintf(stderr, "qemu: too many parallel flash images\n");
7287 exit(1);
7289 pflash_filename[pflash_index++] = optarg;
7290 break;
7291 case QEMU_OPTION_snapshot:
7292 snapshot = 1;
7293 break;
7294 case QEMU_OPTION_hdachs:
7296 const char *p;
7297 p = optarg;
7298 cyls = strtol(p, (char **)&p, 0);
7299 if (cyls < 1 || cyls > 16383)
7300 goto chs_fail;
7301 if (*p != ',')
7302 goto chs_fail;
7303 p++;
7304 heads = strtol(p, (char **)&p, 0);
7305 if (heads < 1 || heads > 16)
7306 goto chs_fail;
7307 if (*p != ',')
7308 goto chs_fail;
7309 p++;
7310 secs = strtol(p, (char **)&p, 0);
7311 if (secs < 1 || secs > 63)
7312 goto chs_fail;
7313 if (*p == ',') {
7314 p++;
7315 if (!strcmp(p, "none"))
7316 translation = BIOS_ATA_TRANSLATION_NONE;
7317 else if (!strcmp(p, "lba"))
7318 translation = BIOS_ATA_TRANSLATION_LBA;
7319 else if (!strcmp(p, "auto"))
7320 translation = BIOS_ATA_TRANSLATION_AUTO;
7321 else
7322 goto chs_fail;
7323 } else if (*p != '\0') {
7324 chs_fail:
7325 fprintf(stderr, "qemu: invalid physical CHS format\n");
7326 exit(1);
7329 break;
7330 case QEMU_OPTION_nographic:
7331 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7332 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7333 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7334 nographic = 1;
7335 break;
7336 case QEMU_OPTION_portrait:
7337 graphic_rotate = 1;
7338 break;
7339 case QEMU_OPTION_kernel:
7340 kernel_filename = optarg;
7341 break;
7342 case QEMU_OPTION_append:
7343 kernel_cmdline = optarg;
7344 break;
7345 case QEMU_OPTION_cdrom:
7346 if (cdrom_index >= 0) {
7347 hd_filename[cdrom_index] = optarg;
7349 break;
7350 case QEMU_OPTION_boot:
7351 boot_device = optarg[0];
7352 if (boot_device != 'a' &&
7353 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7354 // Network boot
7355 boot_device != 'n' &&
7356 #endif
7357 boot_device != 'c' && boot_device != 'd') {
7358 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7359 exit(1);
7361 break;
7362 case QEMU_OPTION_fda:
7363 fd_filename[0] = optarg;
7364 break;
7365 case QEMU_OPTION_fdb:
7366 fd_filename[1] = optarg;
7367 break;
7368 #ifdef TARGET_I386
7369 case QEMU_OPTION_no_fd_bootchk:
7370 fd_bootchk = 0;
7371 break;
7372 #endif
7373 case QEMU_OPTION_no_code_copy:
7374 code_copy_enabled = 0;
7375 break;
7376 case QEMU_OPTION_net:
7377 if (nb_net_clients >= MAX_NET_CLIENTS) {
7378 fprintf(stderr, "qemu: too many network clients\n");
7379 exit(1);
7381 pstrcpy(net_clients[nb_net_clients],
7382 sizeof(net_clients[0]),
7383 optarg);
7384 nb_net_clients++;
7385 break;
7386 #ifdef CONFIG_SLIRP
7387 case QEMU_OPTION_tftp:
7388 tftp_prefix = optarg;
7389 break;
7390 case QEMU_OPTION_bootp:
7391 bootp_filename = optarg;
7392 break;
7393 #ifndef _WIN32
7394 case QEMU_OPTION_smb:
7395 net_slirp_smb(optarg);
7396 break;
7397 #endif
7398 case QEMU_OPTION_redir:
7399 net_slirp_redir(optarg);
7400 break;
7401 #endif
7402 #ifdef HAS_AUDIO
7403 case QEMU_OPTION_audio_help:
7404 AUD_help ();
7405 exit (0);
7406 break;
7407 case QEMU_OPTION_soundhw:
7408 select_soundhw (optarg);
7409 break;
7410 #endif
7411 case QEMU_OPTION_h:
7412 help();
7413 break;
7414 case QEMU_OPTION_m:
7415 ram_size = atoi(optarg) * 1024 * 1024;
7416 if (ram_size <= 0)
7417 help();
7418 if (ram_size > PHYS_RAM_MAX_SIZE) {
7419 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7420 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7421 exit(1);
7423 break;
7424 case QEMU_OPTION_d:
7426 int mask;
7427 CPULogItem *item;
7429 mask = cpu_str_to_log_mask(optarg);
7430 if (!mask) {
7431 printf("Log items (comma separated):\n");
7432 for(item = cpu_log_items; item->mask != 0; item++) {
7433 printf("%-10s %s\n", item->name, item->help);
7435 exit(1);
7437 cpu_set_log(mask);
7439 break;
7440 #ifdef CONFIG_GDBSTUB
7441 case QEMU_OPTION_s:
7442 use_gdbstub = 1;
7443 break;
7444 case QEMU_OPTION_p:
7445 gdbstub_port = optarg;
7446 break;
7447 #endif
7448 case QEMU_OPTION_L:
7449 bios_dir = optarg;
7450 break;
7451 case QEMU_OPTION_S:
7452 autostart = 0;
7453 break;
7454 case QEMU_OPTION_k:
7455 keyboard_layout = optarg;
7456 break;
7457 case QEMU_OPTION_localtime:
7458 rtc_utc = 0;
7459 break;
7460 case QEMU_OPTION_cirrusvga:
7461 cirrus_vga_enabled = 1;
7462 vmsvga_enabled = 0;
7463 break;
7464 case QEMU_OPTION_vmsvga:
7465 cirrus_vga_enabled = 0;
7466 vmsvga_enabled = 1;
7467 break;
7468 case QEMU_OPTION_std_vga:
7469 cirrus_vga_enabled = 0;
7470 vmsvga_enabled = 0;
7471 break;
7472 case QEMU_OPTION_g:
7474 const char *p;
7475 int w, h, depth;
7476 p = optarg;
7477 w = strtol(p, (char **)&p, 10);
7478 if (w <= 0) {
7479 graphic_error:
7480 fprintf(stderr, "qemu: invalid resolution or depth\n");
7481 exit(1);
7483 if (*p != 'x')
7484 goto graphic_error;
7485 p++;
7486 h = strtol(p, (char **)&p, 10);
7487 if (h <= 0)
7488 goto graphic_error;
7489 if (*p == 'x') {
7490 p++;
7491 depth = strtol(p, (char **)&p, 10);
7492 if (depth != 8 && depth != 15 && depth != 16 &&
7493 depth != 24 && depth != 32)
7494 goto graphic_error;
7495 } else if (*p == '\0') {
7496 depth = graphic_depth;
7497 } else {
7498 goto graphic_error;
7501 graphic_width = w;
7502 graphic_height = h;
7503 graphic_depth = depth;
7505 break;
7506 case QEMU_OPTION_echr:
7508 char *r;
7509 term_escape_char = strtol(optarg, &r, 0);
7510 if (r == optarg)
7511 printf("Bad argument to echr\n");
7512 break;
7514 case QEMU_OPTION_monitor:
7515 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7516 break;
7517 case QEMU_OPTION_serial:
7518 if (serial_device_index >= MAX_SERIAL_PORTS) {
7519 fprintf(stderr, "qemu: too many serial ports\n");
7520 exit(1);
7522 pstrcpy(serial_devices[serial_device_index],
7523 sizeof(serial_devices[0]), optarg);
7524 serial_device_index++;
7525 break;
7526 case QEMU_OPTION_parallel:
7527 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7528 fprintf(stderr, "qemu: too many parallel ports\n");
7529 exit(1);
7531 pstrcpy(parallel_devices[parallel_device_index],
7532 sizeof(parallel_devices[0]), optarg);
7533 parallel_device_index++;
7534 break;
7535 case QEMU_OPTION_loadvm:
7536 loadvm = optarg;
7537 break;
7538 case QEMU_OPTION_full_screen:
7539 full_screen = 1;
7540 break;
7541 #ifdef CONFIG_SDL
7542 case QEMU_OPTION_no_frame:
7543 no_frame = 1;
7544 break;
7545 case QEMU_OPTION_no_quit:
7546 no_quit = 1;
7547 break;
7548 #endif
7549 case QEMU_OPTION_pidfile:
7550 pid_file = optarg;
7551 break;
7552 #ifdef TARGET_I386
7553 case QEMU_OPTION_win2k_hack:
7554 win2k_install_hack = 1;
7555 break;
7556 #endif
7557 #ifdef USE_KQEMU
7558 case QEMU_OPTION_no_kqemu:
7559 kqemu_allowed = 0;
7560 break;
7561 case QEMU_OPTION_kernel_kqemu:
7562 kqemu_allowed = 2;
7563 break;
7564 #endif
7565 case QEMU_OPTION_usb:
7566 usb_enabled = 1;
7567 break;
7568 case QEMU_OPTION_usbdevice:
7569 usb_enabled = 1;
7570 if (usb_devices_index >= MAX_USB_CMDLINE) {
7571 fprintf(stderr, "Too many USB devices\n");
7572 exit(1);
7574 pstrcpy(usb_devices[usb_devices_index],
7575 sizeof(usb_devices[usb_devices_index]),
7576 optarg);
7577 usb_devices_index++;
7578 break;
7579 case QEMU_OPTION_smp:
7580 smp_cpus = atoi(optarg);
7581 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7582 fprintf(stderr, "Invalid number of CPUs\n");
7583 exit(1);
7585 break;
7586 case QEMU_OPTION_vnc:
7587 vnc_display = optarg;
7588 break;
7589 case QEMU_OPTION_no_acpi:
7590 acpi_enabled = 0;
7591 break;
7592 case QEMU_OPTION_no_reboot:
7593 no_reboot = 1;
7594 break;
7595 case QEMU_OPTION_show_cursor:
7596 cursor_hide = 0;
7597 break;
7598 case QEMU_OPTION_daemonize:
7599 daemonize = 1;
7600 break;
7601 case QEMU_OPTION_option_rom:
7602 if (nb_option_roms >= MAX_OPTION_ROMS) {
7603 fprintf(stderr, "Too many option ROMs\n");
7604 exit(1);
7606 option_rom[nb_option_roms] = optarg;
7607 nb_option_roms++;
7608 break;
7609 case QEMU_OPTION_semihosting:
7610 semihosting_enabled = 1;
7611 break;
7612 case QEMU_OPTION_name:
7613 qemu_name = optarg;
7614 break;
7615 #ifdef TARGET_SPARC
7616 case QEMU_OPTION_prom_env:
7617 if (nb_prom_envs >= MAX_PROM_ENVS) {
7618 fprintf(stderr, "Too many prom variables\n");
7619 exit(1);
7621 prom_envs[nb_prom_envs] = optarg;
7622 nb_prom_envs++;
7623 break;
7624 #endif
7629 #ifndef _WIN32
7630 if (daemonize && !nographic && vnc_display == NULL) {
7631 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7632 daemonize = 0;
7635 if (daemonize) {
7636 pid_t pid;
7638 if (pipe(fds) == -1)
7639 exit(1);
7641 pid = fork();
7642 if (pid > 0) {
7643 uint8_t status;
7644 ssize_t len;
7646 close(fds[1]);
7648 again:
7649 len = read(fds[0], &status, 1);
7650 if (len == -1 && (errno == EINTR))
7651 goto again;
7653 if (len != 1)
7654 exit(1);
7655 else if (status == 1) {
7656 fprintf(stderr, "Could not acquire pidfile\n");
7657 exit(1);
7658 } else
7659 exit(0);
7660 } else if (pid < 0)
7661 exit(1);
7663 setsid();
7665 pid = fork();
7666 if (pid > 0)
7667 exit(0);
7668 else if (pid < 0)
7669 exit(1);
7671 umask(027);
7672 chdir("/");
7674 signal(SIGTSTP, SIG_IGN);
7675 signal(SIGTTOU, SIG_IGN);
7676 signal(SIGTTIN, SIG_IGN);
7678 #endif
7680 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7681 if (daemonize) {
7682 uint8_t status = 1;
7683 write(fds[1], &status, 1);
7684 } else
7685 fprintf(stderr, "Could not acquire pid file\n");
7686 exit(1);
7689 #ifdef USE_KQEMU
7690 if (smp_cpus > 1)
7691 kqemu_allowed = 0;
7692 #endif
7693 linux_boot = (kernel_filename != NULL);
7695 if (!linux_boot &&
7696 boot_device != 'n' &&
7697 hd_filename[0] == '\0' &&
7698 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7699 fd_filename[0] == '\0')
7700 help();
7702 /* boot to floppy or the default cd if no hard disk defined yet */
7703 if (hd_filename[0] == '\0' && boot_device == 'c') {
7704 if (fd_filename[0] != '\0')
7705 boot_device = 'a';
7706 else
7707 boot_device = 'd';
7710 setvbuf(stdout, NULL, _IOLBF, 0);
7712 init_timers();
7713 init_timer_alarm();
7714 qemu_aio_init();
7716 #ifdef _WIN32
7717 socket_init();
7718 #endif
7720 /* init network clients */
7721 if (nb_net_clients == 0) {
7722 /* if no clients, we use a default config */
7723 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7724 "nic");
7725 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7726 "user");
7727 nb_net_clients = 2;
7730 for(i = 0;i < nb_net_clients; i++) {
7731 if (net_client_init(net_clients[i]) < 0)
7732 exit(1);
7734 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7735 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7736 continue;
7737 if (vlan->nb_guest_devs == 0) {
7738 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7739 exit(1);
7741 if (vlan->nb_host_devs == 0)
7742 fprintf(stderr,
7743 "Warning: vlan %d is not connected to host network\n",
7744 vlan->id);
7747 #ifdef TARGET_I386
7748 if (boot_device == 'n') {
7749 for (i = 0; i < nb_nics; i++) {
7750 const char *model = nd_table[i].model;
7751 char buf[1024];
7752 if (model == NULL)
7753 model = "ne2k_pci";
7754 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7755 if (get_image_size(buf) > 0) {
7756 option_rom[nb_option_roms] = strdup(buf);
7757 nb_option_roms++;
7758 break;
7761 if (i == nb_nics) {
7762 fprintf(stderr, "No valid PXE rom found for network device\n");
7763 exit(1);
7765 boot_device = 'c'; /* to prevent confusion by the BIOS */
7767 #endif
7769 /* init the memory */
7770 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7772 phys_ram_base = qemu_vmalloc(phys_ram_size);
7773 if (!phys_ram_base) {
7774 fprintf(stderr, "Could not allocate physical memory\n");
7775 exit(1);
7778 /* we always create the cdrom drive, even if no disk is there */
7779 bdrv_init();
7780 if (cdrom_index >= 0) {
7781 bs_table[cdrom_index] = bdrv_new("cdrom");
7782 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7785 /* open the virtual block devices */
7786 for(i = 0; i < MAX_DISKS; i++) {
7787 if (hd_filename[i]) {
7788 if (!bs_table[i]) {
7789 char buf[64];
7790 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7791 bs_table[i] = bdrv_new(buf);
7793 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7794 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7795 hd_filename[i]);
7796 exit(1);
7798 if (i == 0 && cyls != 0) {
7799 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7800 bdrv_set_translation_hint(bs_table[i], translation);
7805 /* we always create at least one floppy disk */
7806 fd_table[0] = bdrv_new("fda");
7807 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7809 for(i = 0; i < MAX_FD; i++) {
7810 if (fd_filename[i]) {
7811 if (!fd_table[i]) {
7812 char buf[64];
7813 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7814 fd_table[i] = bdrv_new(buf);
7815 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7817 if (fd_filename[i][0] != '\0') {
7818 if (bdrv_open(fd_table[i], fd_filename[i],
7819 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7820 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7821 fd_filename[i]);
7822 exit(1);
7828 /* Open the virtual parallel flash block devices */
7829 for(i = 0; i < MAX_PFLASH; i++) {
7830 if (pflash_filename[i]) {
7831 if (!pflash_table[i]) {
7832 char buf[64];
7833 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7834 pflash_table[i] = bdrv_new(buf);
7836 if (bdrv_open(pflash_table[i], pflash_filename[i],
7837 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7838 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7839 pflash_filename[i]);
7840 exit(1);
7845 sd_bdrv = bdrv_new ("sd");
7846 /* FIXME: This isn't really a floppy, but it's a reasonable
7847 approximation. */
7848 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7849 if (sd_filename) {
7850 if (bdrv_open(sd_bdrv, sd_filename,
7851 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7852 fprintf(stderr, "qemu: could not open SD card image %s\n",
7853 sd_filename);
7854 } else
7855 qemu_key_check(sd_bdrv, sd_filename);
7858 if (mtd_filename) {
7859 mtd_bdrv = bdrv_new ("mtd");
7860 if (bdrv_open(mtd_bdrv, mtd_filename,
7861 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7862 qemu_key_check(mtd_bdrv, mtd_filename)) {
7863 fprintf(stderr, "qemu: could not open Flash image %s\n",
7864 mtd_filename);
7865 bdrv_delete(mtd_bdrv);
7866 mtd_bdrv = 0;
7870 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7871 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7873 init_ioports();
7875 /* terminal init */
7876 memset(&display_state, 0, sizeof(display_state));
7877 if (nographic) {
7878 /* nothing to do */
7879 } else if (vnc_display != NULL) {
7880 vnc_display_init(ds, vnc_display);
7881 } else {
7882 #if defined(CONFIG_SDL)
7883 sdl_display_init(ds, full_screen, no_frame);
7884 #elif defined(CONFIG_COCOA)
7885 cocoa_display_init(ds, full_screen);
7886 #endif
7889 /* Maintain compatibility with multiple stdio monitors */
7890 if (!strcmp(monitor_device,"stdio")) {
7891 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7892 if (!strcmp(serial_devices[i],"mon:stdio")) {
7893 monitor_device[0] = '\0';
7894 break;
7895 } else if (!strcmp(serial_devices[i],"stdio")) {
7896 monitor_device[0] = '\0';
7897 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7898 break;
7902 if (monitor_device[0] != '\0') {
7903 monitor_hd = qemu_chr_open(monitor_device);
7904 if (!monitor_hd) {
7905 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7906 exit(1);
7908 monitor_init(monitor_hd, !nographic);
7911 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7912 const char *devname = serial_devices[i];
7913 if (devname[0] != '\0' && strcmp(devname, "none")) {
7914 serial_hds[i] = qemu_chr_open(devname);
7915 if (!serial_hds[i]) {
7916 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7917 devname);
7918 exit(1);
7920 if (!strcmp(devname, "vc"))
7921 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7925 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7926 const char *devname = parallel_devices[i];
7927 if (devname[0] != '\0' && strcmp(devname, "none")) {
7928 parallel_hds[i] = qemu_chr_open(devname);
7929 if (!parallel_hds[i]) {
7930 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7931 devname);
7932 exit(1);
7934 if (!strcmp(devname, "vc"))
7935 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7939 machine->init(ram_size, vga_ram_size, boot_device,
7940 ds, fd_filename, snapshot,
7941 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7943 /* init USB devices */
7944 if (usb_enabled) {
7945 for(i = 0; i < usb_devices_index; i++) {
7946 if (usb_device_add(usb_devices[i]) < 0) {
7947 fprintf(stderr, "Warning: could not add USB device %s\n",
7948 usb_devices[i]);
7953 if (display_state.dpy_refresh) {
7954 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
7955 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
7958 #ifdef CONFIG_GDBSTUB
7959 if (use_gdbstub) {
7960 /* XXX: use standard host:port notation and modify options
7961 accordingly. */
7962 if (gdbserver_start(gdbstub_port) < 0) {
7963 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7964 gdbstub_port);
7965 exit(1);
7967 } else
7968 #endif
7969 if (loadvm)
7970 do_loadvm(loadvm);
7973 /* XXX: simplify init */
7974 read_passwords();
7975 if (autostart) {
7976 vm_start();
7980 if (daemonize) {
7981 uint8_t status = 0;
7982 ssize_t len;
7983 int fd;
7985 again1:
7986 len = write(fds[1], &status, 1);
7987 if (len == -1 && (errno == EINTR))
7988 goto again1;
7990 if (len != 1)
7991 exit(1);
7993 fd = open("/dev/null", O_RDWR);
7994 if (fd == -1)
7995 exit(1);
7997 dup2(fd, 0);
7998 dup2(fd, 1);
7999 dup2(fd, 2);
8001 close(fd);
8004 main_loop();
8005 quit_timers();
8006 return 0;