PowerPC improvments:
[qemu/mini2440.git] / vl.c
blob87bb1bcd50f49e0f1eb55e453f38a6d3b4ee1e5e
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 /* point to the block driver where the snapshots are managed */
142 BlockDriverState *bs_snapshots;
143 int vga_ram_size;
144 static DisplayState display_state;
145 int nographic;
146 const char* keyboard_layout = NULL;
147 int64_t ticks_per_sec;
148 int boot_device = 'c';
149 int ram_size;
150 int pit_min_timer_count = 0;
151 int nb_nics;
152 NICInfo nd_table[MAX_NICS];
153 QEMUTimer *gui_timer;
154 int vm_running;
155 int rtc_utc = 1;
156 int cirrus_vga_enabled = 1;
157 #ifdef TARGET_SPARC
158 int graphic_width = 1024;
159 int graphic_height = 768;
160 #else
161 int graphic_width = 800;
162 int graphic_height = 600;
163 #endif
164 int graphic_depth = 15;
165 int full_screen = 0;
166 int no_frame = 0;
167 int no_quit = 0;
168 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
169 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
170 #ifdef TARGET_I386
171 int win2k_install_hack = 0;
172 #endif
173 int usb_enabled = 0;
174 static VLANState *first_vlan;
175 int smp_cpus = 1;
176 const char *vnc_display;
177 #if defined(TARGET_SPARC)
178 #define MAX_CPUS 16
179 #elif defined(TARGET_I386)
180 #define MAX_CPUS 255
181 #else
182 #define MAX_CPUS 1
183 #endif
184 int acpi_enabled = 1;
185 int fd_bootchk = 1;
186 int no_reboot = 0;
187 int daemonize = 0;
188 const char *option_rom[MAX_OPTION_ROMS];
189 int nb_option_roms;
190 int semihosting_enabled = 0;
191 int autostart = 1;
192 const char *qemu_name;
194 /***********************************************************/
195 /* x86 ISA bus support */
197 target_phys_addr_t isa_mem_base = 0;
198 PicState2 *isa_pic;
200 uint32_t default_ioport_readb(void *opaque, uint32_t address)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr, "unused inb: port=0x%04x\n", address);
204 #endif
205 return 0xff;
208 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
210 #ifdef DEBUG_UNUSED_IOPORT
211 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
212 #endif
215 /* default is to make two byte accesses */
216 uint32_t default_ioport_readw(void *opaque, uint32_t address)
218 uint32_t data;
219 data = ioport_read_table[0][address](ioport_opaque[address], address);
220 address = (address + 1) & (MAX_IOPORTS - 1);
221 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
222 return data;
225 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
227 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
228 address = (address + 1) & (MAX_IOPORTS - 1);
229 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
232 uint32_t default_ioport_readl(void *opaque, uint32_t address)
234 #ifdef DEBUG_UNUSED_IOPORT
235 fprintf(stderr, "unused inl: port=0x%04x\n", address);
236 #endif
237 return 0xffffffff;
240 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
242 #ifdef DEBUG_UNUSED_IOPORT
243 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
244 #endif
247 void init_ioports(void)
249 int i;
251 for(i = 0; i < MAX_IOPORTS; i++) {
252 ioport_read_table[0][i] = default_ioport_readb;
253 ioport_write_table[0][i] = default_ioport_writeb;
254 ioport_read_table[1][i] = default_ioport_readw;
255 ioport_write_table[1][i] = default_ioport_writew;
256 ioport_read_table[2][i] = default_ioport_readl;
257 ioport_write_table[2][i] = default_ioport_writel;
261 /* size is the word size in byte */
262 int register_ioport_read(int start, int length, int size,
263 IOPortReadFunc *func, void *opaque)
265 int i, bsize;
267 if (size == 1) {
268 bsize = 0;
269 } else if (size == 2) {
270 bsize = 1;
271 } else if (size == 4) {
272 bsize = 2;
273 } else {
274 hw_error("register_ioport_read: invalid size");
275 return -1;
277 for(i = start; i < start + length; i += size) {
278 ioport_read_table[bsize][i] = func;
279 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
280 hw_error("register_ioport_read: invalid opaque");
281 ioport_opaque[i] = opaque;
283 return 0;
286 /* size is the word size in byte */
287 int register_ioport_write(int start, int length, int size,
288 IOPortWriteFunc *func, void *opaque)
290 int i, bsize;
292 if (size == 1) {
293 bsize = 0;
294 } else if (size == 2) {
295 bsize = 1;
296 } else if (size == 4) {
297 bsize = 2;
298 } else {
299 hw_error("register_ioport_write: invalid size");
300 return -1;
302 for(i = start; i < start + length; i += size) {
303 ioport_write_table[bsize][i] = func;
304 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
305 hw_error("register_ioport_write: invalid opaque");
306 ioport_opaque[i] = opaque;
308 return 0;
311 void isa_unassign_ioport(int start, int length)
313 int i;
315 for(i = start; i < start + length; i++) {
316 ioport_read_table[0][i] = default_ioport_readb;
317 ioport_read_table[1][i] = default_ioport_readw;
318 ioport_read_table[2][i] = default_ioport_readl;
320 ioport_write_table[0][i] = default_ioport_writeb;
321 ioport_write_table[1][i] = default_ioport_writew;
322 ioport_write_table[2][i] = default_ioport_writel;
326 /***********************************************************/
328 void cpu_outb(CPUState *env, int addr, int val)
330 #ifdef DEBUG_IOPORT
331 if (loglevel & CPU_LOG_IOPORT)
332 fprintf(logfile, "outb: %04x %02x\n", addr, val);
333 #endif
334 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
335 #ifdef USE_KQEMU
336 if (env)
337 env->last_io_time = cpu_get_time_fast();
338 #endif
341 void cpu_outw(CPUState *env, int addr, int val)
343 #ifdef DEBUG_IOPORT
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outw: %04x %04x\n", addr, val);
346 #endif
347 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
348 #ifdef USE_KQEMU
349 if (env)
350 env->last_io_time = cpu_get_time_fast();
351 #endif
354 void cpu_outl(CPUState *env, int addr, int val)
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outl: %04x %08x\n", addr, val);
359 #endif
360 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
367 int cpu_inb(CPUState *env, int addr)
369 int val;
370 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
371 #ifdef DEBUG_IOPORT
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "inb : %04x %02x\n", addr, val);
374 #endif
375 #ifdef USE_KQEMU
376 if (env)
377 env->last_io_time = cpu_get_time_fast();
378 #endif
379 return val;
382 int cpu_inw(CPUState *env, int addr)
384 int val;
385 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
386 #ifdef DEBUG_IOPORT
387 if (loglevel & CPU_LOG_IOPORT)
388 fprintf(logfile, "inw : %04x %04x\n", addr, val);
389 #endif
390 #ifdef USE_KQEMU
391 if (env)
392 env->last_io_time = cpu_get_time_fast();
393 #endif
394 return val;
397 int cpu_inl(CPUState *env, int addr)
399 int val;
400 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
401 #ifdef DEBUG_IOPORT
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inl : %04x %08x\n", addr, val);
404 #endif
405 #ifdef USE_KQEMU
406 if (env)
407 env->last_io_time = cpu_get_time_fast();
408 #endif
409 return val;
412 /***********************************************************/
413 void hw_error(const char *fmt, ...)
415 va_list ap;
416 CPUState *env;
418 va_start(ap, fmt);
419 fprintf(stderr, "qemu: hardware error: ");
420 vfprintf(stderr, fmt, ap);
421 fprintf(stderr, "\n");
422 for(env = first_cpu; env != NULL; env = env->next_cpu) {
423 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
424 #ifdef TARGET_I386
425 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
426 #else
427 cpu_dump_state(env, stderr, fprintf, 0);
428 #endif
430 va_end(ap);
431 abort();
434 /***********************************************************/
435 /* keyboard/mouse */
437 static QEMUPutKBDEvent *qemu_put_kbd_event;
438 static void *qemu_put_kbd_event_opaque;
439 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
440 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
442 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
444 qemu_put_kbd_event_opaque = opaque;
445 qemu_put_kbd_event = func;
448 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
449 void *opaque, int absolute,
450 const char *name)
452 QEMUPutMouseEntry *s, *cursor;
454 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
455 if (!s)
456 return NULL;
458 s->qemu_put_mouse_event = func;
459 s->qemu_put_mouse_event_opaque = opaque;
460 s->qemu_put_mouse_event_absolute = absolute;
461 s->qemu_put_mouse_event_name = qemu_strdup(name);
462 s->next = NULL;
464 if (!qemu_put_mouse_event_head) {
465 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
466 return s;
469 cursor = qemu_put_mouse_event_head;
470 while (cursor->next != NULL)
471 cursor = cursor->next;
473 cursor->next = s;
474 qemu_put_mouse_event_current = s;
476 return s;
479 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
481 QEMUPutMouseEntry *prev = NULL, *cursor;
483 if (!qemu_put_mouse_event_head || entry == NULL)
484 return;
486 cursor = qemu_put_mouse_event_head;
487 while (cursor != NULL && cursor != entry) {
488 prev = cursor;
489 cursor = cursor->next;
492 if (cursor == NULL) // does not exist or list empty
493 return;
494 else if (prev == NULL) { // entry is head
495 qemu_put_mouse_event_head = cursor->next;
496 if (qemu_put_mouse_event_current == entry)
497 qemu_put_mouse_event_current = cursor->next;
498 qemu_free(entry->qemu_put_mouse_event_name);
499 qemu_free(entry);
500 return;
503 prev->next = entry->next;
505 if (qemu_put_mouse_event_current == entry)
506 qemu_put_mouse_event_current = prev;
508 qemu_free(entry->qemu_put_mouse_event_name);
509 qemu_free(entry);
512 void kbd_put_keycode(int keycode)
514 if (qemu_put_kbd_event) {
515 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
519 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
521 QEMUPutMouseEvent *mouse_event;
522 void *mouse_event_opaque;
524 if (!qemu_put_mouse_event_current) {
525 return;
528 mouse_event =
529 qemu_put_mouse_event_current->qemu_put_mouse_event;
530 mouse_event_opaque =
531 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
533 if (mouse_event) {
534 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
538 int kbd_mouse_is_absolute(void)
540 if (!qemu_put_mouse_event_current)
541 return 0;
543 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
546 void do_info_mice(void)
548 QEMUPutMouseEntry *cursor;
549 int index = 0;
551 if (!qemu_put_mouse_event_head) {
552 term_printf("No mouse devices connected\n");
553 return;
556 term_printf("Mouse devices available:\n");
557 cursor = qemu_put_mouse_event_head;
558 while (cursor != NULL) {
559 term_printf("%c Mouse #%d: %s\n",
560 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
561 index, cursor->qemu_put_mouse_event_name);
562 index++;
563 cursor = cursor->next;
567 void do_mouse_set(int index)
569 QEMUPutMouseEntry *cursor;
570 int i = 0;
572 if (!qemu_put_mouse_event_head) {
573 term_printf("No mouse devices connected\n");
574 return;
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL && index != i) {
579 i++;
580 cursor = cursor->next;
583 if (cursor != NULL)
584 qemu_put_mouse_event_current = cursor;
585 else
586 term_printf("Mouse at given index not found\n");
589 /* compute with 96 bit intermediate result: (a*b)/c */
590 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
592 union {
593 uint64_t ll;
594 struct {
595 #ifdef WORDS_BIGENDIAN
596 uint32_t high, low;
597 #else
598 uint32_t low, high;
599 #endif
600 } l;
601 } u, res;
602 uint64_t rl, rh;
604 u.ll = a;
605 rl = (uint64_t)u.l.low * (uint64_t)b;
606 rh = (uint64_t)u.l.high * (uint64_t)b;
607 rh += (rl >> 32);
608 res.l.high = rh / c;
609 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
610 return res.ll;
613 /***********************************************************/
614 /* real time host monotonic timer */
616 #define QEMU_TIMER_BASE 1000000000LL
618 #ifdef WIN32
620 static int64_t clock_freq;
622 static void init_get_clock(void)
624 LARGE_INTEGER freq;
625 int ret;
626 ret = QueryPerformanceFrequency(&freq);
627 if (ret == 0) {
628 fprintf(stderr, "Could not calibrate ticks\n");
629 exit(1);
631 clock_freq = freq.QuadPart;
634 static int64_t get_clock(void)
636 LARGE_INTEGER ti;
637 QueryPerformanceCounter(&ti);
638 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
641 #else
643 static int use_rt_clock;
645 static void init_get_clock(void)
647 use_rt_clock = 0;
648 #if defined(__linux__)
650 struct timespec ts;
651 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
652 use_rt_clock = 1;
655 #endif
658 static int64_t get_clock(void)
660 #if defined(__linux__)
661 if (use_rt_clock) {
662 struct timespec ts;
663 clock_gettime(CLOCK_MONOTONIC, &ts);
664 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
665 } else
666 #endif
668 /* XXX: using gettimeofday leads to problems if the date
669 changes, so it should be avoided. */
670 struct timeval tv;
671 gettimeofday(&tv, NULL);
672 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
676 #endif
678 /***********************************************************/
679 /* guest cycle counter */
681 static int64_t cpu_ticks_prev;
682 static int64_t cpu_ticks_offset;
683 static int64_t cpu_clock_offset;
684 static int cpu_ticks_enabled;
686 /* return the host CPU cycle counter and handle stop/restart */
687 int64_t cpu_get_ticks(void)
689 if (!cpu_ticks_enabled) {
690 return cpu_ticks_offset;
691 } else {
692 int64_t ticks;
693 ticks = cpu_get_real_ticks();
694 if (cpu_ticks_prev > ticks) {
695 /* Note: non increasing ticks may happen if the host uses
696 software suspend */
697 cpu_ticks_offset += cpu_ticks_prev - ticks;
699 cpu_ticks_prev = ticks;
700 return ticks + cpu_ticks_offset;
704 /* return the host CPU monotonic timer and handle stop/restart */
705 static int64_t cpu_get_clock(void)
707 int64_t ti;
708 if (!cpu_ticks_enabled) {
709 return cpu_clock_offset;
710 } else {
711 ti = get_clock();
712 return ti + cpu_clock_offset;
716 /* enable cpu_get_ticks() */
717 void cpu_enable_ticks(void)
719 if (!cpu_ticks_enabled) {
720 cpu_ticks_offset -= cpu_get_real_ticks();
721 cpu_clock_offset -= get_clock();
722 cpu_ticks_enabled = 1;
726 /* disable cpu_get_ticks() : the clock is stopped. You must not call
727 cpu_get_ticks() after that. */
728 void cpu_disable_ticks(void)
730 if (cpu_ticks_enabled) {
731 cpu_ticks_offset = cpu_get_ticks();
732 cpu_clock_offset = cpu_get_clock();
733 cpu_ticks_enabled = 0;
737 /***********************************************************/
738 /* timers */
740 #define QEMU_TIMER_REALTIME 0
741 #define QEMU_TIMER_VIRTUAL 1
743 struct QEMUClock {
744 int type;
745 /* XXX: add frequency */
748 struct QEMUTimer {
749 QEMUClock *clock;
750 int64_t expire_time;
751 QEMUTimerCB *cb;
752 void *opaque;
753 struct QEMUTimer *next;
756 QEMUClock *rt_clock;
757 QEMUClock *vm_clock;
759 static QEMUTimer *active_timers[2];
760 #ifdef _WIN32
761 static MMRESULT timerID;
762 static HANDLE host_alarm = NULL;
763 static unsigned int period = 1;
764 #else
765 /* frequency of the times() clock tick */
766 static int timer_freq;
767 #endif
769 QEMUClock *qemu_new_clock(int type)
771 QEMUClock *clock;
772 clock = qemu_mallocz(sizeof(QEMUClock));
773 if (!clock)
774 return NULL;
775 clock->type = type;
776 return clock;
779 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
781 QEMUTimer *ts;
783 ts = qemu_mallocz(sizeof(QEMUTimer));
784 ts->clock = clock;
785 ts->cb = cb;
786 ts->opaque = opaque;
787 return ts;
790 void qemu_free_timer(QEMUTimer *ts)
792 qemu_free(ts);
795 /* stop a timer, but do not dealloc it */
796 void qemu_del_timer(QEMUTimer *ts)
798 QEMUTimer **pt, *t;
800 /* NOTE: this code must be signal safe because
801 qemu_timer_expired() can be called from a signal. */
802 pt = &active_timers[ts->clock->type];
803 for(;;) {
804 t = *pt;
805 if (!t)
806 break;
807 if (t == ts) {
808 *pt = t->next;
809 break;
811 pt = &t->next;
815 /* modify the current timer so that it will be fired when current_time
816 >= expire_time. The corresponding callback will be called. */
817 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
819 QEMUTimer **pt, *t;
821 qemu_del_timer(ts);
823 /* add the timer in the sorted list */
824 /* NOTE: this code must be signal safe because
825 qemu_timer_expired() can be called from a signal. */
826 pt = &active_timers[ts->clock->type];
827 for(;;) {
828 t = *pt;
829 if (!t)
830 break;
831 if (t->expire_time > expire_time)
832 break;
833 pt = &t->next;
835 ts->expire_time = expire_time;
836 ts->next = *pt;
837 *pt = ts;
840 int qemu_timer_pending(QEMUTimer *ts)
842 QEMUTimer *t;
843 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
844 if (t == ts)
845 return 1;
847 return 0;
850 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
852 if (!timer_head)
853 return 0;
854 return (timer_head->expire_time <= current_time);
857 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
859 QEMUTimer *ts;
861 for(;;) {
862 ts = *ptimer_head;
863 if (!ts || ts->expire_time > current_time)
864 break;
865 /* remove timer from the list before calling the callback */
866 *ptimer_head = ts->next;
867 ts->next = NULL;
869 /* run the callback (the timer list can be modified) */
870 ts->cb(ts->opaque);
874 int64_t qemu_get_clock(QEMUClock *clock)
876 switch(clock->type) {
877 case QEMU_TIMER_REALTIME:
878 return get_clock() / 1000000;
879 default:
880 case QEMU_TIMER_VIRTUAL:
881 return cpu_get_clock();
885 static void init_timers(void)
887 init_get_clock();
888 ticks_per_sec = QEMU_TIMER_BASE;
889 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
890 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
893 /* save a timer */
894 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
896 uint64_t expire_time;
898 if (qemu_timer_pending(ts)) {
899 expire_time = ts->expire_time;
900 } else {
901 expire_time = -1;
903 qemu_put_be64(f, expire_time);
906 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
908 uint64_t expire_time;
910 expire_time = qemu_get_be64(f);
911 if (expire_time != -1) {
912 qemu_mod_timer(ts, expire_time);
913 } else {
914 qemu_del_timer(ts);
918 static void timer_save(QEMUFile *f, void *opaque)
920 if (cpu_ticks_enabled) {
921 hw_error("cannot save state if virtual timers are running");
923 qemu_put_be64s(f, &cpu_ticks_offset);
924 qemu_put_be64s(f, &ticks_per_sec);
925 qemu_put_be64s(f, &cpu_clock_offset);
928 static int timer_load(QEMUFile *f, void *opaque, int version_id)
930 if (version_id != 1 && version_id != 2)
931 return -EINVAL;
932 if (cpu_ticks_enabled) {
933 return -EINVAL;
935 qemu_get_be64s(f, &cpu_ticks_offset);
936 qemu_get_be64s(f, &ticks_per_sec);
937 if (version_id == 2) {
938 qemu_get_be64s(f, &cpu_clock_offset);
940 return 0;
943 #ifdef _WIN32
944 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
945 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
946 #else
947 static void host_alarm_handler(int host_signum)
948 #endif
950 #if 0
951 #define DISP_FREQ 1000
953 static int64_t delta_min = INT64_MAX;
954 static int64_t delta_max, delta_cum, last_clock, delta, ti;
955 static int count;
956 ti = qemu_get_clock(vm_clock);
957 if (last_clock != 0) {
958 delta = ti - last_clock;
959 if (delta < delta_min)
960 delta_min = delta;
961 if (delta > delta_max)
962 delta_max = delta;
963 delta_cum += delta;
964 if (++count == DISP_FREQ) {
965 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
966 muldiv64(delta_min, 1000000, ticks_per_sec),
967 muldiv64(delta_max, 1000000, ticks_per_sec),
968 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
969 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
970 count = 0;
971 delta_min = INT64_MAX;
972 delta_max = 0;
973 delta_cum = 0;
976 last_clock = ti;
978 #endif
979 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
980 qemu_get_clock(vm_clock)) ||
981 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
982 qemu_get_clock(rt_clock))) {
983 #ifdef _WIN32
984 SetEvent(host_alarm);
985 #endif
986 CPUState *env = cpu_single_env;
987 if (env) {
988 /* stop the currently executing cpu because a timer occured */
989 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
990 #ifdef USE_KQEMU
991 if (env->kqemu_enabled) {
992 kqemu_cpu_interrupt(env);
994 #endif
999 #ifndef _WIN32
1001 #if defined(__linux__)
1003 #define RTC_FREQ 1024
1005 static int rtc_fd;
1007 static int start_rtc_timer(void)
1009 rtc_fd = open("/dev/rtc", O_RDONLY);
1010 if (rtc_fd < 0)
1011 return -1;
1012 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1013 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1014 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1015 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1016 goto fail;
1018 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1019 fail:
1020 close(rtc_fd);
1021 return -1;
1023 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1024 return 0;
1027 #else
1029 static int start_rtc_timer(void)
1031 return -1;
1034 #endif /* !defined(__linux__) */
1036 #endif /* !defined(_WIN32) */
1038 static void init_timer_alarm(void)
1040 #ifdef _WIN32
1042 int count=0;
1043 TIMECAPS tc;
1045 ZeroMemory(&tc, sizeof(TIMECAPS));
1046 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1047 if (period < tc.wPeriodMin)
1048 period = tc.wPeriodMin;
1049 timeBeginPeriod(period);
1050 timerID = timeSetEvent(1, // interval (ms)
1051 period, // resolution
1052 host_alarm_handler, // function
1053 (DWORD)&count, // user parameter
1054 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1055 if( !timerID ) {
1056 perror("failed timer alarm");
1057 exit(1);
1059 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1060 if (!host_alarm) {
1061 perror("failed CreateEvent");
1062 exit(1);
1064 qemu_add_wait_object(host_alarm, NULL, NULL);
1066 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1067 #else
1069 struct sigaction act;
1070 struct itimerval itv;
1072 /* get times() syscall frequency */
1073 timer_freq = sysconf(_SC_CLK_TCK);
1075 /* timer signal */
1076 sigfillset(&act.sa_mask);
1077 act.sa_flags = 0;
1078 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1079 act.sa_flags |= SA_ONSTACK;
1080 #endif
1081 act.sa_handler = host_alarm_handler;
1082 sigaction(SIGALRM, &act, NULL);
1084 itv.it_interval.tv_sec = 0;
1085 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1086 itv.it_value.tv_sec = 0;
1087 itv.it_value.tv_usec = 10 * 1000;
1088 setitimer(ITIMER_REAL, &itv, NULL);
1089 /* we probe the tick duration of the kernel to inform the user if
1090 the emulated kernel requested a too high timer frequency */
1091 getitimer(ITIMER_REAL, &itv);
1093 #if defined(__linux__)
1094 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1095 have timers with 1 ms resolution. The correct solution will
1096 be to use the POSIX real time timers available in recent
1097 2.6 kernels */
1098 if (itv.it_interval.tv_usec > 1000 || 1) {
1099 /* try to use /dev/rtc to have a faster timer */
1100 if (start_rtc_timer() < 0)
1101 goto use_itimer;
1102 /* disable itimer */
1103 itv.it_interval.tv_sec = 0;
1104 itv.it_interval.tv_usec = 0;
1105 itv.it_value.tv_sec = 0;
1106 itv.it_value.tv_usec = 0;
1107 setitimer(ITIMER_REAL, &itv, NULL);
1109 /* use the RTC */
1110 sigaction(SIGIO, &act, NULL);
1111 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1112 fcntl(rtc_fd, F_SETOWN, getpid());
1113 } else
1114 #endif /* defined(__linux__) */
1116 use_itimer:
1117 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1118 PIT_FREQ) / 1000000;
1121 #endif
1124 void quit_timers(void)
1126 #ifdef _WIN32
1127 timeKillEvent(timerID);
1128 timeEndPeriod(period);
1129 if (host_alarm) {
1130 CloseHandle(host_alarm);
1131 host_alarm = NULL;
1133 #endif
1136 /***********************************************************/
1137 /* character device */
1139 static void qemu_chr_event(CharDriverState *s, int event)
1141 if (!s->chr_event)
1142 return;
1143 s->chr_event(s->handler_opaque, event);
1146 static void qemu_chr_reset_bh(void *opaque)
1148 CharDriverState *s = opaque;
1149 qemu_chr_event(s, CHR_EVENT_RESET);
1150 qemu_bh_delete(s->bh);
1151 s->bh = NULL;
1154 void qemu_chr_reset(CharDriverState *s)
1156 if (s->bh == NULL) {
1157 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1158 qemu_bh_schedule(s->bh);
1162 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1164 return s->chr_write(s, buf, len);
1167 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1169 if (!s->chr_ioctl)
1170 return -ENOTSUP;
1171 return s->chr_ioctl(s, cmd, arg);
1174 int qemu_chr_can_read(CharDriverState *s)
1176 if (!s->chr_can_read)
1177 return 0;
1178 return s->chr_can_read(s->handler_opaque);
1181 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1183 s->chr_read(s->handler_opaque, buf, len);
1187 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1189 char buf[4096];
1190 va_list ap;
1191 va_start(ap, fmt);
1192 vsnprintf(buf, sizeof(buf), fmt, ap);
1193 qemu_chr_write(s, buf, strlen(buf));
1194 va_end(ap);
1197 void qemu_chr_send_event(CharDriverState *s, int event)
1199 if (s->chr_send_event)
1200 s->chr_send_event(s, event);
1203 void qemu_chr_add_handlers(CharDriverState *s,
1204 IOCanRWHandler *fd_can_read,
1205 IOReadHandler *fd_read,
1206 IOEventHandler *fd_event,
1207 void *opaque)
1209 s->chr_can_read = fd_can_read;
1210 s->chr_read = fd_read;
1211 s->chr_event = fd_event;
1212 s->handler_opaque = opaque;
1213 if (s->chr_update_read_handler)
1214 s->chr_update_read_handler(s);
1217 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1219 return len;
1222 static CharDriverState *qemu_chr_open_null(void)
1224 CharDriverState *chr;
1226 chr = qemu_mallocz(sizeof(CharDriverState));
1227 if (!chr)
1228 return NULL;
1229 chr->chr_write = null_chr_write;
1230 return chr;
1233 /* MUX driver for serial I/O splitting */
1234 static int term_timestamps;
1235 static int64_t term_timestamps_start;
1236 #define MAX_MUX 4
1237 typedef struct {
1238 IOCanRWHandler *chr_can_read[MAX_MUX];
1239 IOReadHandler *chr_read[MAX_MUX];
1240 IOEventHandler *chr_event[MAX_MUX];
1241 void *ext_opaque[MAX_MUX];
1242 CharDriverState *drv;
1243 int mux_cnt;
1244 int term_got_escape;
1245 int max_size;
1246 } MuxDriver;
1249 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1251 MuxDriver *d = chr->opaque;
1252 int ret;
1253 if (!term_timestamps) {
1254 ret = d->drv->chr_write(d->drv, buf, len);
1255 } else {
1256 int i;
1258 ret = 0;
1259 for(i = 0; i < len; i++) {
1260 ret += d->drv->chr_write(d->drv, buf+i, 1);
1261 if (buf[i] == '\n') {
1262 char buf1[64];
1263 int64_t ti;
1264 int secs;
1266 ti = get_clock();
1267 if (term_timestamps_start == -1)
1268 term_timestamps_start = ti;
1269 ti -= term_timestamps_start;
1270 secs = ti / 1000000000;
1271 snprintf(buf1, sizeof(buf1),
1272 "[%02d:%02d:%02d.%03d] ",
1273 secs / 3600,
1274 (secs / 60) % 60,
1275 secs % 60,
1276 (int)((ti / 1000000) % 1000));
1277 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1281 return ret;
1284 static char *mux_help[] = {
1285 "% h print this help\n\r",
1286 "% x exit emulator\n\r",
1287 "% s save disk data back to file (if -snapshot)\n\r",
1288 "% t toggle console timestamps\n\r"
1289 "% b send break (magic sysrq)\n\r",
1290 "% c switch between console and monitor\n\r",
1291 "% % sends %\n\r",
1292 NULL
1295 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1296 static void mux_print_help(CharDriverState *chr)
1298 int i, j;
1299 char ebuf[15] = "Escape-Char";
1300 char cbuf[50] = "\n\r";
1302 if (term_escape_char > 0 && term_escape_char < 26) {
1303 sprintf(cbuf,"\n\r");
1304 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1305 } else {
1306 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1308 chr->chr_write(chr, cbuf, strlen(cbuf));
1309 for (i = 0; mux_help[i] != NULL; i++) {
1310 for (j=0; mux_help[i][j] != '\0'; j++) {
1311 if (mux_help[i][j] == '%')
1312 chr->chr_write(chr, ebuf, strlen(ebuf));
1313 else
1314 chr->chr_write(chr, &mux_help[i][j], 1);
1319 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1321 if (d->term_got_escape) {
1322 d->term_got_escape = 0;
1323 if (ch == term_escape_char)
1324 goto send_char;
1325 switch(ch) {
1326 case '?':
1327 case 'h':
1328 mux_print_help(chr);
1329 break;
1330 case 'x':
1332 char *term = "QEMU: Terminated\n\r";
1333 chr->chr_write(chr,term,strlen(term));
1334 exit(0);
1335 break;
1337 case 's':
1339 int i;
1340 for (i = 0; i < MAX_DISKS; i++) {
1341 if (bs_table[i])
1342 bdrv_commit(bs_table[i]);
1345 break;
1346 case 'b':
1347 if (chr->chr_event)
1348 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1349 break;
1350 case 'c':
1351 /* Switch to the next registered device */
1352 chr->focus++;
1353 if (chr->focus >= d->mux_cnt)
1354 chr->focus = 0;
1355 break;
1356 case 't':
1357 term_timestamps = !term_timestamps;
1358 term_timestamps_start = -1;
1359 break;
1361 } else if (ch == term_escape_char) {
1362 d->term_got_escape = 1;
1363 } else {
1364 send_char:
1365 return 1;
1367 return 0;
1370 static int mux_chr_can_read(void *opaque)
1372 CharDriverState *chr = opaque;
1373 MuxDriver *d = chr->opaque;
1374 if (d->chr_can_read[chr->focus])
1375 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1376 return 0;
1379 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1381 CharDriverState *chr = opaque;
1382 MuxDriver *d = chr->opaque;
1383 int i;
1384 for(i = 0; i < size; i++)
1385 if (mux_proc_byte(chr, d, buf[i]))
1386 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1389 static void mux_chr_event(void *opaque, int event)
1391 CharDriverState *chr = opaque;
1392 MuxDriver *d = chr->opaque;
1393 int i;
1395 /* Send the event to all registered listeners */
1396 for (i = 0; i < d->mux_cnt; i++)
1397 if (d->chr_event[i])
1398 d->chr_event[i](d->ext_opaque[i], event);
1401 static void mux_chr_update_read_handler(CharDriverState *chr)
1403 MuxDriver *d = chr->opaque;
1405 if (d->mux_cnt >= MAX_MUX) {
1406 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1407 return;
1409 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1410 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1411 d->chr_read[d->mux_cnt] = chr->chr_read;
1412 d->chr_event[d->mux_cnt] = chr->chr_event;
1413 /* Fix up the real driver with mux routines */
1414 if (d->mux_cnt == 0) {
1415 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1416 mux_chr_event, chr);
1418 chr->focus = d->mux_cnt;
1419 d->mux_cnt++;
1422 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1424 CharDriverState *chr;
1425 MuxDriver *d;
1427 chr = qemu_mallocz(sizeof(CharDriverState));
1428 if (!chr)
1429 return NULL;
1430 d = qemu_mallocz(sizeof(MuxDriver));
1431 if (!d) {
1432 free(chr);
1433 return NULL;
1436 chr->opaque = d;
1437 d->drv = drv;
1438 chr->focus = -1;
1439 chr->chr_write = mux_chr_write;
1440 chr->chr_update_read_handler = mux_chr_update_read_handler;
1441 return chr;
1445 #ifdef _WIN32
1447 static void socket_cleanup(void)
1449 WSACleanup();
1452 static int socket_init(void)
1454 WSADATA Data;
1455 int ret, err;
1457 ret = WSAStartup(MAKEWORD(2,2), &Data);
1458 if (ret != 0) {
1459 err = WSAGetLastError();
1460 fprintf(stderr, "WSAStartup: %d\n", err);
1461 return -1;
1463 atexit(socket_cleanup);
1464 return 0;
1467 static int send_all(int fd, const uint8_t *buf, int len1)
1469 int ret, len;
1471 len = len1;
1472 while (len > 0) {
1473 ret = send(fd, buf, len, 0);
1474 if (ret < 0) {
1475 int errno;
1476 errno = WSAGetLastError();
1477 if (errno != WSAEWOULDBLOCK) {
1478 return -1;
1480 } else if (ret == 0) {
1481 break;
1482 } else {
1483 buf += ret;
1484 len -= ret;
1487 return len1 - len;
1490 void socket_set_nonblock(int fd)
1492 unsigned long opt = 1;
1493 ioctlsocket(fd, FIONBIO, &opt);
1496 #else
1498 static int unix_write(int fd, const uint8_t *buf, int len1)
1500 int ret, len;
1502 len = len1;
1503 while (len > 0) {
1504 ret = write(fd, buf, len);
1505 if (ret < 0) {
1506 if (errno != EINTR && errno != EAGAIN)
1507 return -1;
1508 } else if (ret == 0) {
1509 break;
1510 } else {
1511 buf += ret;
1512 len -= ret;
1515 return len1 - len;
1518 static inline int send_all(int fd, const uint8_t *buf, int len1)
1520 return unix_write(fd, buf, len1);
1523 void socket_set_nonblock(int fd)
1525 fcntl(fd, F_SETFL, O_NONBLOCK);
1527 #endif /* !_WIN32 */
1529 #ifndef _WIN32
1531 typedef struct {
1532 int fd_in, fd_out;
1533 int max_size;
1534 } FDCharDriver;
1536 #define STDIO_MAX_CLIENTS 1
1537 static int stdio_nb_clients = 0;
1539 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1541 FDCharDriver *s = chr->opaque;
1542 return unix_write(s->fd_out, buf, len);
1545 static int fd_chr_read_poll(void *opaque)
1547 CharDriverState *chr = opaque;
1548 FDCharDriver *s = chr->opaque;
1550 s->max_size = qemu_chr_can_read(chr);
1551 return s->max_size;
1554 static void fd_chr_read(void *opaque)
1556 CharDriverState *chr = opaque;
1557 FDCharDriver *s = chr->opaque;
1558 int size, len;
1559 uint8_t buf[1024];
1561 len = sizeof(buf);
1562 if (len > s->max_size)
1563 len = s->max_size;
1564 if (len == 0)
1565 return;
1566 size = read(s->fd_in, buf, len);
1567 if (size == 0) {
1568 /* FD has been closed. Remove it from the active list. */
1569 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1570 return;
1572 if (size > 0) {
1573 qemu_chr_read(chr, buf, size);
1577 static void fd_chr_update_read_handler(CharDriverState *chr)
1579 FDCharDriver *s = chr->opaque;
1581 if (s->fd_in >= 0) {
1582 if (nographic && s->fd_in == 0) {
1583 } else {
1584 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1585 fd_chr_read, NULL, chr);
1590 /* open a character device to a unix fd */
1591 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1593 CharDriverState *chr;
1594 FDCharDriver *s;
1596 chr = qemu_mallocz(sizeof(CharDriverState));
1597 if (!chr)
1598 return NULL;
1599 s = qemu_mallocz(sizeof(FDCharDriver));
1600 if (!s) {
1601 free(chr);
1602 return NULL;
1604 s->fd_in = fd_in;
1605 s->fd_out = fd_out;
1606 chr->opaque = s;
1607 chr->chr_write = fd_chr_write;
1608 chr->chr_update_read_handler = fd_chr_update_read_handler;
1610 qemu_chr_reset(chr);
1612 return chr;
1615 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1617 int fd_out;
1619 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1620 if (fd_out < 0)
1621 return NULL;
1622 return qemu_chr_open_fd(-1, fd_out);
1625 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1627 int fd_in, fd_out;
1628 char filename_in[256], filename_out[256];
1630 snprintf(filename_in, 256, "%s.in", filename);
1631 snprintf(filename_out, 256, "%s.out", filename);
1632 fd_in = open(filename_in, O_RDWR | O_BINARY);
1633 fd_out = open(filename_out, O_RDWR | O_BINARY);
1634 if (fd_in < 0 || fd_out < 0) {
1635 if (fd_in >= 0)
1636 close(fd_in);
1637 if (fd_out >= 0)
1638 close(fd_out);
1639 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1640 if (fd_in < 0)
1641 return NULL;
1643 return qemu_chr_open_fd(fd_in, fd_out);
1647 /* for STDIO, we handle the case where several clients use it
1648 (nographic mode) */
1650 #define TERM_FIFO_MAX_SIZE 1
1652 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1653 static int term_fifo_size;
1655 static int stdio_read_poll(void *opaque)
1657 CharDriverState *chr = opaque;
1659 /* try to flush the queue if needed */
1660 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1661 qemu_chr_read(chr, term_fifo, 1);
1662 term_fifo_size = 0;
1664 /* see if we can absorb more chars */
1665 if (term_fifo_size == 0)
1666 return 1;
1667 else
1668 return 0;
1671 static void stdio_read(void *opaque)
1673 int size;
1674 uint8_t buf[1];
1675 CharDriverState *chr = opaque;
1677 size = read(0, buf, 1);
1678 if (size == 0) {
1679 /* stdin has been closed. Remove it from the active list. */
1680 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1681 return;
1683 if (size > 0) {
1684 if (qemu_chr_can_read(chr) > 0) {
1685 qemu_chr_read(chr, buf, 1);
1686 } else if (term_fifo_size == 0) {
1687 term_fifo[term_fifo_size++] = buf[0];
1692 /* init terminal so that we can grab keys */
1693 static struct termios oldtty;
1694 static int old_fd0_flags;
1696 static void term_exit(void)
1698 tcsetattr (0, TCSANOW, &oldtty);
1699 fcntl(0, F_SETFL, old_fd0_flags);
1702 static void term_init(void)
1704 struct termios tty;
1706 tcgetattr (0, &tty);
1707 oldtty = tty;
1708 old_fd0_flags = fcntl(0, F_GETFL);
1710 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1711 |INLCR|IGNCR|ICRNL|IXON);
1712 tty.c_oflag |= OPOST;
1713 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1714 /* if graphical mode, we allow Ctrl-C handling */
1715 if (nographic)
1716 tty.c_lflag &= ~ISIG;
1717 tty.c_cflag &= ~(CSIZE|PARENB);
1718 tty.c_cflag |= CS8;
1719 tty.c_cc[VMIN] = 1;
1720 tty.c_cc[VTIME] = 0;
1722 tcsetattr (0, TCSANOW, &tty);
1724 atexit(term_exit);
1726 fcntl(0, F_SETFL, O_NONBLOCK);
1729 static CharDriverState *qemu_chr_open_stdio(void)
1731 CharDriverState *chr;
1733 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1734 return NULL;
1735 chr = qemu_chr_open_fd(0, 1);
1736 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1737 stdio_nb_clients++;
1738 term_init();
1740 return chr;
1743 #if defined(__linux__)
1744 static CharDriverState *qemu_chr_open_pty(void)
1746 struct termios tty;
1747 char slave_name[1024];
1748 int master_fd, slave_fd;
1750 /* Not satisfying */
1751 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1752 return NULL;
1755 /* Disabling local echo and line-buffered output */
1756 tcgetattr (master_fd, &tty);
1757 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1758 tty.c_cc[VMIN] = 1;
1759 tty.c_cc[VTIME] = 0;
1760 tcsetattr (master_fd, TCSAFLUSH, &tty);
1762 fprintf(stderr, "char device redirected to %s\n", slave_name);
1763 return qemu_chr_open_fd(master_fd, master_fd);
1766 static void tty_serial_init(int fd, int speed,
1767 int parity, int data_bits, int stop_bits)
1769 struct termios tty;
1770 speed_t spd;
1772 #if 0
1773 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1774 speed, parity, data_bits, stop_bits);
1775 #endif
1776 tcgetattr (fd, &tty);
1778 switch(speed) {
1779 case 50:
1780 spd = B50;
1781 break;
1782 case 75:
1783 spd = B75;
1784 break;
1785 case 300:
1786 spd = B300;
1787 break;
1788 case 600:
1789 spd = B600;
1790 break;
1791 case 1200:
1792 spd = B1200;
1793 break;
1794 case 2400:
1795 spd = B2400;
1796 break;
1797 case 4800:
1798 spd = B4800;
1799 break;
1800 case 9600:
1801 spd = B9600;
1802 break;
1803 case 19200:
1804 spd = B19200;
1805 break;
1806 case 38400:
1807 spd = B38400;
1808 break;
1809 case 57600:
1810 spd = B57600;
1811 break;
1812 default:
1813 case 115200:
1814 spd = B115200;
1815 break;
1818 cfsetispeed(&tty, spd);
1819 cfsetospeed(&tty, spd);
1821 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1822 |INLCR|IGNCR|ICRNL|IXON);
1823 tty.c_oflag |= OPOST;
1824 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1825 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1826 switch(data_bits) {
1827 default:
1828 case 8:
1829 tty.c_cflag |= CS8;
1830 break;
1831 case 7:
1832 tty.c_cflag |= CS7;
1833 break;
1834 case 6:
1835 tty.c_cflag |= CS6;
1836 break;
1837 case 5:
1838 tty.c_cflag |= CS5;
1839 break;
1841 switch(parity) {
1842 default:
1843 case 'N':
1844 break;
1845 case 'E':
1846 tty.c_cflag |= PARENB;
1847 break;
1848 case 'O':
1849 tty.c_cflag |= PARENB | PARODD;
1850 break;
1852 if (stop_bits == 2)
1853 tty.c_cflag |= CSTOPB;
1855 tcsetattr (fd, TCSANOW, &tty);
1858 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1860 FDCharDriver *s = chr->opaque;
1862 switch(cmd) {
1863 case CHR_IOCTL_SERIAL_SET_PARAMS:
1865 QEMUSerialSetParams *ssp = arg;
1866 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1867 ssp->data_bits, ssp->stop_bits);
1869 break;
1870 case CHR_IOCTL_SERIAL_SET_BREAK:
1872 int enable = *(int *)arg;
1873 if (enable)
1874 tcsendbreak(s->fd_in, 1);
1876 break;
1877 default:
1878 return -ENOTSUP;
1880 return 0;
1883 static CharDriverState *qemu_chr_open_tty(const char *filename)
1885 CharDriverState *chr;
1886 int fd;
1888 fd = open(filename, O_RDWR | O_NONBLOCK);
1889 if (fd < 0)
1890 return NULL;
1891 fcntl(fd, F_SETFL, O_NONBLOCK);
1892 tty_serial_init(fd, 115200, 'N', 8, 1);
1893 chr = qemu_chr_open_fd(fd, fd);
1894 if (!chr)
1895 return NULL;
1896 chr->chr_ioctl = tty_serial_ioctl;
1897 qemu_chr_reset(chr);
1898 return chr;
1901 typedef struct {
1902 int fd;
1903 int mode;
1904 } ParallelCharDriver;
1906 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1908 if (s->mode != mode) {
1909 int m = mode;
1910 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1911 return 0;
1912 s->mode = mode;
1914 return 1;
1917 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1919 ParallelCharDriver *drv = chr->opaque;
1920 int fd = drv->fd;
1921 uint8_t b;
1923 switch(cmd) {
1924 case CHR_IOCTL_PP_READ_DATA:
1925 if (ioctl(fd, PPRDATA, &b) < 0)
1926 return -ENOTSUP;
1927 *(uint8_t *)arg = b;
1928 break;
1929 case CHR_IOCTL_PP_WRITE_DATA:
1930 b = *(uint8_t *)arg;
1931 if (ioctl(fd, PPWDATA, &b) < 0)
1932 return -ENOTSUP;
1933 break;
1934 case CHR_IOCTL_PP_READ_CONTROL:
1935 if (ioctl(fd, PPRCONTROL, &b) < 0)
1936 return -ENOTSUP;
1937 /* Linux gives only the lowest bits, and no way to know data
1938 direction! For better compatibility set the fixed upper
1939 bits. */
1940 *(uint8_t *)arg = b | 0xc0;
1941 break;
1942 case CHR_IOCTL_PP_WRITE_CONTROL:
1943 b = *(uint8_t *)arg;
1944 if (ioctl(fd, PPWCONTROL, &b) < 0)
1945 return -ENOTSUP;
1946 break;
1947 case CHR_IOCTL_PP_READ_STATUS:
1948 if (ioctl(fd, PPRSTATUS, &b) < 0)
1949 return -ENOTSUP;
1950 *(uint8_t *)arg = b;
1951 break;
1952 case CHR_IOCTL_PP_EPP_READ_ADDR:
1953 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1954 struct ParallelIOArg *parg = arg;
1955 int n = read(fd, parg->buffer, parg->count);
1956 if (n != parg->count) {
1957 return -EIO;
1960 break;
1961 case CHR_IOCTL_PP_EPP_READ:
1962 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1963 struct ParallelIOArg *parg = arg;
1964 int n = read(fd, parg->buffer, parg->count);
1965 if (n != parg->count) {
1966 return -EIO;
1969 break;
1970 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1971 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1972 struct ParallelIOArg *parg = arg;
1973 int n = write(fd, parg->buffer, parg->count);
1974 if (n != parg->count) {
1975 return -EIO;
1978 break;
1979 case CHR_IOCTL_PP_EPP_WRITE:
1980 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1981 struct ParallelIOArg *parg = arg;
1982 int n = write(fd, parg->buffer, parg->count);
1983 if (n != parg->count) {
1984 return -EIO;
1987 break;
1988 default:
1989 return -ENOTSUP;
1991 return 0;
1994 static void pp_close(CharDriverState *chr)
1996 ParallelCharDriver *drv = chr->opaque;
1997 int fd = drv->fd;
1999 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2000 ioctl(fd, PPRELEASE);
2001 close(fd);
2002 qemu_free(drv);
2005 static CharDriverState *qemu_chr_open_pp(const char *filename)
2007 CharDriverState *chr;
2008 ParallelCharDriver *drv;
2009 int fd;
2011 fd = open(filename, O_RDWR);
2012 if (fd < 0)
2013 return NULL;
2015 if (ioctl(fd, PPCLAIM) < 0) {
2016 close(fd);
2017 return NULL;
2020 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2021 if (!drv) {
2022 close(fd);
2023 return NULL;
2025 drv->fd = fd;
2026 drv->mode = IEEE1284_MODE_COMPAT;
2028 chr = qemu_mallocz(sizeof(CharDriverState));
2029 if (!chr) {
2030 qemu_free(drv);
2031 close(fd);
2032 return NULL;
2034 chr->chr_write = null_chr_write;
2035 chr->chr_ioctl = pp_ioctl;
2036 chr->chr_close = pp_close;
2037 chr->opaque = drv;
2039 qemu_chr_reset(chr);
2041 return chr;
2044 #else
2045 static CharDriverState *qemu_chr_open_pty(void)
2047 return NULL;
2049 #endif
2051 #endif /* !defined(_WIN32) */
2053 #ifdef _WIN32
2054 typedef struct {
2055 int max_size;
2056 HANDLE hcom, hrecv, hsend;
2057 OVERLAPPED orecv, osend;
2058 BOOL fpipe;
2059 DWORD len;
2060 } WinCharState;
2062 #define NSENDBUF 2048
2063 #define NRECVBUF 2048
2064 #define MAXCONNECT 1
2065 #define NTIMEOUT 5000
2067 static int win_chr_poll(void *opaque);
2068 static int win_chr_pipe_poll(void *opaque);
2070 static void win_chr_close(CharDriverState *chr)
2072 WinCharState *s = chr->opaque;
2074 if (s->hsend) {
2075 CloseHandle(s->hsend);
2076 s->hsend = NULL;
2078 if (s->hrecv) {
2079 CloseHandle(s->hrecv);
2080 s->hrecv = NULL;
2082 if (s->hcom) {
2083 CloseHandle(s->hcom);
2084 s->hcom = NULL;
2086 if (s->fpipe)
2087 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2088 else
2089 qemu_del_polling_cb(win_chr_poll, chr);
2092 static int win_chr_init(CharDriverState *chr, const char *filename)
2094 WinCharState *s = chr->opaque;
2095 COMMCONFIG comcfg;
2096 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2097 COMSTAT comstat;
2098 DWORD size;
2099 DWORD err;
2101 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2102 if (!s->hsend) {
2103 fprintf(stderr, "Failed CreateEvent\n");
2104 goto fail;
2106 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2107 if (!s->hrecv) {
2108 fprintf(stderr, "Failed CreateEvent\n");
2109 goto fail;
2112 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2113 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2114 if (s->hcom == INVALID_HANDLE_VALUE) {
2115 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2116 s->hcom = NULL;
2117 goto fail;
2120 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2121 fprintf(stderr, "Failed SetupComm\n");
2122 goto fail;
2125 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2126 size = sizeof(COMMCONFIG);
2127 GetDefaultCommConfig(filename, &comcfg, &size);
2128 comcfg.dcb.DCBlength = sizeof(DCB);
2129 CommConfigDialog(filename, NULL, &comcfg);
2131 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2132 fprintf(stderr, "Failed SetCommState\n");
2133 goto fail;
2136 if (!SetCommMask(s->hcom, EV_ERR)) {
2137 fprintf(stderr, "Failed SetCommMask\n");
2138 goto fail;
2141 cto.ReadIntervalTimeout = MAXDWORD;
2142 if (!SetCommTimeouts(s->hcom, &cto)) {
2143 fprintf(stderr, "Failed SetCommTimeouts\n");
2144 goto fail;
2147 if (!ClearCommError(s->hcom, &err, &comstat)) {
2148 fprintf(stderr, "Failed ClearCommError\n");
2149 goto fail;
2151 qemu_add_polling_cb(win_chr_poll, chr);
2152 return 0;
2154 fail:
2155 win_chr_close(chr);
2156 return -1;
2159 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2161 WinCharState *s = chr->opaque;
2162 DWORD len, ret, size, err;
2164 len = len1;
2165 ZeroMemory(&s->osend, sizeof(s->osend));
2166 s->osend.hEvent = s->hsend;
2167 while (len > 0) {
2168 if (s->hsend)
2169 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2170 else
2171 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2172 if (!ret) {
2173 err = GetLastError();
2174 if (err == ERROR_IO_PENDING) {
2175 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2176 if (ret) {
2177 buf += size;
2178 len -= size;
2179 } else {
2180 break;
2182 } else {
2183 break;
2185 } else {
2186 buf += size;
2187 len -= size;
2190 return len1 - len;
2193 static int win_chr_read_poll(CharDriverState *chr)
2195 WinCharState *s = chr->opaque;
2197 s->max_size = qemu_chr_can_read(chr);
2198 return s->max_size;
2201 static void win_chr_readfile(CharDriverState *chr)
2203 WinCharState *s = chr->opaque;
2204 int ret, err;
2205 uint8_t buf[1024];
2206 DWORD size;
2208 ZeroMemory(&s->orecv, sizeof(s->orecv));
2209 s->orecv.hEvent = s->hrecv;
2210 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2211 if (!ret) {
2212 err = GetLastError();
2213 if (err == ERROR_IO_PENDING) {
2214 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2218 if (size > 0) {
2219 qemu_chr_read(chr, buf, size);
2223 static void win_chr_read(CharDriverState *chr)
2225 WinCharState *s = chr->opaque;
2227 if (s->len > s->max_size)
2228 s->len = s->max_size;
2229 if (s->len == 0)
2230 return;
2232 win_chr_readfile(chr);
2235 static int win_chr_poll(void *opaque)
2237 CharDriverState *chr = opaque;
2238 WinCharState *s = chr->opaque;
2239 COMSTAT status;
2240 DWORD comerr;
2242 ClearCommError(s->hcom, &comerr, &status);
2243 if (status.cbInQue > 0) {
2244 s->len = status.cbInQue;
2245 win_chr_read_poll(chr);
2246 win_chr_read(chr);
2247 return 1;
2249 return 0;
2252 static CharDriverState *qemu_chr_open_win(const char *filename)
2254 CharDriverState *chr;
2255 WinCharState *s;
2257 chr = qemu_mallocz(sizeof(CharDriverState));
2258 if (!chr)
2259 return NULL;
2260 s = qemu_mallocz(sizeof(WinCharState));
2261 if (!s) {
2262 free(chr);
2263 return NULL;
2265 chr->opaque = s;
2266 chr->chr_write = win_chr_write;
2267 chr->chr_close = win_chr_close;
2269 if (win_chr_init(chr, filename) < 0) {
2270 free(s);
2271 free(chr);
2272 return NULL;
2274 qemu_chr_reset(chr);
2275 return chr;
2278 static int win_chr_pipe_poll(void *opaque)
2280 CharDriverState *chr = opaque;
2281 WinCharState *s = chr->opaque;
2282 DWORD size;
2284 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2285 if (size > 0) {
2286 s->len = size;
2287 win_chr_read_poll(chr);
2288 win_chr_read(chr);
2289 return 1;
2291 return 0;
2294 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2296 WinCharState *s = chr->opaque;
2297 OVERLAPPED ov;
2298 int ret;
2299 DWORD size;
2300 char openname[256];
2302 s->fpipe = TRUE;
2304 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2305 if (!s->hsend) {
2306 fprintf(stderr, "Failed CreateEvent\n");
2307 goto fail;
2309 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2310 if (!s->hrecv) {
2311 fprintf(stderr, "Failed CreateEvent\n");
2312 goto fail;
2315 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2316 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2317 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2318 PIPE_WAIT,
2319 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2320 if (s->hcom == INVALID_HANDLE_VALUE) {
2321 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2322 s->hcom = NULL;
2323 goto fail;
2326 ZeroMemory(&ov, sizeof(ov));
2327 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2328 ret = ConnectNamedPipe(s->hcom, &ov);
2329 if (ret) {
2330 fprintf(stderr, "Failed ConnectNamedPipe\n");
2331 goto fail;
2334 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2335 if (!ret) {
2336 fprintf(stderr, "Failed GetOverlappedResult\n");
2337 if (ov.hEvent) {
2338 CloseHandle(ov.hEvent);
2339 ov.hEvent = NULL;
2341 goto fail;
2344 if (ov.hEvent) {
2345 CloseHandle(ov.hEvent);
2346 ov.hEvent = NULL;
2348 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2349 return 0;
2351 fail:
2352 win_chr_close(chr);
2353 return -1;
2357 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2359 CharDriverState *chr;
2360 WinCharState *s;
2362 chr = qemu_mallocz(sizeof(CharDriverState));
2363 if (!chr)
2364 return NULL;
2365 s = qemu_mallocz(sizeof(WinCharState));
2366 if (!s) {
2367 free(chr);
2368 return NULL;
2370 chr->opaque = s;
2371 chr->chr_write = win_chr_write;
2372 chr->chr_close = win_chr_close;
2374 if (win_chr_pipe_init(chr, filename) < 0) {
2375 free(s);
2376 free(chr);
2377 return NULL;
2379 qemu_chr_reset(chr);
2380 return chr;
2383 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2385 CharDriverState *chr;
2386 WinCharState *s;
2388 chr = qemu_mallocz(sizeof(CharDriverState));
2389 if (!chr)
2390 return NULL;
2391 s = qemu_mallocz(sizeof(WinCharState));
2392 if (!s) {
2393 free(chr);
2394 return NULL;
2396 s->hcom = fd_out;
2397 chr->opaque = s;
2398 chr->chr_write = win_chr_write;
2399 qemu_chr_reset(chr);
2400 return chr;
2403 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2405 HANDLE fd_out;
2407 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2408 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2409 if (fd_out == INVALID_HANDLE_VALUE)
2410 return NULL;
2412 return qemu_chr_open_win_file(fd_out);
2414 #endif
2416 /***********************************************************/
2417 /* UDP Net console */
2419 typedef struct {
2420 int fd;
2421 struct sockaddr_in daddr;
2422 char buf[1024];
2423 int bufcnt;
2424 int bufptr;
2425 int max_size;
2426 } NetCharDriver;
2428 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2430 NetCharDriver *s = chr->opaque;
2432 return sendto(s->fd, buf, len, 0,
2433 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2436 static int udp_chr_read_poll(void *opaque)
2438 CharDriverState *chr = opaque;
2439 NetCharDriver *s = chr->opaque;
2441 s->max_size = qemu_chr_can_read(chr);
2443 /* If there were any stray characters in the queue process them
2444 * first
2446 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2447 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2448 s->bufptr++;
2449 s->max_size = qemu_chr_can_read(chr);
2451 return s->max_size;
2454 static void udp_chr_read(void *opaque)
2456 CharDriverState *chr = opaque;
2457 NetCharDriver *s = chr->opaque;
2459 if (s->max_size == 0)
2460 return;
2461 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2462 s->bufptr = s->bufcnt;
2463 if (s->bufcnt <= 0)
2464 return;
2466 s->bufptr = 0;
2467 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2468 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2469 s->bufptr++;
2470 s->max_size = qemu_chr_can_read(chr);
2474 static void udp_chr_update_read_handler(CharDriverState *chr)
2476 NetCharDriver *s = chr->opaque;
2478 if (s->fd >= 0) {
2479 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2480 udp_chr_read, NULL, chr);
2484 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2485 #ifndef _WIN32
2486 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2487 #endif
2488 int parse_host_src_port(struct sockaddr_in *haddr,
2489 struct sockaddr_in *saddr,
2490 const char *str);
2492 static CharDriverState *qemu_chr_open_udp(const char *def)
2494 CharDriverState *chr = NULL;
2495 NetCharDriver *s = NULL;
2496 int fd = -1;
2497 struct sockaddr_in saddr;
2499 chr = qemu_mallocz(sizeof(CharDriverState));
2500 if (!chr)
2501 goto return_err;
2502 s = qemu_mallocz(sizeof(NetCharDriver));
2503 if (!s)
2504 goto return_err;
2506 fd = socket(PF_INET, SOCK_DGRAM, 0);
2507 if (fd < 0) {
2508 perror("socket(PF_INET, SOCK_DGRAM)");
2509 goto return_err;
2512 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2513 printf("Could not parse: %s\n", def);
2514 goto return_err;
2517 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2519 perror("bind");
2520 goto return_err;
2523 s->fd = fd;
2524 s->bufcnt = 0;
2525 s->bufptr = 0;
2526 chr->opaque = s;
2527 chr->chr_write = udp_chr_write;
2528 chr->chr_update_read_handler = udp_chr_update_read_handler;
2529 return chr;
2531 return_err:
2532 if (chr)
2533 free(chr);
2534 if (s)
2535 free(s);
2536 if (fd >= 0)
2537 closesocket(fd);
2538 return NULL;
2541 /***********************************************************/
2542 /* TCP Net console */
2544 typedef struct {
2545 int fd, listen_fd;
2546 int connected;
2547 int max_size;
2548 int do_telnetopt;
2549 int do_nodelay;
2550 int is_unix;
2551 } TCPCharDriver;
2553 static void tcp_chr_accept(void *opaque);
2555 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2557 TCPCharDriver *s = chr->opaque;
2558 if (s->connected) {
2559 return send_all(s->fd, buf, len);
2560 } else {
2561 /* XXX: indicate an error ? */
2562 return len;
2566 static int tcp_chr_read_poll(void *opaque)
2568 CharDriverState *chr = opaque;
2569 TCPCharDriver *s = chr->opaque;
2570 if (!s->connected)
2571 return 0;
2572 s->max_size = qemu_chr_can_read(chr);
2573 return s->max_size;
2576 #define IAC 255
2577 #define IAC_BREAK 243
2578 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2579 TCPCharDriver *s,
2580 char *buf, int *size)
2582 /* Handle any telnet client's basic IAC options to satisfy char by
2583 * char mode with no echo. All IAC options will be removed from
2584 * the buf and the do_telnetopt variable will be used to track the
2585 * state of the width of the IAC information.
2587 * IAC commands come in sets of 3 bytes with the exception of the
2588 * "IAC BREAK" command and the double IAC.
2591 int i;
2592 int j = 0;
2594 for (i = 0; i < *size; i++) {
2595 if (s->do_telnetopt > 1) {
2596 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2597 /* Double IAC means send an IAC */
2598 if (j != i)
2599 buf[j] = buf[i];
2600 j++;
2601 s->do_telnetopt = 1;
2602 } else {
2603 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2604 /* Handle IAC break commands by sending a serial break */
2605 qemu_chr_event(chr, CHR_EVENT_BREAK);
2606 s->do_telnetopt++;
2608 s->do_telnetopt++;
2610 if (s->do_telnetopt >= 4) {
2611 s->do_telnetopt = 1;
2613 } else {
2614 if ((unsigned char)buf[i] == IAC) {
2615 s->do_telnetopt = 2;
2616 } else {
2617 if (j != i)
2618 buf[j] = buf[i];
2619 j++;
2623 *size = j;
2626 static void tcp_chr_read(void *opaque)
2628 CharDriverState *chr = opaque;
2629 TCPCharDriver *s = chr->opaque;
2630 uint8_t buf[1024];
2631 int len, size;
2633 if (!s->connected || s->max_size <= 0)
2634 return;
2635 len = sizeof(buf);
2636 if (len > s->max_size)
2637 len = s->max_size;
2638 size = recv(s->fd, buf, len, 0);
2639 if (size == 0) {
2640 /* connection closed */
2641 s->connected = 0;
2642 if (s->listen_fd >= 0) {
2643 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2645 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2646 closesocket(s->fd);
2647 s->fd = -1;
2648 } else if (size > 0) {
2649 if (s->do_telnetopt)
2650 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2651 if (size > 0)
2652 qemu_chr_read(chr, buf, size);
2656 static void tcp_chr_connect(void *opaque)
2658 CharDriverState *chr = opaque;
2659 TCPCharDriver *s = chr->opaque;
2661 s->connected = 1;
2662 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2663 tcp_chr_read, NULL, chr);
2664 qemu_chr_reset(chr);
2667 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2668 static void tcp_chr_telnet_init(int fd)
2670 char buf[3];
2671 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2672 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2673 send(fd, (char *)buf, 3, 0);
2674 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2675 send(fd, (char *)buf, 3, 0);
2676 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2677 send(fd, (char *)buf, 3, 0);
2678 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2679 send(fd, (char *)buf, 3, 0);
2682 static void socket_set_nodelay(int fd)
2684 int val = 1;
2685 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2688 static void tcp_chr_accept(void *opaque)
2690 CharDriverState *chr = opaque;
2691 TCPCharDriver *s = chr->opaque;
2692 struct sockaddr_in saddr;
2693 #ifndef _WIN32
2694 struct sockaddr_un uaddr;
2695 #endif
2696 struct sockaddr *addr;
2697 socklen_t len;
2698 int fd;
2700 for(;;) {
2701 #ifndef _WIN32
2702 if (s->is_unix) {
2703 len = sizeof(uaddr);
2704 addr = (struct sockaddr *)&uaddr;
2705 } else
2706 #endif
2708 len = sizeof(saddr);
2709 addr = (struct sockaddr *)&saddr;
2711 fd = accept(s->listen_fd, addr, &len);
2712 if (fd < 0 && errno != EINTR) {
2713 return;
2714 } else if (fd >= 0) {
2715 if (s->do_telnetopt)
2716 tcp_chr_telnet_init(fd);
2717 break;
2720 socket_set_nonblock(fd);
2721 if (s->do_nodelay)
2722 socket_set_nodelay(fd);
2723 s->fd = fd;
2724 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2725 tcp_chr_connect(chr);
2728 static void tcp_chr_close(CharDriverState *chr)
2730 TCPCharDriver *s = chr->opaque;
2731 if (s->fd >= 0)
2732 closesocket(s->fd);
2733 if (s->listen_fd >= 0)
2734 closesocket(s->listen_fd);
2735 qemu_free(s);
2738 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2739 int is_telnet,
2740 int is_unix)
2742 CharDriverState *chr = NULL;
2743 TCPCharDriver *s = NULL;
2744 int fd = -1, ret, err, val;
2745 int is_listen = 0;
2746 int is_waitconnect = 1;
2747 int do_nodelay = 0;
2748 const char *ptr;
2749 struct sockaddr_in saddr;
2750 #ifndef _WIN32
2751 struct sockaddr_un uaddr;
2752 #endif
2753 struct sockaddr *addr;
2754 socklen_t addrlen;
2756 #ifndef _WIN32
2757 if (is_unix) {
2758 addr = (struct sockaddr *)&uaddr;
2759 addrlen = sizeof(uaddr);
2760 if (parse_unix_path(&uaddr, host_str) < 0)
2761 goto fail;
2762 } else
2763 #endif
2765 addr = (struct sockaddr *)&saddr;
2766 addrlen = sizeof(saddr);
2767 if (parse_host_port(&saddr, host_str) < 0)
2768 goto fail;
2771 ptr = host_str;
2772 while((ptr = strchr(ptr,','))) {
2773 ptr++;
2774 if (!strncmp(ptr,"server",6)) {
2775 is_listen = 1;
2776 } else if (!strncmp(ptr,"nowait",6)) {
2777 is_waitconnect = 0;
2778 } else if (!strncmp(ptr,"nodelay",6)) {
2779 do_nodelay = 1;
2780 } else {
2781 printf("Unknown option: %s\n", ptr);
2782 goto fail;
2785 if (!is_listen)
2786 is_waitconnect = 0;
2788 chr = qemu_mallocz(sizeof(CharDriverState));
2789 if (!chr)
2790 goto fail;
2791 s = qemu_mallocz(sizeof(TCPCharDriver));
2792 if (!s)
2793 goto fail;
2795 #ifndef _WIN32
2796 if (is_unix)
2797 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2798 else
2799 #endif
2800 fd = socket(PF_INET, SOCK_STREAM, 0);
2802 if (fd < 0)
2803 goto fail;
2805 if (!is_waitconnect)
2806 socket_set_nonblock(fd);
2808 s->connected = 0;
2809 s->fd = -1;
2810 s->listen_fd = -1;
2811 s->is_unix = is_unix;
2812 s->do_nodelay = do_nodelay && !is_unix;
2814 chr->opaque = s;
2815 chr->chr_write = tcp_chr_write;
2816 chr->chr_close = tcp_chr_close;
2818 if (is_listen) {
2819 /* allow fast reuse */
2820 #ifndef _WIN32
2821 if (is_unix) {
2822 char path[109];
2823 strncpy(path, uaddr.sun_path, 108);
2824 path[108] = 0;
2825 unlink(path);
2826 } else
2827 #endif
2829 val = 1;
2830 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2833 ret = bind(fd, addr, addrlen);
2834 if (ret < 0)
2835 goto fail;
2837 ret = listen(fd, 0);
2838 if (ret < 0)
2839 goto fail;
2841 s->listen_fd = fd;
2842 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2843 if (is_telnet)
2844 s->do_telnetopt = 1;
2845 } else {
2846 for(;;) {
2847 ret = connect(fd, addr, addrlen);
2848 if (ret < 0) {
2849 err = socket_error();
2850 if (err == EINTR || err == EWOULDBLOCK) {
2851 } else if (err == EINPROGRESS) {
2852 break;
2853 } else {
2854 goto fail;
2856 } else {
2857 s->connected = 1;
2858 break;
2861 s->fd = fd;
2862 socket_set_nodelay(fd);
2863 if (s->connected)
2864 tcp_chr_connect(chr);
2865 else
2866 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2869 if (is_listen && is_waitconnect) {
2870 printf("QEMU waiting for connection on: %s\n", host_str);
2871 tcp_chr_accept(chr);
2872 socket_set_nonblock(s->listen_fd);
2875 return chr;
2876 fail:
2877 if (fd >= 0)
2878 closesocket(fd);
2879 qemu_free(s);
2880 qemu_free(chr);
2881 return NULL;
2884 CharDriverState *qemu_chr_open(const char *filename)
2886 const char *p;
2888 if (!strcmp(filename, "vc")) {
2889 return text_console_init(&display_state);
2890 } else if (!strcmp(filename, "null")) {
2891 return qemu_chr_open_null();
2892 } else
2893 if (strstart(filename, "tcp:", &p)) {
2894 return qemu_chr_open_tcp(p, 0, 0);
2895 } else
2896 if (strstart(filename, "telnet:", &p)) {
2897 return qemu_chr_open_tcp(p, 1, 0);
2898 } else
2899 if (strstart(filename, "udp:", &p)) {
2900 return qemu_chr_open_udp(p);
2901 } else
2902 if (strstart(filename, "mon:", &p)) {
2903 CharDriverState *drv = qemu_chr_open(p);
2904 if (drv) {
2905 drv = qemu_chr_open_mux(drv);
2906 monitor_init(drv, !nographic);
2907 return drv;
2909 printf("Unable to open driver: %s\n", p);
2910 return 0;
2911 } else
2912 #ifndef _WIN32
2913 if (strstart(filename, "unix:", &p)) {
2914 return qemu_chr_open_tcp(p, 0, 1);
2915 } else if (strstart(filename, "file:", &p)) {
2916 return qemu_chr_open_file_out(p);
2917 } else if (strstart(filename, "pipe:", &p)) {
2918 return qemu_chr_open_pipe(p);
2919 } else if (!strcmp(filename, "pty")) {
2920 return qemu_chr_open_pty();
2921 } else if (!strcmp(filename, "stdio")) {
2922 return qemu_chr_open_stdio();
2923 } else
2924 #endif
2925 #if defined(__linux__)
2926 if (strstart(filename, "/dev/parport", NULL)) {
2927 return qemu_chr_open_pp(filename);
2928 } else
2929 if (strstart(filename, "/dev/", NULL)) {
2930 return qemu_chr_open_tty(filename);
2931 } else
2932 #endif
2933 #ifdef _WIN32
2934 if (strstart(filename, "COM", NULL)) {
2935 return qemu_chr_open_win(filename);
2936 } else
2937 if (strstart(filename, "pipe:", &p)) {
2938 return qemu_chr_open_win_pipe(p);
2939 } else
2940 if (strstart(filename, "file:", &p)) {
2941 return qemu_chr_open_win_file_out(p);
2943 #endif
2945 return NULL;
2949 void qemu_chr_close(CharDriverState *chr)
2951 if (chr->chr_close)
2952 chr->chr_close(chr);
2955 /***********************************************************/
2956 /* network device redirectors */
2958 void hex_dump(FILE *f, const uint8_t *buf, int size)
2960 int len, i, j, c;
2962 for(i=0;i<size;i+=16) {
2963 len = size - i;
2964 if (len > 16)
2965 len = 16;
2966 fprintf(f, "%08x ", i);
2967 for(j=0;j<16;j++) {
2968 if (j < len)
2969 fprintf(f, " %02x", buf[i+j]);
2970 else
2971 fprintf(f, " ");
2973 fprintf(f, " ");
2974 for(j=0;j<len;j++) {
2975 c = buf[i+j];
2976 if (c < ' ' || c > '~')
2977 c = '.';
2978 fprintf(f, "%c", c);
2980 fprintf(f, "\n");
2984 static int parse_macaddr(uint8_t *macaddr, const char *p)
2986 int i;
2987 for(i = 0; i < 6; i++) {
2988 macaddr[i] = strtol(p, (char **)&p, 16);
2989 if (i == 5) {
2990 if (*p != '\0')
2991 return -1;
2992 } else {
2993 if (*p != ':')
2994 return -1;
2995 p++;
2998 return 0;
3001 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3003 const char *p, *p1;
3004 int len;
3005 p = *pp;
3006 p1 = strchr(p, sep);
3007 if (!p1)
3008 return -1;
3009 len = p1 - p;
3010 p1++;
3011 if (buf_size > 0) {
3012 if (len > buf_size - 1)
3013 len = buf_size - 1;
3014 memcpy(buf, p, len);
3015 buf[len] = '\0';
3017 *pp = p1;
3018 return 0;
3021 int parse_host_src_port(struct sockaddr_in *haddr,
3022 struct sockaddr_in *saddr,
3023 const char *input_str)
3025 char *str = strdup(input_str);
3026 char *host_str = str;
3027 char *src_str;
3028 char *ptr;
3031 * Chop off any extra arguments at the end of the string which
3032 * would start with a comma, then fill in the src port information
3033 * if it was provided else use the "any address" and "any port".
3035 if ((ptr = strchr(str,',')))
3036 *ptr = '\0';
3038 if ((src_str = strchr(input_str,'@'))) {
3039 *src_str = '\0';
3040 src_str++;
3043 if (parse_host_port(haddr, host_str) < 0)
3044 goto fail;
3046 if (!src_str || *src_str == '\0')
3047 src_str = ":0";
3049 if (parse_host_port(saddr, src_str) < 0)
3050 goto fail;
3052 free(str);
3053 return(0);
3055 fail:
3056 free(str);
3057 return -1;
3060 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3062 char buf[512];
3063 struct hostent *he;
3064 const char *p, *r;
3065 int port;
3067 p = str;
3068 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3069 return -1;
3070 saddr->sin_family = AF_INET;
3071 if (buf[0] == '\0') {
3072 saddr->sin_addr.s_addr = 0;
3073 } else {
3074 if (isdigit(buf[0])) {
3075 if (!inet_aton(buf, &saddr->sin_addr))
3076 return -1;
3077 } else {
3078 if ((he = gethostbyname(buf)) == NULL)
3079 return - 1;
3080 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3083 port = strtol(p, (char **)&r, 0);
3084 if (r == p)
3085 return -1;
3086 saddr->sin_port = htons(port);
3087 return 0;
3090 #ifndef _WIN32
3091 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3093 const char *p;
3094 int len;
3096 len = MIN(108, strlen(str));
3097 p = strchr(str, ',');
3098 if (p)
3099 len = MIN(len, p - str);
3101 memset(uaddr, 0, sizeof(*uaddr));
3103 uaddr->sun_family = AF_UNIX;
3104 memcpy(uaddr->sun_path, str, len);
3106 return 0;
3108 #endif
3110 /* find or alloc a new VLAN */
3111 VLANState *qemu_find_vlan(int id)
3113 VLANState **pvlan, *vlan;
3114 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3115 if (vlan->id == id)
3116 return vlan;
3118 vlan = qemu_mallocz(sizeof(VLANState));
3119 if (!vlan)
3120 return NULL;
3121 vlan->id = id;
3122 vlan->next = NULL;
3123 pvlan = &first_vlan;
3124 while (*pvlan != NULL)
3125 pvlan = &(*pvlan)->next;
3126 *pvlan = vlan;
3127 return vlan;
3130 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3131 IOReadHandler *fd_read,
3132 IOCanRWHandler *fd_can_read,
3133 void *opaque)
3135 VLANClientState *vc, **pvc;
3136 vc = qemu_mallocz(sizeof(VLANClientState));
3137 if (!vc)
3138 return NULL;
3139 vc->fd_read = fd_read;
3140 vc->fd_can_read = fd_can_read;
3141 vc->opaque = opaque;
3142 vc->vlan = vlan;
3144 vc->next = NULL;
3145 pvc = &vlan->first_client;
3146 while (*pvc != NULL)
3147 pvc = &(*pvc)->next;
3148 *pvc = vc;
3149 return vc;
3152 int qemu_can_send_packet(VLANClientState *vc1)
3154 VLANState *vlan = vc1->vlan;
3155 VLANClientState *vc;
3157 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3158 if (vc != vc1) {
3159 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3160 return 0;
3163 return 1;
3166 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3168 VLANState *vlan = vc1->vlan;
3169 VLANClientState *vc;
3171 #if 0
3172 printf("vlan %d send:\n", vlan->id);
3173 hex_dump(stdout, buf, size);
3174 #endif
3175 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3176 if (vc != vc1) {
3177 vc->fd_read(vc->opaque, buf, size);
3182 #if defined(CONFIG_SLIRP)
3184 /* slirp network adapter */
3186 static int slirp_inited;
3187 static VLANClientState *slirp_vc;
3189 int slirp_can_output(void)
3191 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3194 void slirp_output(const uint8_t *pkt, int pkt_len)
3196 #if 0
3197 printf("slirp output:\n");
3198 hex_dump(stdout, pkt, pkt_len);
3199 #endif
3200 if (!slirp_vc)
3201 return;
3202 qemu_send_packet(slirp_vc, pkt, pkt_len);
3205 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3207 #if 0
3208 printf("slirp input:\n");
3209 hex_dump(stdout, buf, size);
3210 #endif
3211 slirp_input(buf, size);
3214 static int net_slirp_init(VLANState *vlan)
3216 if (!slirp_inited) {
3217 slirp_inited = 1;
3218 slirp_init();
3220 slirp_vc = qemu_new_vlan_client(vlan,
3221 slirp_receive, NULL, NULL);
3222 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3223 return 0;
3226 static void net_slirp_redir(const char *redir_str)
3228 int is_udp;
3229 char buf[256], *r;
3230 const char *p;
3231 struct in_addr guest_addr;
3232 int host_port, guest_port;
3234 if (!slirp_inited) {
3235 slirp_inited = 1;
3236 slirp_init();
3239 p = redir_str;
3240 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3241 goto fail;
3242 if (!strcmp(buf, "tcp")) {
3243 is_udp = 0;
3244 } else if (!strcmp(buf, "udp")) {
3245 is_udp = 1;
3246 } else {
3247 goto fail;
3250 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3251 goto fail;
3252 host_port = strtol(buf, &r, 0);
3253 if (r == buf)
3254 goto fail;
3256 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3257 goto fail;
3258 if (buf[0] == '\0') {
3259 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3261 if (!inet_aton(buf, &guest_addr))
3262 goto fail;
3264 guest_port = strtol(p, &r, 0);
3265 if (r == p)
3266 goto fail;
3268 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3269 fprintf(stderr, "qemu: could not set up redirection\n");
3270 exit(1);
3272 return;
3273 fail:
3274 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3275 exit(1);
3278 #ifndef _WIN32
3280 char smb_dir[1024];
3282 static void smb_exit(void)
3284 DIR *d;
3285 struct dirent *de;
3286 char filename[1024];
3288 /* erase all the files in the directory */
3289 d = opendir(smb_dir);
3290 for(;;) {
3291 de = readdir(d);
3292 if (!de)
3293 break;
3294 if (strcmp(de->d_name, ".") != 0 &&
3295 strcmp(de->d_name, "..") != 0) {
3296 snprintf(filename, sizeof(filename), "%s/%s",
3297 smb_dir, de->d_name);
3298 unlink(filename);
3301 closedir(d);
3302 rmdir(smb_dir);
3305 /* automatic user mode samba server configuration */
3306 void net_slirp_smb(const char *exported_dir)
3308 char smb_conf[1024];
3309 char smb_cmdline[1024];
3310 FILE *f;
3312 if (!slirp_inited) {
3313 slirp_inited = 1;
3314 slirp_init();
3317 /* XXX: better tmp dir construction */
3318 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3319 if (mkdir(smb_dir, 0700) < 0) {
3320 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3321 exit(1);
3323 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3325 f = fopen(smb_conf, "w");
3326 if (!f) {
3327 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3328 exit(1);
3330 fprintf(f,
3331 "[global]\n"
3332 "private dir=%s\n"
3333 "smb ports=0\n"
3334 "socket address=127.0.0.1\n"
3335 "pid directory=%s\n"
3336 "lock directory=%s\n"
3337 "log file=%s/log.smbd\n"
3338 "smb passwd file=%s/smbpasswd\n"
3339 "security = share\n"
3340 "[qemu]\n"
3341 "path=%s\n"
3342 "read only=no\n"
3343 "guest ok=yes\n",
3344 smb_dir,
3345 smb_dir,
3346 smb_dir,
3347 smb_dir,
3348 smb_dir,
3349 exported_dir
3351 fclose(f);
3352 atexit(smb_exit);
3354 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3355 SMBD_COMMAND, smb_conf);
3357 slirp_add_exec(0, smb_cmdline, 4, 139);
3360 #endif /* !defined(_WIN32) */
3362 #endif /* CONFIG_SLIRP */
3364 #if !defined(_WIN32)
3366 typedef struct TAPState {
3367 VLANClientState *vc;
3368 int fd;
3369 } TAPState;
3371 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3373 TAPState *s = opaque;
3374 int ret;
3375 for(;;) {
3376 ret = write(s->fd, buf, size);
3377 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3378 } else {
3379 break;
3384 static void tap_send(void *opaque)
3386 TAPState *s = opaque;
3387 uint8_t buf[4096];
3388 int size;
3390 #ifdef __sun__
3391 struct strbuf sbuf;
3392 int f = 0;
3393 sbuf.maxlen = sizeof(buf);
3394 sbuf.buf = buf;
3395 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3396 #else
3397 size = read(s->fd, buf, sizeof(buf));
3398 #endif
3399 if (size > 0) {
3400 qemu_send_packet(s->vc, buf, size);
3404 /* fd support */
3406 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3408 TAPState *s;
3410 s = qemu_mallocz(sizeof(TAPState));
3411 if (!s)
3412 return NULL;
3413 s->fd = fd;
3414 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3415 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3416 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3417 return s;
3420 #ifdef _BSD
3421 static int tap_open(char *ifname, int ifname_size)
3423 int fd;
3424 char *dev;
3425 struct stat s;
3427 fd = open("/dev/tap", O_RDWR);
3428 if (fd < 0) {
3429 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3430 return -1;
3433 fstat(fd, &s);
3434 dev = devname(s.st_rdev, S_IFCHR);
3435 pstrcpy(ifname, ifname_size, dev);
3437 fcntl(fd, F_SETFL, O_NONBLOCK);
3438 return fd;
3440 #elif defined(__sun__)
3441 #define TUNNEWPPA (('T'<<16) | 0x0001)
3443 * Allocate TAP device, returns opened fd.
3444 * Stores dev name in the first arg(must be large enough).
3446 int tap_alloc(char *dev)
3448 int tap_fd, if_fd, ppa = -1;
3449 static int ip_fd = 0;
3450 char *ptr;
3452 static int arp_fd = 0;
3453 int ip_muxid, arp_muxid;
3454 struct strioctl strioc_if, strioc_ppa;
3455 int link_type = I_PLINK;;
3456 struct lifreq ifr;
3457 char actual_name[32] = "";
3459 memset(&ifr, 0x0, sizeof(ifr));
3461 if( *dev ){
3462 ptr = dev;
3463 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3464 ppa = atoi(ptr);
3467 /* Check if IP device was opened */
3468 if( ip_fd )
3469 close(ip_fd);
3471 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3472 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3473 return -1;
3476 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3477 syslog(LOG_ERR, "Can't open /dev/tap");
3478 return -1;
3481 /* Assign a new PPA and get its unit number. */
3482 strioc_ppa.ic_cmd = TUNNEWPPA;
3483 strioc_ppa.ic_timout = 0;
3484 strioc_ppa.ic_len = sizeof(ppa);
3485 strioc_ppa.ic_dp = (char *)&ppa;
3486 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3487 syslog (LOG_ERR, "Can't assign new interface");
3489 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3490 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3491 return -1;
3493 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3494 syslog(LOG_ERR, "Can't push IP module");
3495 return -1;
3498 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3499 syslog(LOG_ERR, "Can't get flags\n");
3501 snprintf (actual_name, 32, "tap%d", ppa);
3502 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3504 ifr.lifr_ppa = ppa;
3505 /* Assign ppa according to the unit number returned by tun device */
3507 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3508 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3509 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3510 syslog (LOG_ERR, "Can't get flags\n");
3511 /* Push arp module to if_fd */
3512 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3513 syslog (LOG_ERR, "Can't push ARP module (2)");
3515 /* Push arp module to ip_fd */
3516 if (ioctl (ip_fd, I_POP, NULL) < 0)
3517 syslog (LOG_ERR, "I_POP failed\n");
3518 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3519 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3520 /* Open arp_fd */
3521 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3522 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3524 /* Set ifname to arp */
3525 strioc_if.ic_cmd = SIOCSLIFNAME;
3526 strioc_if.ic_timout = 0;
3527 strioc_if.ic_len = sizeof(ifr);
3528 strioc_if.ic_dp = (char *)&ifr;
3529 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3530 syslog (LOG_ERR, "Can't set ifname to arp\n");
3533 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3534 syslog(LOG_ERR, "Can't link TAP device to IP");
3535 return -1;
3538 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3539 syslog (LOG_ERR, "Can't link TAP device to ARP");
3541 close (if_fd);
3543 memset(&ifr, 0x0, sizeof(ifr));
3544 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3545 ifr.lifr_ip_muxid = ip_muxid;
3546 ifr.lifr_arp_muxid = arp_muxid;
3548 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3550 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3551 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3552 syslog (LOG_ERR, "Can't set multiplexor id");
3555 sprintf(dev, "tap%d", ppa);
3556 return tap_fd;
3559 static int tap_open(char *ifname, int ifname_size)
3561 char dev[10]="";
3562 int fd;
3563 if( (fd = tap_alloc(dev)) < 0 ){
3564 fprintf(stderr, "Cannot allocate TAP device\n");
3565 return -1;
3567 pstrcpy(ifname, ifname_size, dev);
3568 fcntl(fd, F_SETFL, O_NONBLOCK);
3569 return fd;
3571 #else
3572 static int tap_open(char *ifname, int ifname_size)
3574 struct ifreq ifr;
3575 int fd, ret;
3577 fd = open("/dev/net/tun", O_RDWR);
3578 if (fd < 0) {
3579 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3580 return -1;
3582 memset(&ifr, 0, sizeof(ifr));
3583 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3584 if (ifname[0] != '\0')
3585 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3586 else
3587 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3588 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3589 if (ret != 0) {
3590 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3591 close(fd);
3592 return -1;
3594 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3595 fcntl(fd, F_SETFL, O_NONBLOCK);
3596 return fd;
3598 #endif
3600 static int net_tap_init(VLANState *vlan, const char *ifname1,
3601 const char *setup_script)
3603 TAPState *s;
3604 int pid, status, fd;
3605 char *args[3];
3606 char **parg;
3607 char ifname[128];
3609 if (ifname1 != NULL)
3610 pstrcpy(ifname, sizeof(ifname), ifname1);
3611 else
3612 ifname[0] = '\0';
3613 fd = tap_open(ifname, sizeof(ifname));
3614 if (fd < 0)
3615 return -1;
3617 if (!setup_script || !strcmp(setup_script, "no"))
3618 setup_script = "";
3619 if (setup_script[0] != '\0') {
3620 /* try to launch network init script */
3621 pid = fork();
3622 if (pid >= 0) {
3623 if (pid == 0) {
3624 int open_max = sysconf (_SC_OPEN_MAX), i;
3625 for (i = 0; i < open_max; i++)
3626 if (i != STDIN_FILENO &&
3627 i != STDOUT_FILENO &&
3628 i != STDERR_FILENO &&
3629 i != fd)
3630 close(i);
3632 parg = args;
3633 *parg++ = (char *)setup_script;
3634 *parg++ = ifname;
3635 *parg++ = NULL;
3636 execv(setup_script, args);
3637 _exit(1);
3639 while (waitpid(pid, &status, 0) != pid);
3640 if (!WIFEXITED(status) ||
3641 WEXITSTATUS(status) != 0) {
3642 fprintf(stderr, "%s: could not launch network script\n",
3643 setup_script);
3644 return -1;
3648 s = net_tap_fd_init(vlan, fd);
3649 if (!s)
3650 return -1;
3651 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3652 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3653 return 0;
3656 #endif /* !_WIN32 */
3658 /* network connection */
3659 typedef struct NetSocketState {
3660 VLANClientState *vc;
3661 int fd;
3662 int state; /* 0 = getting length, 1 = getting data */
3663 int index;
3664 int packet_len;
3665 uint8_t buf[4096];
3666 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3667 } NetSocketState;
3669 typedef struct NetSocketListenState {
3670 VLANState *vlan;
3671 int fd;
3672 } NetSocketListenState;
3674 /* XXX: we consider we can send the whole packet without blocking */
3675 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3677 NetSocketState *s = opaque;
3678 uint32_t len;
3679 len = htonl(size);
3681 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3682 send_all(s->fd, buf, size);
3685 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3687 NetSocketState *s = opaque;
3688 sendto(s->fd, buf, size, 0,
3689 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3692 static void net_socket_send(void *opaque)
3694 NetSocketState *s = opaque;
3695 int l, size, err;
3696 uint8_t buf1[4096];
3697 const uint8_t *buf;
3699 size = recv(s->fd, buf1, sizeof(buf1), 0);
3700 if (size < 0) {
3701 err = socket_error();
3702 if (err != EWOULDBLOCK)
3703 goto eoc;
3704 } else if (size == 0) {
3705 /* end of connection */
3706 eoc:
3707 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3708 closesocket(s->fd);
3709 return;
3711 buf = buf1;
3712 while (size > 0) {
3713 /* reassemble a packet from the network */
3714 switch(s->state) {
3715 case 0:
3716 l = 4 - s->index;
3717 if (l > size)
3718 l = size;
3719 memcpy(s->buf + s->index, buf, l);
3720 buf += l;
3721 size -= l;
3722 s->index += l;
3723 if (s->index == 4) {
3724 /* got length */
3725 s->packet_len = ntohl(*(uint32_t *)s->buf);
3726 s->index = 0;
3727 s->state = 1;
3729 break;
3730 case 1:
3731 l = s->packet_len - s->index;
3732 if (l > size)
3733 l = size;
3734 memcpy(s->buf + s->index, buf, l);
3735 s->index += l;
3736 buf += l;
3737 size -= l;
3738 if (s->index >= s->packet_len) {
3739 qemu_send_packet(s->vc, s->buf, s->packet_len);
3740 s->index = 0;
3741 s->state = 0;
3743 break;
3748 static void net_socket_send_dgram(void *opaque)
3750 NetSocketState *s = opaque;
3751 int size;
3753 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3754 if (size < 0)
3755 return;
3756 if (size == 0) {
3757 /* end of connection */
3758 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3759 return;
3761 qemu_send_packet(s->vc, s->buf, size);
3764 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3766 struct ip_mreq imr;
3767 int fd;
3768 int val, ret;
3769 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3770 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3771 inet_ntoa(mcastaddr->sin_addr),
3772 (int)ntohl(mcastaddr->sin_addr.s_addr));
3773 return -1;
3776 fd = socket(PF_INET, SOCK_DGRAM, 0);
3777 if (fd < 0) {
3778 perror("socket(PF_INET, SOCK_DGRAM)");
3779 return -1;
3782 val = 1;
3783 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3784 (const char *)&val, sizeof(val));
3785 if (ret < 0) {
3786 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3787 goto fail;
3790 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3791 if (ret < 0) {
3792 perror("bind");
3793 goto fail;
3796 /* Add host to multicast group */
3797 imr.imr_multiaddr = mcastaddr->sin_addr;
3798 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3800 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3801 (const char *)&imr, sizeof(struct ip_mreq));
3802 if (ret < 0) {
3803 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3804 goto fail;
3807 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3808 val = 1;
3809 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3810 (const char *)&val, sizeof(val));
3811 if (ret < 0) {
3812 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3813 goto fail;
3816 socket_set_nonblock(fd);
3817 return fd;
3818 fail:
3819 if (fd >= 0)
3820 closesocket(fd);
3821 return -1;
3824 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3825 int is_connected)
3827 struct sockaddr_in saddr;
3828 int newfd;
3829 socklen_t saddr_len;
3830 NetSocketState *s;
3832 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3833 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3834 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3837 if (is_connected) {
3838 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3839 /* must be bound */
3840 if (saddr.sin_addr.s_addr==0) {
3841 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3842 fd);
3843 return NULL;
3845 /* clone dgram socket */
3846 newfd = net_socket_mcast_create(&saddr);
3847 if (newfd < 0) {
3848 /* error already reported by net_socket_mcast_create() */
3849 close(fd);
3850 return NULL;
3852 /* clone newfd to fd, close newfd */
3853 dup2(newfd, fd);
3854 close(newfd);
3856 } else {
3857 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3858 fd, strerror(errno));
3859 return NULL;
3863 s = qemu_mallocz(sizeof(NetSocketState));
3864 if (!s)
3865 return NULL;
3866 s->fd = fd;
3868 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3869 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3871 /* mcast: save bound address as dst */
3872 if (is_connected) s->dgram_dst=saddr;
3874 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3875 "socket: fd=%d (%s mcast=%s:%d)",
3876 fd, is_connected? "cloned" : "",
3877 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3878 return s;
3881 static void net_socket_connect(void *opaque)
3883 NetSocketState *s = opaque;
3884 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3887 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3888 int is_connected)
3890 NetSocketState *s;
3891 s = qemu_mallocz(sizeof(NetSocketState));
3892 if (!s)
3893 return NULL;
3894 s->fd = fd;
3895 s->vc = qemu_new_vlan_client(vlan,
3896 net_socket_receive, NULL, s);
3897 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3898 "socket: fd=%d", fd);
3899 if (is_connected) {
3900 net_socket_connect(s);
3901 } else {
3902 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3904 return s;
3907 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3908 int is_connected)
3910 int so_type=-1, optlen=sizeof(so_type);
3912 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3913 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3914 return NULL;
3916 switch(so_type) {
3917 case SOCK_DGRAM:
3918 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3919 case SOCK_STREAM:
3920 return net_socket_fd_init_stream(vlan, fd, is_connected);
3921 default:
3922 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3923 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3924 return net_socket_fd_init_stream(vlan, fd, is_connected);
3926 return NULL;
3929 static void net_socket_accept(void *opaque)
3931 NetSocketListenState *s = opaque;
3932 NetSocketState *s1;
3933 struct sockaddr_in saddr;
3934 socklen_t len;
3935 int fd;
3937 for(;;) {
3938 len = sizeof(saddr);
3939 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3940 if (fd < 0 && errno != EINTR) {
3941 return;
3942 } else if (fd >= 0) {
3943 break;
3946 s1 = net_socket_fd_init(s->vlan, fd, 1);
3947 if (!s1) {
3948 closesocket(fd);
3949 } else {
3950 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3951 "socket: connection from %s:%d",
3952 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3956 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3958 NetSocketListenState *s;
3959 int fd, val, ret;
3960 struct sockaddr_in saddr;
3962 if (parse_host_port(&saddr, host_str) < 0)
3963 return -1;
3965 s = qemu_mallocz(sizeof(NetSocketListenState));
3966 if (!s)
3967 return -1;
3969 fd = socket(PF_INET, SOCK_STREAM, 0);
3970 if (fd < 0) {
3971 perror("socket");
3972 return -1;
3974 socket_set_nonblock(fd);
3976 /* allow fast reuse */
3977 val = 1;
3978 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3980 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3981 if (ret < 0) {
3982 perror("bind");
3983 return -1;
3985 ret = listen(fd, 0);
3986 if (ret < 0) {
3987 perror("listen");
3988 return -1;
3990 s->vlan = vlan;
3991 s->fd = fd;
3992 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3993 return 0;
3996 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3998 NetSocketState *s;
3999 int fd, connected, ret, err;
4000 struct sockaddr_in saddr;
4002 if (parse_host_port(&saddr, host_str) < 0)
4003 return -1;
4005 fd = socket(PF_INET, SOCK_STREAM, 0);
4006 if (fd < 0) {
4007 perror("socket");
4008 return -1;
4010 socket_set_nonblock(fd);
4012 connected = 0;
4013 for(;;) {
4014 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4015 if (ret < 0) {
4016 err = socket_error();
4017 if (err == EINTR || err == EWOULDBLOCK) {
4018 } else if (err == EINPROGRESS) {
4019 break;
4020 } else {
4021 perror("connect");
4022 closesocket(fd);
4023 return -1;
4025 } else {
4026 connected = 1;
4027 break;
4030 s = net_socket_fd_init(vlan, fd, connected);
4031 if (!s)
4032 return -1;
4033 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4034 "socket: connect to %s:%d",
4035 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4036 return 0;
4039 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4041 NetSocketState *s;
4042 int fd;
4043 struct sockaddr_in saddr;
4045 if (parse_host_port(&saddr, host_str) < 0)
4046 return -1;
4049 fd = net_socket_mcast_create(&saddr);
4050 if (fd < 0)
4051 return -1;
4053 s = net_socket_fd_init(vlan, fd, 0);
4054 if (!s)
4055 return -1;
4057 s->dgram_dst = saddr;
4059 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4060 "socket: mcast=%s:%d",
4061 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4062 return 0;
4066 static int get_param_value(char *buf, int buf_size,
4067 const char *tag, const char *str)
4069 const char *p;
4070 char *q;
4071 char option[128];
4073 p = str;
4074 for(;;) {
4075 q = option;
4076 while (*p != '\0' && *p != '=') {
4077 if ((q - option) < sizeof(option) - 1)
4078 *q++ = *p;
4079 p++;
4081 *q = '\0';
4082 if (*p != '=')
4083 break;
4084 p++;
4085 if (!strcmp(tag, option)) {
4086 q = buf;
4087 while (*p != '\0' && *p != ',') {
4088 if ((q - buf) < buf_size - 1)
4089 *q++ = *p;
4090 p++;
4092 *q = '\0';
4093 return q - buf;
4094 } else {
4095 while (*p != '\0' && *p != ',') {
4096 p++;
4099 if (*p != ',')
4100 break;
4101 p++;
4103 return 0;
4106 static int net_client_init(const char *str)
4108 const char *p;
4109 char *q;
4110 char device[64];
4111 char buf[1024];
4112 int vlan_id, ret;
4113 VLANState *vlan;
4115 p = str;
4116 q = device;
4117 while (*p != '\0' && *p != ',') {
4118 if ((q - device) < sizeof(device) - 1)
4119 *q++ = *p;
4120 p++;
4122 *q = '\0';
4123 if (*p == ',')
4124 p++;
4125 vlan_id = 0;
4126 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4127 vlan_id = strtol(buf, NULL, 0);
4129 vlan = qemu_find_vlan(vlan_id);
4130 if (!vlan) {
4131 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4132 return -1;
4134 if (!strcmp(device, "nic")) {
4135 NICInfo *nd;
4136 uint8_t *macaddr;
4138 if (nb_nics >= MAX_NICS) {
4139 fprintf(stderr, "Too Many NICs\n");
4140 return -1;
4142 nd = &nd_table[nb_nics];
4143 macaddr = nd->macaddr;
4144 macaddr[0] = 0x52;
4145 macaddr[1] = 0x54;
4146 macaddr[2] = 0x00;
4147 macaddr[3] = 0x12;
4148 macaddr[4] = 0x34;
4149 macaddr[5] = 0x56 + nb_nics;
4151 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4152 if (parse_macaddr(macaddr, buf) < 0) {
4153 fprintf(stderr, "invalid syntax for ethernet address\n");
4154 return -1;
4157 if (get_param_value(buf, sizeof(buf), "model", p)) {
4158 nd->model = strdup(buf);
4160 nd->vlan = vlan;
4161 nb_nics++;
4162 ret = 0;
4163 } else
4164 if (!strcmp(device, "none")) {
4165 /* does nothing. It is needed to signal that no network cards
4166 are wanted */
4167 ret = 0;
4168 } else
4169 #ifdef CONFIG_SLIRP
4170 if (!strcmp(device, "user")) {
4171 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4172 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4174 ret = net_slirp_init(vlan);
4175 } else
4176 #endif
4177 #ifdef _WIN32
4178 if (!strcmp(device, "tap")) {
4179 char ifname[64];
4180 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4181 fprintf(stderr, "tap: no interface name\n");
4182 return -1;
4184 ret = tap_win32_init(vlan, ifname);
4185 } else
4186 #else
4187 if (!strcmp(device, "tap")) {
4188 char ifname[64];
4189 char setup_script[1024];
4190 int fd;
4191 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4192 fd = strtol(buf, NULL, 0);
4193 ret = -1;
4194 if (net_tap_fd_init(vlan, fd))
4195 ret = 0;
4196 } else {
4197 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4198 ifname[0] = '\0';
4200 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4201 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4203 ret = net_tap_init(vlan, ifname, setup_script);
4205 } else
4206 #endif
4207 if (!strcmp(device, "socket")) {
4208 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4209 int fd;
4210 fd = strtol(buf, NULL, 0);
4211 ret = -1;
4212 if (net_socket_fd_init(vlan, fd, 1))
4213 ret = 0;
4214 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4215 ret = net_socket_listen_init(vlan, buf);
4216 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4217 ret = net_socket_connect_init(vlan, buf);
4218 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4219 ret = net_socket_mcast_init(vlan, buf);
4220 } else {
4221 fprintf(stderr, "Unknown socket options: %s\n", p);
4222 return -1;
4224 } else
4226 fprintf(stderr, "Unknown network device: %s\n", device);
4227 return -1;
4229 if (ret < 0) {
4230 fprintf(stderr, "Could not initialize device '%s'\n", device);
4233 return ret;
4236 void do_info_network(void)
4238 VLANState *vlan;
4239 VLANClientState *vc;
4241 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4242 term_printf("VLAN %d devices:\n", vlan->id);
4243 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4244 term_printf(" %s\n", vc->info_str);
4248 /***********************************************************/
4249 /* USB devices */
4251 static USBPort *used_usb_ports;
4252 static USBPort *free_usb_ports;
4254 /* ??? Maybe change this to register a hub to keep track of the topology. */
4255 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4256 usb_attachfn attach)
4258 port->opaque = opaque;
4259 port->index = index;
4260 port->attach = attach;
4261 port->next = free_usb_ports;
4262 free_usb_ports = port;
4265 static int usb_device_add(const char *devname)
4267 const char *p;
4268 USBDevice *dev;
4269 USBPort *port;
4271 if (!free_usb_ports)
4272 return -1;
4274 if (strstart(devname, "host:", &p)) {
4275 dev = usb_host_device_open(p);
4276 } else if (!strcmp(devname, "mouse")) {
4277 dev = usb_mouse_init();
4278 } else if (!strcmp(devname, "tablet")) {
4279 dev = usb_tablet_init();
4280 } else if (strstart(devname, "disk:", &p)) {
4281 dev = usb_msd_init(p);
4282 } else {
4283 return -1;
4285 if (!dev)
4286 return -1;
4288 /* Find a USB port to add the device to. */
4289 port = free_usb_ports;
4290 if (!port->next) {
4291 USBDevice *hub;
4293 /* Create a new hub and chain it on. */
4294 free_usb_ports = NULL;
4295 port->next = used_usb_ports;
4296 used_usb_ports = port;
4298 hub = usb_hub_init(VM_USB_HUB_SIZE);
4299 usb_attach(port, hub);
4300 port = free_usb_ports;
4303 free_usb_ports = port->next;
4304 port->next = used_usb_ports;
4305 used_usb_ports = port;
4306 usb_attach(port, dev);
4307 return 0;
4310 static int usb_device_del(const char *devname)
4312 USBPort *port;
4313 USBPort **lastp;
4314 USBDevice *dev;
4315 int bus_num, addr;
4316 const char *p;
4318 if (!used_usb_ports)
4319 return -1;
4321 p = strchr(devname, '.');
4322 if (!p)
4323 return -1;
4324 bus_num = strtoul(devname, NULL, 0);
4325 addr = strtoul(p + 1, NULL, 0);
4326 if (bus_num != 0)
4327 return -1;
4329 lastp = &used_usb_ports;
4330 port = used_usb_ports;
4331 while (port && port->dev->addr != addr) {
4332 lastp = &port->next;
4333 port = port->next;
4336 if (!port)
4337 return -1;
4339 dev = port->dev;
4340 *lastp = port->next;
4341 usb_attach(port, NULL);
4342 dev->handle_destroy(dev);
4343 port->next = free_usb_ports;
4344 free_usb_ports = port;
4345 return 0;
4348 void do_usb_add(const char *devname)
4350 int ret;
4351 ret = usb_device_add(devname);
4352 if (ret < 0)
4353 term_printf("Could not add USB device '%s'\n", devname);
4356 void do_usb_del(const char *devname)
4358 int ret;
4359 ret = usb_device_del(devname);
4360 if (ret < 0)
4361 term_printf("Could not remove USB device '%s'\n", devname);
4364 void usb_info(void)
4366 USBDevice *dev;
4367 USBPort *port;
4368 const char *speed_str;
4370 if (!usb_enabled) {
4371 term_printf("USB support not enabled\n");
4372 return;
4375 for (port = used_usb_ports; port; port = port->next) {
4376 dev = port->dev;
4377 if (!dev)
4378 continue;
4379 switch(dev->speed) {
4380 case USB_SPEED_LOW:
4381 speed_str = "1.5";
4382 break;
4383 case USB_SPEED_FULL:
4384 speed_str = "12";
4385 break;
4386 case USB_SPEED_HIGH:
4387 speed_str = "480";
4388 break;
4389 default:
4390 speed_str = "?";
4391 break;
4393 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4394 0, dev->addr, speed_str, dev->devname);
4398 static int create_pidfile(const char *filename)
4400 int fd;
4401 char buffer[128];
4402 int len;
4404 fd = open(filename, O_RDWR | O_CREAT, 0600);
4405 if (fd == -1)
4406 return -1;
4408 /* XXX: No locking for Win32 implemented */
4409 #ifndef _WIN32
4410 if (lockf(fd, F_TLOCK, 0) == -1)
4411 return -1;
4412 #endif
4414 len = snprintf(buffer, sizeof(buffer), "%ld\n", (long)getpid());
4415 if (write(fd, buffer, len) != len)
4416 return -1;
4418 return 0;
4421 /***********************************************************/
4422 /* dumb display */
4424 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4428 static void dumb_resize(DisplayState *ds, int w, int h)
4432 static void dumb_refresh(DisplayState *ds)
4434 vga_hw_update();
4437 void dumb_display_init(DisplayState *ds)
4439 ds->data = NULL;
4440 ds->linesize = 0;
4441 ds->depth = 0;
4442 ds->dpy_update = dumb_update;
4443 ds->dpy_resize = dumb_resize;
4444 ds->dpy_refresh = dumb_refresh;
4447 /***********************************************************/
4448 /* I/O handling */
4450 #define MAX_IO_HANDLERS 64
4452 typedef struct IOHandlerRecord {
4453 int fd;
4454 IOCanRWHandler *fd_read_poll;
4455 IOHandler *fd_read;
4456 IOHandler *fd_write;
4457 int deleted;
4458 void *opaque;
4459 /* temporary data */
4460 struct pollfd *ufd;
4461 struct IOHandlerRecord *next;
4462 } IOHandlerRecord;
4464 static IOHandlerRecord *first_io_handler;
4466 /* XXX: fd_read_poll should be suppressed, but an API change is
4467 necessary in the character devices to suppress fd_can_read(). */
4468 int qemu_set_fd_handler2(int fd,
4469 IOCanRWHandler *fd_read_poll,
4470 IOHandler *fd_read,
4471 IOHandler *fd_write,
4472 void *opaque)
4474 IOHandlerRecord **pioh, *ioh;
4476 if (!fd_read && !fd_write) {
4477 pioh = &first_io_handler;
4478 for(;;) {
4479 ioh = *pioh;
4480 if (ioh == NULL)
4481 break;
4482 if (ioh->fd == fd) {
4483 ioh->deleted = 1;
4484 break;
4486 pioh = &ioh->next;
4488 } else {
4489 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4490 if (ioh->fd == fd)
4491 goto found;
4493 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4494 if (!ioh)
4495 return -1;
4496 ioh->next = first_io_handler;
4497 first_io_handler = ioh;
4498 found:
4499 ioh->fd = fd;
4500 ioh->fd_read_poll = fd_read_poll;
4501 ioh->fd_read = fd_read;
4502 ioh->fd_write = fd_write;
4503 ioh->opaque = opaque;
4504 ioh->deleted = 0;
4506 return 0;
4509 int qemu_set_fd_handler(int fd,
4510 IOHandler *fd_read,
4511 IOHandler *fd_write,
4512 void *opaque)
4514 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4517 /***********************************************************/
4518 /* Polling handling */
4520 typedef struct PollingEntry {
4521 PollingFunc *func;
4522 void *opaque;
4523 struct PollingEntry *next;
4524 } PollingEntry;
4526 static PollingEntry *first_polling_entry;
4528 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4530 PollingEntry **ppe, *pe;
4531 pe = qemu_mallocz(sizeof(PollingEntry));
4532 if (!pe)
4533 return -1;
4534 pe->func = func;
4535 pe->opaque = opaque;
4536 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4537 *ppe = pe;
4538 return 0;
4541 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4543 PollingEntry **ppe, *pe;
4544 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4545 pe = *ppe;
4546 if (pe->func == func && pe->opaque == opaque) {
4547 *ppe = pe->next;
4548 qemu_free(pe);
4549 break;
4554 #ifdef _WIN32
4555 /***********************************************************/
4556 /* Wait objects support */
4557 typedef struct WaitObjects {
4558 int num;
4559 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4560 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4561 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4562 } WaitObjects;
4564 static WaitObjects wait_objects = {0};
4566 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4568 WaitObjects *w = &wait_objects;
4570 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4571 return -1;
4572 w->events[w->num] = handle;
4573 w->func[w->num] = func;
4574 w->opaque[w->num] = opaque;
4575 w->num++;
4576 return 0;
4579 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4581 int i, found;
4582 WaitObjects *w = &wait_objects;
4584 found = 0;
4585 for (i = 0; i < w->num; i++) {
4586 if (w->events[i] == handle)
4587 found = 1;
4588 if (found) {
4589 w->events[i] = w->events[i + 1];
4590 w->func[i] = w->func[i + 1];
4591 w->opaque[i] = w->opaque[i + 1];
4594 if (found)
4595 w->num--;
4597 #endif
4599 /***********************************************************/
4600 /* savevm/loadvm support */
4602 #define IO_BUF_SIZE 32768
4604 struct QEMUFile {
4605 FILE *outfile;
4606 BlockDriverState *bs;
4607 int is_file;
4608 int is_writable;
4609 int64_t base_offset;
4610 int64_t buf_offset; /* start of buffer when writing, end of buffer
4611 when reading */
4612 int buf_index;
4613 int buf_size; /* 0 when writing */
4614 uint8_t buf[IO_BUF_SIZE];
4617 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4619 QEMUFile *f;
4621 f = qemu_mallocz(sizeof(QEMUFile));
4622 if (!f)
4623 return NULL;
4624 if (!strcmp(mode, "wb")) {
4625 f->is_writable = 1;
4626 } else if (!strcmp(mode, "rb")) {
4627 f->is_writable = 0;
4628 } else {
4629 goto fail;
4631 f->outfile = fopen(filename, mode);
4632 if (!f->outfile)
4633 goto fail;
4634 f->is_file = 1;
4635 return f;
4636 fail:
4637 if (f->outfile)
4638 fclose(f->outfile);
4639 qemu_free(f);
4640 return NULL;
4643 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4645 QEMUFile *f;
4647 f = qemu_mallocz(sizeof(QEMUFile));
4648 if (!f)
4649 return NULL;
4650 f->is_file = 0;
4651 f->bs = bs;
4652 f->is_writable = is_writable;
4653 f->base_offset = offset;
4654 return f;
4657 void qemu_fflush(QEMUFile *f)
4659 if (!f->is_writable)
4660 return;
4661 if (f->buf_index > 0) {
4662 if (f->is_file) {
4663 fseek(f->outfile, f->buf_offset, SEEK_SET);
4664 fwrite(f->buf, 1, f->buf_index, f->outfile);
4665 } else {
4666 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4667 f->buf, f->buf_index);
4669 f->buf_offset += f->buf_index;
4670 f->buf_index = 0;
4674 static void qemu_fill_buffer(QEMUFile *f)
4676 int len;
4678 if (f->is_writable)
4679 return;
4680 if (f->is_file) {
4681 fseek(f->outfile, f->buf_offset, SEEK_SET);
4682 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4683 if (len < 0)
4684 len = 0;
4685 } else {
4686 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4687 f->buf, IO_BUF_SIZE);
4688 if (len < 0)
4689 len = 0;
4691 f->buf_index = 0;
4692 f->buf_size = len;
4693 f->buf_offset += len;
4696 void qemu_fclose(QEMUFile *f)
4698 if (f->is_writable)
4699 qemu_fflush(f);
4700 if (f->is_file) {
4701 fclose(f->outfile);
4703 qemu_free(f);
4706 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4708 int l;
4709 while (size > 0) {
4710 l = IO_BUF_SIZE - f->buf_index;
4711 if (l > size)
4712 l = size;
4713 memcpy(f->buf + f->buf_index, buf, l);
4714 f->buf_index += l;
4715 buf += l;
4716 size -= l;
4717 if (f->buf_index >= IO_BUF_SIZE)
4718 qemu_fflush(f);
4722 void qemu_put_byte(QEMUFile *f, int v)
4724 f->buf[f->buf_index++] = v;
4725 if (f->buf_index >= IO_BUF_SIZE)
4726 qemu_fflush(f);
4729 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4731 int size, l;
4733 size = size1;
4734 while (size > 0) {
4735 l = f->buf_size - f->buf_index;
4736 if (l == 0) {
4737 qemu_fill_buffer(f);
4738 l = f->buf_size - f->buf_index;
4739 if (l == 0)
4740 break;
4742 if (l > size)
4743 l = size;
4744 memcpy(buf, f->buf + f->buf_index, l);
4745 f->buf_index += l;
4746 buf += l;
4747 size -= l;
4749 return size1 - size;
4752 int qemu_get_byte(QEMUFile *f)
4754 if (f->buf_index >= f->buf_size) {
4755 qemu_fill_buffer(f);
4756 if (f->buf_index >= f->buf_size)
4757 return 0;
4759 return f->buf[f->buf_index++];
4762 int64_t qemu_ftell(QEMUFile *f)
4764 return f->buf_offset - f->buf_size + f->buf_index;
4767 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4769 if (whence == SEEK_SET) {
4770 /* nothing to do */
4771 } else if (whence == SEEK_CUR) {
4772 pos += qemu_ftell(f);
4773 } else {
4774 /* SEEK_END not supported */
4775 return -1;
4777 if (f->is_writable) {
4778 qemu_fflush(f);
4779 f->buf_offset = pos;
4780 } else {
4781 f->buf_offset = pos;
4782 f->buf_index = 0;
4783 f->buf_size = 0;
4785 return pos;
4788 void qemu_put_be16(QEMUFile *f, unsigned int v)
4790 qemu_put_byte(f, v >> 8);
4791 qemu_put_byte(f, v);
4794 void qemu_put_be32(QEMUFile *f, unsigned int v)
4796 qemu_put_byte(f, v >> 24);
4797 qemu_put_byte(f, v >> 16);
4798 qemu_put_byte(f, v >> 8);
4799 qemu_put_byte(f, v);
4802 void qemu_put_be64(QEMUFile *f, uint64_t v)
4804 qemu_put_be32(f, v >> 32);
4805 qemu_put_be32(f, v);
4808 unsigned int qemu_get_be16(QEMUFile *f)
4810 unsigned int v;
4811 v = qemu_get_byte(f) << 8;
4812 v |= qemu_get_byte(f);
4813 return v;
4816 unsigned int qemu_get_be32(QEMUFile *f)
4818 unsigned int v;
4819 v = qemu_get_byte(f) << 24;
4820 v |= qemu_get_byte(f) << 16;
4821 v |= qemu_get_byte(f) << 8;
4822 v |= qemu_get_byte(f);
4823 return v;
4826 uint64_t qemu_get_be64(QEMUFile *f)
4828 uint64_t v;
4829 v = (uint64_t)qemu_get_be32(f) << 32;
4830 v |= qemu_get_be32(f);
4831 return v;
4834 typedef struct SaveStateEntry {
4835 char idstr[256];
4836 int instance_id;
4837 int version_id;
4838 SaveStateHandler *save_state;
4839 LoadStateHandler *load_state;
4840 void *opaque;
4841 struct SaveStateEntry *next;
4842 } SaveStateEntry;
4844 static SaveStateEntry *first_se;
4846 int register_savevm(const char *idstr,
4847 int instance_id,
4848 int version_id,
4849 SaveStateHandler *save_state,
4850 LoadStateHandler *load_state,
4851 void *opaque)
4853 SaveStateEntry *se, **pse;
4855 se = qemu_malloc(sizeof(SaveStateEntry));
4856 if (!se)
4857 return -1;
4858 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4859 se->instance_id = instance_id;
4860 se->version_id = version_id;
4861 se->save_state = save_state;
4862 se->load_state = load_state;
4863 se->opaque = opaque;
4864 se->next = NULL;
4866 /* add at the end of list */
4867 pse = &first_se;
4868 while (*pse != NULL)
4869 pse = &(*pse)->next;
4870 *pse = se;
4871 return 0;
4874 #define QEMU_VM_FILE_MAGIC 0x5145564d
4875 #define QEMU_VM_FILE_VERSION 0x00000002
4877 int qemu_savevm_state(QEMUFile *f)
4879 SaveStateEntry *se;
4880 int len, ret;
4881 int64_t cur_pos, len_pos, total_len_pos;
4883 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4884 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4885 total_len_pos = qemu_ftell(f);
4886 qemu_put_be64(f, 0); /* total size */
4888 for(se = first_se; se != NULL; se = se->next) {
4889 /* ID string */
4890 len = strlen(se->idstr);
4891 qemu_put_byte(f, len);
4892 qemu_put_buffer(f, se->idstr, len);
4894 qemu_put_be32(f, se->instance_id);
4895 qemu_put_be32(f, se->version_id);
4897 /* record size: filled later */
4898 len_pos = qemu_ftell(f);
4899 qemu_put_be32(f, 0);
4901 se->save_state(f, se->opaque);
4903 /* fill record size */
4904 cur_pos = qemu_ftell(f);
4905 len = cur_pos - len_pos - 4;
4906 qemu_fseek(f, len_pos, SEEK_SET);
4907 qemu_put_be32(f, len);
4908 qemu_fseek(f, cur_pos, SEEK_SET);
4910 cur_pos = qemu_ftell(f);
4911 qemu_fseek(f, total_len_pos, SEEK_SET);
4912 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4913 qemu_fseek(f, cur_pos, SEEK_SET);
4915 ret = 0;
4916 return ret;
4919 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4921 SaveStateEntry *se;
4923 for(se = first_se; se != NULL; se = se->next) {
4924 if (!strcmp(se->idstr, idstr) &&
4925 instance_id == se->instance_id)
4926 return se;
4928 return NULL;
4931 int qemu_loadvm_state(QEMUFile *f)
4933 SaveStateEntry *se;
4934 int len, ret, instance_id, record_len, version_id;
4935 int64_t total_len, end_pos, cur_pos;
4936 unsigned int v;
4937 char idstr[256];
4939 v = qemu_get_be32(f);
4940 if (v != QEMU_VM_FILE_MAGIC)
4941 goto fail;
4942 v = qemu_get_be32(f);
4943 if (v != QEMU_VM_FILE_VERSION) {
4944 fail:
4945 ret = -1;
4946 goto the_end;
4948 total_len = qemu_get_be64(f);
4949 end_pos = total_len + qemu_ftell(f);
4950 for(;;) {
4951 if (qemu_ftell(f) >= end_pos)
4952 break;
4953 len = qemu_get_byte(f);
4954 qemu_get_buffer(f, idstr, len);
4955 idstr[len] = '\0';
4956 instance_id = qemu_get_be32(f);
4957 version_id = qemu_get_be32(f);
4958 record_len = qemu_get_be32(f);
4959 #if 0
4960 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4961 idstr, instance_id, version_id, record_len);
4962 #endif
4963 cur_pos = qemu_ftell(f);
4964 se = find_se(idstr, instance_id);
4965 if (!se) {
4966 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4967 instance_id, idstr);
4968 } else {
4969 ret = se->load_state(f, se->opaque, version_id);
4970 if (ret < 0) {
4971 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4972 instance_id, idstr);
4975 /* always seek to exact end of record */
4976 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4978 ret = 0;
4979 the_end:
4980 return ret;
4983 /* device can contain snapshots */
4984 static int bdrv_can_snapshot(BlockDriverState *bs)
4986 return (bs &&
4987 !bdrv_is_removable(bs) &&
4988 !bdrv_is_read_only(bs));
4991 /* device must be snapshots in order to have a reliable snapshot */
4992 static int bdrv_has_snapshot(BlockDriverState *bs)
4994 return (bs &&
4995 !bdrv_is_removable(bs) &&
4996 !bdrv_is_read_only(bs));
4999 static BlockDriverState *get_bs_snapshots(void)
5001 BlockDriverState *bs;
5002 int i;
5004 if (bs_snapshots)
5005 return bs_snapshots;
5006 for(i = 0; i <= MAX_DISKS; i++) {
5007 bs = bs_table[i];
5008 if (bdrv_can_snapshot(bs))
5009 goto ok;
5011 return NULL;
5013 bs_snapshots = bs;
5014 return bs;
5017 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5018 const char *name)
5020 QEMUSnapshotInfo *sn_tab, *sn;
5021 int nb_sns, i, ret;
5023 ret = -ENOENT;
5024 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5025 if (nb_sns < 0)
5026 return ret;
5027 for(i = 0; i < nb_sns; i++) {
5028 sn = &sn_tab[i];
5029 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5030 *sn_info = *sn;
5031 ret = 0;
5032 break;
5035 qemu_free(sn_tab);
5036 return ret;
5039 void do_savevm(const char *name)
5041 BlockDriverState *bs, *bs1;
5042 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5043 int must_delete, ret, i;
5044 BlockDriverInfo bdi1, *bdi = &bdi1;
5045 QEMUFile *f;
5046 int saved_vm_running;
5047 #ifdef _WIN32
5048 struct _timeb tb;
5049 #else
5050 struct timeval tv;
5051 #endif
5053 bs = get_bs_snapshots();
5054 if (!bs) {
5055 term_printf("No block device can accept snapshots\n");
5056 return;
5059 /* ??? Should this occur after vm_stop? */
5060 qemu_aio_flush();
5062 saved_vm_running = vm_running;
5063 vm_stop(0);
5065 must_delete = 0;
5066 if (name) {
5067 ret = bdrv_snapshot_find(bs, old_sn, name);
5068 if (ret >= 0) {
5069 must_delete = 1;
5072 memset(sn, 0, sizeof(*sn));
5073 if (must_delete) {
5074 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5075 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5076 } else {
5077 if (name)
5078 pstrcpy(sn->name, sizeof(sn->name), name);
5081 /* fill auxiliary fields */
5082 #ifdef _WIN32
5083 _ftime(&tb);
5084 sn->date_sec = tb.time;
5085 sn->date_nsec = tb.millitm * 1000000;
5086 #else
5087 gettimeofday(&tv, NULL);
5088 sn->date_sec = tv.tv_sec;
5089 sn->date_nsec = tv.tv_usec * 1000;
5090 #endif
5091 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5093 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5094 term_printf("Device %s does not support VM state snapshots\n",
5095 bdrv_get_device_name(bs));
5096 goto the_end;
5099 /* save the VM state */
5100 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5101 if (!f) {
5102 term_printf("Could not open VM state file\n");
5103 goto the_end;
5105 ret = qemu_savevm_state(f);
5106 sn->vm_state_size = qemu_ftell(f);
5107 qemu_fclose(f);
5108 if (ret < 0) {
5109 term_printf("Error %d while writing VM\n", ret);
5110 goto the_end;
5113 /* create the snapshots */
5115 for(i = 0; i < MAX_DISKS; i++) {
5116 bs1 = bs_table[i];
5117 if (bdrv_has_snapshot(bs1)) {
5118 if (must_delete) {
5119 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5120 if (ret < 0) {
5121 term_printf("Error while deleting snapshot on '%s'\n",
5122 bdrv_get_device_name(bs1));
5125 ret = bdrv_snapshot_create(bs1, sn);
5126 if (ret < 0) {
5127 term_printf("Error while creating snapshot on '%s'\n",
5128 bdrv_get_device_name(bs1));
5133 the_end:
5134 if (saved_vm_running)
5135 vm_start();
5138 void do_loadvm(const char *name)
5140 BlockDriverState *bs, *bs1;
5141 BlockDriverInfo bdi1, *bdi = &bdi1;
5142 QEMUFile *f;
5143 int i, ret;
5144 int saved_vm_running;
5146 bs = get_bs_snapshots();
5147 if (!bs) {
5148 term_printf("No block device supports snapshots\n");
5149 return;
5152 /* Flush all IO requests so they don't interfere with the new state. */
5153 qemu_aio_flush();
5155 saved_vm_running = vm_running;
5156 vm_stop(0);
5158 for(i = 0; i <= MAX_DISKS; i++) {
5159 bs1 = bs_table[i];
5160 if (bdrv_has_snapshot(bs1)) {
5161 ret = bdrv_snapshot_goto(bs1, name);
5162 if (ret < 0) {
5163 if (bs != bs1)
5164 term_printf("Warning: ");
5165 switch(ret) {
5166 case -ENOTSUP:
5167 term_printf("Snapshots not supported on device '%s'\n",
5168 bdrv_get_device_name(bs1));
5169 break;
5170 case -ENOENT:
5171 term_printf("Could not find snapshot '%s' on device '%s'\n",
5172 name, bdrv_get_device_name(bs1));
5173 break;
5174 default:
5175 term_printf("Error %d while activating snapshot on '%s'\n",
5176 ret, bdrv_get_device_name(bs1));
5177 break;
5179 /* fatal on snapshot block device */
5180 if (bs == bs1)
5181 goto the_end;
5186 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5187 term_printf("Device %s does not support VM state snapshots\n",
5188 bdrv_get_device_name(bs));
5189 return;
5192 /* restore the VM state */
5193 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5194 if (!f) {
5195 term_printf("Could not open VM state file\n");
5196 goto the_end;
5198 ret = qemu_loadvm_state(f);
5199 qemu_fclose(f);
5200 if (ret < 0) {
5201 term_printf("Error %d while loading VM state\n", ret);
5203 the_end:
5204 if (saved_vm_running)
5205 vm_start();
5208 void do_delvm(const char *name)
5210 BlockDriverState *bs, *bs1;
5211 int i, ret;
5213 bs = get_bs_snapshots();
5214 if (!bs) {
5215 term_printf("No block device supports snapshots\n");
5216 return;
5219 for(i = 0; i <= MAX_DISKS; i++) {
5220 bs1 = bs_table[i];
5221 if (bdrv_has_snapshot(bs1)) {
5222 ret = bdrv_snapshot_delete(bs1, name);
5223 if (ret < 0) {
5224 if (ret == -ENOTSUP)
5225 term_printf("Snapshots not supported on device '%s'\n",
5226 bdrv_get_device_name(bs1));
5227 else
5228 term_printf("Error %d while deleting snapshot on '%s'\n",
5229 ret, bdrv_get_device_name(bs1));
5235 void do_info_snapshots(void)
5237 BlockDriverState *bs, *bs1;
5238 QEMUSnapshotInfo *sn_tab, *sn;
5239 int nb_sns, i;
5240 char buf[256];
5242 bs = get_bs_snapshots();
5243 if (!bs) {
5244 term_printf("No available block device supports snapshots\n");
5245 return;
5247 term_printf("Snapshot devices:");
5248 for(i = 0; i <= MAX_DISKS; i++) {
5249 bs1 = bs_table[i];
5250 if (bdrv_has_snapshot(bs1)) {
5251 if (bs == bs1)
5252 term_printf(" %s", bdrv_get_device_name(bs1));
5255 term_printf("\n");
5257 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5258 if (nb_sns < 0) {
5259 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5260 return;
5262 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5263 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5264 for(i = 0; i < nb_sns; i++) {
5265 sn = &sn_tab[i];
5266 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5268 qemu_free(sn_tab);
5271 /***********************************************************/
5272 /* cpu save/restore */
5274 #if defined(TARGET_I386)
5276 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5278 qemu_put_be32(f, dt->selector);
5279 qemu_put_betl(f, dt->base);
5280 qemu_put_be32(f, dt->limit);
5281 qemu_put_be32(f, dt->flags);
5284 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5286 dt->selector = qemu_get_be32(f);
5287 dt->base = qemu_get_betl(f);
5288 dt->limit = qemu_get_be32(f);
5289 dt->flags = qemu_get_be32(f);
5292 void cpu_save(QEMUFile *f, void *opaque)
5294 CPUState *env = opaque;
5295 uint16_t fptag, fpus, fpuc, fpregs_format;
5296 uint32_t hflags;
5297 int i;
5299 for(i = 0; i < CPU_NB_REGS; i++)
5300 qemu_put_betls(f, &env->regs[i]);
5301 qemu_put_betls(f, &env->eip);
5302 qemu_put_betls(f, &env->eflags);
5303 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5304 qemu_put_be32s(f, &hflags);
5306 /* FPU */
5307 fpuc = env->fpuc;
5308 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5309 fptag = 0;
5310 for(i = 0; i < 8; i++) {
5311 fptag |= ((!env->fptags[i]) << i);
5314 qemu_put_be16s(f, &fpuc);
5315 qemu_put_be16s(f, &fpus);
5316 qemu_put_be16s(f, &fptag);
5318 #ifdef USE_X86LDOUBLE
5319 fpregs_format = 0;
5320 #else
5321 fpregs_format = 1;
5322 #endif
5323 qemu_put_be16s(f, &fpregs_format);
5325 for(i = 0; i < 8; i++) {
5326 #ifdef USE_X86LDOUBLE
5328 uint64_t mant;
5329 uint16_t exp;
5330 /* we save the real CPU data (in case of MMX usage only 'mant'
5331 contains the MMX register */
5332 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5333 qemu_put_be64(f, mant);
5334 qemu_put_be16(f, exp);
5336 #else
5337 /* if we use doubles for float emulation, we save the doubles to
5338 avoid losing information in case of MMX usage. It can give
5339 problems if the image is restored on a CPU where long
5340 doubles are used instead. */
5341 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5342 #endif
5345 for(i = 0; i < 6; i++)
5346 cpu_put_seg(f, &env->segs[i]);
5347 cpu_put_seg(f, &env->ldt);
5348 cpu_put_seg(f, &env->tr);
5349 cpu_put_seg(f, &env->gdt);
5350 cpu_put_seg(f, &env->idt);
5352 qemu_put_be32s(f, &env->sysenter_cs);
5353 qemu_put_be32s(f, &env->sysenter_esp);
5354 qemu_put_be32s(f, &env->sysenter_eip);
5356 qemu_put_betls(f, &env->cr[0]);
5357 qemu_put_betls(f, &env->cr[2]);
5358 qemu_put_betls(f, &env->cr[3]);
5359 qemu_put_betls(f, &env->cr[4]);
5361 for(i = 0; i < 8; i++)
5362 qemu_put_betls(f, &env->dr[i]);
5364 /* MMU */
5365 qemu_put_be32s(f, &env->a20_mask);
5367 /* XMM */
5368 qemu_put_be32s(f, &env->mxcsr);
5369 for(i = 0; i < CPU_NB_REGS; i++) {
5370 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5371 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5374 #ifdef TARGET_X86_64
5375 qemu_put_be64s(f, &env->efer);
5376 qemu_put_be64s(f, &env->star);
5377 qemu_put_be64s(f, &env->lstar);
5378 qemu_put_be64s(f, &env->cstar);
5379 qemu_put_be64s(f, &env->fmask);
5380 qemu_put_be64s(f, &env->kernelgsbase);
5381 #endif
5382 qemu_put_be32s(f, &env->smbase);
5385 #ifdef USE_X86LDOUBLE
5386 /* XXX: add that in a FPU generic layer */
5387 union x86_longdouble {
5388 uint64_t mant;
5389 uint16_t exp;
5392 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5393 #define EXPBIAS1 1023
5394 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5395 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5397 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5399 int e;
5400 /* mantissa */
5401 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5402 /* exponent + sign */
5403 e = EXPD1(temp) - EXPBIAS1 + 16383;
5404 e |= SIGND1(temp) >> 16;
5405 p->exp = e;
5407 #endif
5409 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5411 CPUState *env = opaque;
5412 int i, guess_mmx;
5413 uint32_t hflags;
5414 uint16_t fpus, fpuc, fptag, fpregs_format;
5416 if (version_id != 3 && version_id != 4)
5417 return -EINVAL;
5418 for(i = 0; i < CPU_NB_REGS; i++)
5419 qemu_get_betls(f, &env->regs[i]);
5420 qemu_get_betls(f, &env->eip);
5421 qemu_get_betls(f, &env->eflags);
5422 qemu_get_be32s(f, &hflags);
5424 qemu_get_be16s(f, &fpuc);
5425 qemu_get_be16s(f, &fpus);
5426 qemu_get_be16s(f, &fptag);
5427 qemu_get_be16s(f, &fpregs_format);
5429 /* NOTE: we cannot always restore the FPU state if the image come
5430 from a host with a different 'USE_X86LDOUBLE' define. We guess
5431 if we are in an MMX state to restore correctly in that case. */
5432 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5433 for(i = 0; i < 8; i++) {
5434 uint64_t mant;
5435 uint16_t exp;
5437 switch(fpregs_format) {
5438 case 0:
5439 mant = qemu_get_be64(f);
5440 exp = qemu_get_be16(f);
5441 #ifdef USE_X86LDOUBLE
5442 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5443 #else
5444 /* difficult case */
5445 if (guess_mmx)
5446 env->fpregs[i].mmx.MMX_Q(0) = mant;
5447 else
5448 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5449 #endif
5450 break;
5451 case 1:
5452 mant = qemu_get_be64(f);
5453 #ifdef USE_X86LDOUBLE
5455 union x86_longdouble *p;
5456 /* difficult case */
5457 p = (void *)&env->fpregs[i];
5458 if (guess_mmx) {
5459 p->mant = mant;
5460 p->exp = 0xffff;
5461 } else {
5462 fp64_to_fp80(p, mant);
5465 #else
5466 env->fpregs[i].mmx.MMX_Q(0) = mant;
5467 #endif
5468 break;
5469 default:
5470 return -EINVAL;
5474 env->fpuc = fpuc;
5475 /* XXX: restore FPU round state */
5476 env->fpstt = (fpus >> 11) & 7;
5477 env->fpus = fpus & ~0x3800;
5478 fptag ^= 0xff;
5479 for(i = 0; i < 8; i++) {
5480 env->fptags[i] = (fptag >> i) & 1;
5483 for(i = 0; i < 6; i++)
5484 cpu_get_seg(f, &env->segs[i]);
5485 cpu_get_seg(f, &env->ldt);
5486 cpu_get_seg(f, &env->tr);
5487 cpu_get_seg(f, &env->gdt);
5488 cpu_get_seg(f, &env->idt);
5490 qemu_get_be32s(f, &env->sysenter_cs);
5491 qemu_get_be32s(f, &env->sysenter_esp);
5492 qemu_get_be32s(f, &env->sysenter_eip);
5494 qemu_get_betls(f, &env->cr[0]);
5495 qemu_get_betls(f, &env->cr[2]);
5496 qemu_get_betls(f, &env->cr[3]);
5497 qemu_get_betls(f, &env->cr[4]);
5499 for(i = 0; i < 8; i++)
5500 qemu_get_betls(f, &env->dr[i]);
5502 /* MMU */
5503 qemu_get_be32s(f, &env->a20_mask);
5505 qemu_get_be32s(f, &env->mxcsr);
5506 for(i = 0; i < CPU_NB_REGS; i++) {
5507 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5508 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5511 #ifdef TARGET_X86_64
5512 qemu_get_be64s(f, &env->efer);
5513 qemu_get_be64s(f, &env->star);
5514 qemu_get_be64s(f, &env->lstar);
5515 qemu_get_be64s(f, &env->cstar);
5516 qemu_get_be64s(f, &env->fmask);
5517 qemu_get_be64s(f, &env->kernelgsbase);
5518 #endif
5519 if (version_id >= 4)
5520 qemu_get_be32s(f, &env->smbase);
5522 /* XXX: compute hflags from scratch, except for CPL and IIF */
5523 env->hflags = hflags;
5524 tlb_flush(env, 1);
5525 return 0;
5528 #elif defined(TARGET_PPC)
5529 void cpu_save(QEMUFile *f, void *opaque)
5533 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5535 return 0;
5538 #elif defined(TARGET_MIPS)
5539 void cpu_save(QEMUFile *f, void *opaque)
5543 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5545 return 0;
5548 #elif defined(TARGET_SPARC)
5549 void cpu_save(QEMUFile *f, void *opaque)
5551 CPUState *env = opaque;
5552 int i;
5553 uint32_t tmp;
5555 for(i = 0; i < 8; i++)
5556 qemu_put_betls(f, &env->gregs[i]);
5557 for(i = 0; i < NWINDOWS * 16; i++)
5558 qemu_put_betls(f, &env->regbase[i]);
5560 /* FPU */
5561 for(i = 0; i < TARGET_FPREGS; i++) {
5562 union {
5563 float32 f;
5564 uint32_t i;
5565 } u;
5566 u.f = env->fpr[i];
5567 qemu_put_be32(f, u.i);
5570 qemu_put_betls(f, &env->pc);
5571 qemu_put_betls(f, &env->npc);
5572 qemu_put_betls(f, &env->y);
5573 tmp = GET_PSR(env);
5574 qemu_put_be32(f, tmp);
5575 qemu_put_betls(f, &env->fsr);
5576 qemu_put_betls(f, &env->tbr);
5577 #ifndef TARGET_SPARC64
5578 qemu_put_be32s(f, &env->wim);
5579 /* MMU */
5580 for(i = 0; i < 16; i++)
5581 qemu_put_be32s(f, &env->mmuregs[i]);
5582 #endif
5585 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5587 CPUState *env = opaque;
5588 int i;
5589 uint32_t tmp;
5591 for(i = 0; i < 8; i++)
5592 qemu_get_betls(f, &env->gregs[i]);
5593 for(i = 0; i < NWINDOWS * 16; i++)
5594 qemu_get_betls(f, &env->regbase[i]);
5596 /* FPU */
5597 for(i = 0; i < TARGET_FPREGS; i++) {
5598 union {
5599 float32 f;
5600 uint32_t i;
5601 } u;
5602 u.i = qemu_get_be32(f);
5603 env->fpr[i] = u.f;
5606 qemu_get_betls(f, &env->pc);
5607 qemu_get_betls(f, &env->npc);
5608 qemu_get_betls(f, &env->y);
5609 tmp = qemu_get_be32(f);
5610 env->cwp = 0; /* needed to ensure that the wrapping registers are
5611 correctly updated */
5612 PUT_PSR(env, tmp);
5613 qemu_get_betls(f, &env->fsr);
5614 qemu_get_betls(f, &env->tbr);
5615 #ifndef TARGET_SPARC64
5616 qemu_get_be32s(f, &env->wim);
5617 /* MMU */
5618 for(i = 0; i < 16; i++)
5619 qemu_get_be32s(f, &env->mmuregs[i]);
5620 #endif
5621 tlb_flush(env, 1);
5622 return 0;
5625 #elif defined(TARGET_ARM)
5627 /* ??? Need to implement these. */
5628 void cpu_save(QEMUFile *f, void *opaque)
5632 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5634 return 0;
5637 #else
5639 #warning No CPU save/restore functions
5641 #endif
5643 /***********************************************************/
5644 /* ram save/restore */
5646 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5648 int v;
5650 v = qemu_get_byte(f);
5651 switch(v) {
5652 case 0:
5653 if (qemu_get_buffer(f, buf, len) != len)
5654 return -EIO;
5655 break;
5656 case 1:
5657 v = qemu_get_byte(f);
5658 memset(buf, v, len);
5659 break;
5660 default:
5661 return -EINVAL;
5663 return 0;
5666 static int ram_load_v1(QEMUFile *f, void *opaque)
5668 int i, ret;
5670 if (qemu_get_be32(f) != phys_ram_size)
5671 return -EINVAL;
5672 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5673 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5674 if (ret)
5675 return ret;
5677 return 0;
5680 #define BDRV_HASH_BLOCK_SIZE 1024
5681 #define IOBUF_SIZE 4096
5682 #define RAM_CBLOCK_MAGIC 0xfabe
5684 typedef struct RamCompressState {
5685 z_stream zstream;
5686 QEMUFile *f;
5687 uint8_t buf[IOBUF_SIZE];
5688 } RamCompressState;
5690 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5692 int ret;
5693 memset(s, 0, sizeof(*s));
5694 s->f = f;
5695 ret = deflateInit2(&s->zstream, 1,
5696 Z_DEFLATED, 15,
5697 9, Z_DEFAULT_STRATEGY);
5698 if (ret != Z_OK)
5699 return -1;
5700 s->zstream.avail_out = IOBUF_SIZE;
5701 s->zstream.next_out = s->buf;
5702 return 0;
5705 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5707 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5708 qemu_put_be16(s->f, len);
5709 qemu_put_buffer(s->f, buf, len);
5712 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5714 int ret;
5716 s->zstream.avail_in = len;
5717 s->zstream.next_in = (uint8_t *)buf;
5718 while (s->zstream.avail_in > 0) {
5719 ret = deflate(&s->zstream, Z_NO_FLUSH);
5720 if (ret != Z_OK)
5721 return -1;
5722 if (s->zstream.avail_out == 0) {
5723 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5724 s->zstream.avail_out = IOBUF_SIZE;
5725 s->zstream.next_out = s->buf;
5728 return 0;
5731 static void ram_compress_close(RamCompressState *s)
5733 int len, ret;
5735 /* compress last bytes */
5736 for(;;) {
5737 ret = deflate(&s->zstream, Z_FINISH);
5738 if (ret == Z_OK || ret == Z_STREAM_END) {
5739 len = IOBUF_SIZE - s->zstream.avail_out;
5740 if (len > 0) {
5741 ram_put_cblock(s, s->buf, len);
5743 s->zstream.avail_out = IOBUF_SIZE;
5744 s->zstream.next_out = s->buf;
5745 if (ret == Z_STREAM_END)
5746 break;
5747 } else {
5748 goto fail;
5751 fail:
5752 deflateEnd(&s->zstream);
5755 typedef struct RamDecompressState {
5756 z_stream zstream;
5757 QEMUFile *f;
5758 uint8_t buf[IOBUF_SIZE];
5759 } RamDecompressState;
5761 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5763 int ret;
5764 memset(s, 0, sizeof(*s));
5765 s->f = f;
5766 ret = inflateInit(&s->zstream);
5767 if (ret != Z_OK)
5768 return -1;
5769 return 0;
5772 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5774 int ret, clen;
5776 s->zstream.avail_out = len;
5777 s->zstream.next_out = buf;
5778 while (s->zstream.avail_out > 0) {
5779 if (s->zstream.avail_in == 0) {
5780 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5781 return -1;
5782 clen = qemu_get_be16(s->f);
5783 if (clen > IOBUF_SIZE)
5784 return -1;
5785 qemu_get_buffer(s->f, s->buf, clen);
5786 s->zstream.avail_in = clen;
5787 s->zstream.next_in = s->buf;
5789 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5790 if (ret != Z_OK && ret != Z_STREAM_END) {
5791 return -1;
5794 return 0;
5797 static void ram_decompress_close(RamDecompressState *s)
5799 inflateEnd(&s->zstream);
5802 static void ram_save(QEMUFile *f, void *opaque)
5804 int i;
5805 RamCompressState s1, *s = &s1;
5806 uint8_t buf[10];
5808 qemu_put_be32(f, phys_ram_size);
5809 if (ram_compress_open(s, f) < 0)
5810 return;
5811 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5812 #if 0
5813 if (tight_savevm_enabled) {
5814 int64_t sector_num;
5815 int j;
5817 /* find if the memory block is available on a virtual
5818 block device */
5819 sector_num = -1;
5820 for(j = 0; j < MAX_DISKS; j++) {
5821 if (bs_table[j]) {
5822 sector_num = bdrv_hash_find(bs_table[j],
5823 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5824 if (sector_num >= 0)
5825 break;
5828 if (j == MAX_DISKS)
5829 goto normal_compress;
5830 buf[0] = 1;
5831 buf[1] = j;
5832 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5833 ram_compress_buf(s, buf, 10);
5834 } else
5835 #endif
5837 // normal_compress:
5838 buf[0] = 0;
5839 ram_compress_buf(s, buf, 1);
5840 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5843 ram_compress_close(s);
5846 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5848 RamDecompressState s1, *s = &s1;
5849 uint8_t buf[10];
5850 int i;
5852 if (version_id == 1)
5853 return ram_load_v1(f, opaque);
5854 if (version_id != 2)
5855 return -EINVAL;
5856 if (qemu_get_be32(f) != phys_ram_size)
5857 return -EINVAL;
5858 if (ram_decompress_open(s, f) < 0)
5859 return -EINVAL;
5860 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5861 if (ram_decompress_buf(s, buf, 1) < 0) {
5862 fprintf(stderr, "Error while reading ram block header\n");
5863 goto error;
5865 if (buf[0] == 0) {
5866 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5867 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5868 goto error;
5870 } else
5871 #if 0
5872 if (buf[0] == 1) {
5873 int bs_index;
5874 int64_t sector_num;
5876 ram_decompress_buf(s, buf + 1, 9);
5877 bs_index = buf[1];
5878 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5879 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5880 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5881 goto error;
5883 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5884 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5885 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5886 bs_index, sector_num);
5887 goto error;
5889 } else
5890 #endif
5892 error:
5893 printf("Error block header\n");
5894 return -EINVAL;
5897 ram_decompress_close(s);
5898 return 0;
5901 /***********************************************************/
5902 /* bottom halves (can be seen as timers which expire ASAP) */
5904 struct QEMUBH {
5905 QEMUBHFunc *cb;
5906 void *opaque;
5907 int scheduled;
5908 QEMUBH *next;
5911 static QEMUBH *first_bh = NULL;
5913 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5915 QEMUBH *bh;
5916 bh = qemu_mallocz(sizeof(QEMUBH));
5917 if (!bh)
5918 return NULL;
5919 bh->cb = cb;
5920 bh->opaque = opaque;
5921 return bh;
5924 int qemu_bh_poll(void)
5926 QEMUBH *bh, **pbh;
5927 int ret;
5929 ret = 0;
5930 for(;;) {
5931 pbh = &first_bh;
5932 bh = *pbh;
5933 if (!bh)
5934 break;
5935 ret = 1;
5936 *pbh = bh->next;
5937 bh->scheduled = 0;
5938 bh->cb(bh->opaque);
5940 return ret;
5943 void qemu_bh_schedule(QEMUBH *bh)
5945 CPUState *env = cpu_single_env;
5946 if (bh->scheduled)
5947 return;
5948 bh->scheduled = 1;
5949 bh->next = first_bh;
5950 first_bh = bh;
5952 /* stop the currently executing CPU to execute the BH ASAP */
5953 if (env) {
5954 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5958 void qemu_bh_cancel(QEMUBH *bh)
5960 QEMUBH **pbh;
5961 if (bh->scheduled) {
5962 pbh = &first_bh;
5963 while (*pbh != bh)
5964 pbh = &(*pbh)->next;
5965 *pbh = bh->next;
5966 bh->scheduled = 0;
5970 void qemu_bh_delete(QEMUBH *bh)
5972 qemu_bh_cancel(bh);
5973 qemu_free(bh);
5976 /***********************************************************/
5977 /* machine registration */
5979 QEMUMachine *first_machine = NULL;
5981 int qemu_register_machine(QEMUMachine *m)
5983 QEMUMachine **pm;
5984 pm = &first_machine;
5985 while (*pm != NULL)
5986 pm = &(*pm)->next;
5987 m->next = NULL;
5988 *pm = m;
5989 return 0;
5992 QEMUMachine *find_machine(const char *name)
5994 QEMUMachine *m;
5996 for(m = first_machine; m != NULL; m = m->next) {
5997 if (!strcmp(m->name, name))
5998 return m;
6000 return NULL;
6003 /***********************************************************/
6004 /* main execution loop */
6006 void gui_update(void *opaque)
6008 display_state.dpy_refresh(&display_state);
6009 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6012 struct vm_change_state_entry {
6013 VMChangeStateHandler *cb;
6014 void *opaque;
6015 LIST_ENTRY (vm_change_state_entry) entries;
6018 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6020 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6021 void *opaque)
6023 VMChangeStateEntry *e;
6025 e = qemu_mallocz(sizeof (*e));
6026 if (!e)
6027 return NULL;
6029 e->cb = cb;
6030 e->opaque = opaque;
6031 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6032 return e;
6035 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6037 LIST_REMOVE (e, entries);
6038 qemu_free (e);
6041 static void vm_state_notify(int running)
6043 VMChangeStateEntry *e;
6045 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6046 e->cb(e->opaque, running);
6050 /* XXX: support several handlers */
6051 static VMStopHandler *vm_stop_cb;
6052 static void *vm_stop_opaque;
6054 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6056 vm_stop_cb = cb;
6057 vm_stop_opaque = opaque;
6058 return 0;
6061 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6063 vm_stop_cb = NULL;
6066 void vm_start(void)
6068 if (!vm_running) {
6069 cpu_enable_ticks();
6070 vm_running = 1;
6071 vm_state_notify(1);
6075 void vm_stop(int reason)
6077 if (vm_running) {
6078 cpu_disable_ticks();
6079 vm_running = 0;
6080 if (reason != 0) {
6081 if (vm_stop_cb) {
6082 vm_stop_cb(vm_stop_opaque, reason);
6085 vm_state_notify(0);
6089 /* reset/shutdown handler */
6091 typedef struct QEMUResetEntry {
6092 QEMUResetHandler *func;
6093 void *opaque;
6094 struct QEMUResetEntry *next;
6095 } QEMUResetEntry;
6097 static QEMUResetEntry *first_reset_entry;
6098 static int reset_requested;
6099 static int shutdown_requested;
6100 static int powerdown_requested;
6102 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6104 QEMUResetEntry **pre, *re;
6106 pre = &first_reset_entry;
6107 while (*pre != NULL)
6108 pre = &(*pre)->next;
6109 re = qemu_mallocz(sizeof(QEMUResetEntry));
6110 re->func = func;
6111 re->opaque = opaque;
6112 re->next = NULL;
6113 *pre = re;
6116 static void qemu_system_reset(void)
6118 QEMUResetEntry *re;
6120 /* reset all devices */
6121 for(re = first_reset_entry; re != NULL; re = re->next) {
6122 re->func(re->opaque);
6126 void qemu_system_reset_request(void)
6128 if (no_reboot) {
6129 shutdown_requested = 1;
6130 } else {
6131 reset_requested = 1;
6133 if (cpu_single_env)
6134 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6137 void qemu_system_shutdown_request(void)
6139 shutdown_requested = 1;
6140 if (cpu_single_env)
6141 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6144 void qemu_system_powerdown_request(void)
6146 powerdown_requested = 1;
6147 if (cpu_single_env)
6148 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6151 void main_loop_wait(int timeout)
6153 IOHandlerRecord *ioh;
6154 fd_set rfds, wfds, xfds;
6155 int ret, nfds;
6156 struct timeval tv;
6157 PollingEntry *pe;
6160 /* XXX: need to suppress polling by better using win32 events */
6161 ret = 0;
6162 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6163 ret |= pe->func(pe->opaque);
6165 #ifdef _WIN32
6166 if (ret == 0 && timeout > 0) {
6167 int err;
6168 WaitObjects *w = &wait_objects;
6170 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6171 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6172 if (w->func[ret - WAIT_OBJECT_0])
6173 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6174 } else if (ret == WAIT_TIMEOUT) {
6175 } else {
6176 err = GetLastError();
6177 fprintf(stderr, "Wait error %d %d\n", ret, err);
6180 #endif
6181 /* poll any events */
6182 /* XXX: separate device handlers from system ones */
6183 nfds = -1;
6184 FD_ZERO(&rfds);
6185 FD_ZERO(&wfds);
6186 FD_ZERO(&xfds);
6187 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6188 if (ioh->deleted)
6189 continue;
6190 if (ioh->fd_read &&
6191 (!ioh->fd_read_poll ||
6192 ioh->fd_read_poll(ioh->opaque) != 0)) {
6193 FD_SET(ioh->fd, &rfds);
6194 if (ioh->fd > nfds)
6195 nfds = ioh->fd;
6197 if (ioh->fd_write) {
6198 FD_SET(ioh->fd, &wfds);
6199 if (ioh->fd > nfds)
6200 nfds = ioh->fd;
6204 tv.tv_sec = 0;
6205 #ifdef _WIN32
6206 tv.tv_usec = 0;
6207 #else
6208 tv.tv_usec = timeout * 1000;
6209 #endif
6210 #if defined(CONFIG_SLIRP)
6211 if (slirp_inited) {
6212 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6214 #endif
6215 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6216 if (ret > 0) {
6217 IOHandlerRecord **pioh;
6219 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6220 if (ioh->deleted)
6221 continue;
6222 if (FD_ISSET(ioh->fd, &rfds)) {
6223 ioh->fd_read(ioh->opaque);
6225 if (FD_ISSET(ioh->fd, &wfds)) {
6226 ioh->fd_write(ioh->opaque);
6230 /* remove deleted IO handlers */
6231 pioh = &first_io_handler;
6232 while (*pioh) {
6233 ioh = *pioh;
6234 if (ioh->deleted) {
6235 *pioh = ioh->next;
6236 qemu_free(ioh);
6237 } else
6238 pioh = &ioh->next;
6241 #if defined(CONFIG_SLIRP)
6242 if (slirp_inited) {
6243 if (ret < 0) {
6244 FD_ZERO(&rfds);
6245 FD_ZERO(&wfds);
6246 FD_ZERO(&xfds);
6248 slirp_select_poll(&rfds, &wfds, &xfds);
6250 #endif
6251 qemu_aio_poll();
6252 qemu_bh_poll();
6254 if (vm_running) {
6255 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6256 qemu_get_clock(vm_clock));
6257 /* run dma transfers, if any */
6258 DMA_run();
6261 /* real time timers */
6262 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6263 qemu_get_clock(rt_clock));
6266 static CPUState *cur_cpu;
6268 int main_loop(void)
6270 int ret, timeout;
6271 #ifdef CONFIG_PROFILER
6272 int64_t ti;
6273 #endif
6274 CPUState *env;
6276 cur_cpu = first_cpu;
6277 for(;;) {
6278 if (vm_running) {
6280 env = cur_cpu;
6281 for(;;) {
6282 /* get next cpu */
6283 env = env->next_cpu;
6284 if (!env)
6285 env = first_cpu;
6286 #ifdef CONFIG_PROFILER
6287 ti = profile_getclock();
6288 #endif
6289 ret = cpu_exec(env);
6290 #ifdef CONFIG_PROFILER
6291 qemu_time += profile_getclock() - ti;
6292 #endif
6293 if (ret == EXCP_HLT) {
6294 /* Give the next CPU a chance to run. */
6295 cur_cpu = env;
6296 continue;
6298 if (ret != EXCP_HALTED)
6299 break;
6300 /* all CPUs are halted ? */
6301 if (env == cur_cpu)
6302 break;
6304 cur_cpu = env;
6306 if (shutdown_requested) {
6307 ret = EXCP_INTERRUPT;
6308 break;
6310 if (reset_requested) {
6311 reset_requested = 0;
6312 qemu_system_reset();
6313 ret = EXCP_INTERRUPT;
6315 if (powerdown_requested) {
6316 powerdown_requested = 0;
6317 qemu_system_powerdown();
6318 ret = EXCP_INTERRUPT;
6320 if (ret == EXCP_DEBUG) {
6321 vm_stop(EXCP_DEBUG);
6323 /* If all cpus are halted then wait until the next IRQ */
6324 /* XXX: use timeout computed from timers */
6325 if (ret == EXCP_HALTED)
6326 timeout = 10;
6327 else
6328 timeout = 0;
6329 } else {
6330 timeout = 10;
6332 #ifdef CONFIG_PROFILER
6333 ti = profile_getclock();
6334 #endif
6335 main_loop_wait(timeout);
6336 #ifdef CONFIG_PROFILER
6337 dev_time += profile_getclock() - ti;
6338 #endif
6340 cpu_disable_ticks();
6341 return ret;
6344 void help(void)
6346 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6347 "usage: %s [options] [disk_image]\n"
6348 "\n"
6349 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6350 "\n"
6351 "Standard options:\n"
6352 "-M machine select emulated machine (-M ? for list)\n"
6353 "-cpu cpu select CPU (-cpu ? for list)\n"
6354 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6355 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6356 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6357 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6358 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6359 "-snapshot write to temporary files instead of disk image files\n"
6360 #ifdef CONFIG_SDL
6361 "-no-frame open SDL window without a frame and window decorations\n"
6362 "-no-quit disable SDL window close capability\n"
6363 #endif
6364 #ifdef TARGET_I386
6365 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6366 #endif
6367 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6368 "-smp n set the number of CPUs to 'n' [default=1]\n"
6369 "-nographic disable graphical output and redirect serial I/Os to console\n"
6370 #ifndef _WIN32
6371 "-k language use keyboard layout (for example \"fr\" for French)\n"
6372 #endif
6373 #ifdef HAS_AUDIO
6374 "-audio-help print list of audio drivers and their options\n"
6375 "-soundhw c1,... enable audio support\n"
6376 " and only specified sound cards (comma separated list)\n"
6377 " use -soundhw ? to get the list of supported cards\n"
6378 " use -soundhw all to enable all of them\n"
6379 #endif
6380 "-localtime set the real time clock to local time [default=utc]\n"
6381 "-full-screen start in full screen\n"
6382 #ifdef TARGET_I386
6383 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6384 #endif
6385 "-usb enable the USB driver (will be the default soon)\n"
6386 "-usbdevice name add the host or guest USB device 'name'\n"
6387 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6388 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6389 #endif
6390 "-name string set the name of the guest\n"
6391 "\n"
6392 "Network options:\n"
6393 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6394 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6395 #ifdef CONFIG_SLIRP
6396 "-net user[,vlan=n][,hostname=host]\n"
6397 " connect the user mode network stack to VLAN 'n' and send\n"
6398 " hostname 'host' to DHCP clients\n"
6399 #endif
6400 #ifdef _WIN32
6401 "-net tap[,vlan=n],ifname=name\n"
6402 " connect the host TAP network interface to VLAN 'n'\n"
6403 #else
6404 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6405 " connect the host TAP network interface to VLAN 'n' and use\n"
6406 " the network script 'file' (default=%s);\n"
6407 " use 'script=no' to disable script execution;\n"
6408 " use 'fd=h' to connect to an already opened TAP interface\n"
6409 #endif
6410 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6411 " connect the vlan 'n' to another VLAN using a socket connection\n"
6412 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6413 " connect the vlan 'n' to multicast maddr and port\n"
6414 "-net none use it alone to have zero network devices; if no -net option\n"
6415 " is provided, the default is '-net nic -net user'\n"
6416 "\n"
6417 #ifdef CONFIG_SLIRP
6418 "-tftp dir allow tftp access to files in dir [-net user]\n"
6419 "-bootp file advertise file in BOOTP replies\n"
6420 #ifndef _WIN32
6421 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6422 #endif
6423 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6424 " redirect TCP or UDP connections from host to guest [-net user]\n"
6425 #endif
6426 "\n"
6427 "Linux boot specific:\n"
6428 "-kernel bzImage use 'bzImage' as kernel image\n"
6429 "-append cmdline use 'cmdline' as kernel command line\n"
6430 "-initrd file use 'file' as initial ram disk\n"
6431 "\n"
6432 "Debug/Expert options:\n"
6433 "-monitor dev redirect the monitor to char device 'dev'\n"
6434 "-serial dev redirect the serial port to char device 'dev'\n"
6435 "-parallel dev redirect the parallel port to char device 'dev'\n"
6436 "-pidfile file Write PID to 'file'\n"
6437 "-S freeze CPU at startup (use 'c' to start execution)\n"
6438 "-s wait gdb connection to port\n"
6439 "-p port set gdb connection port [default=%s]\n"
6440 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6441 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6442 " translation (t=none or lba) (usually qemu can guess them)\n"
6443 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6444 #ifdef USE_KQEMU
6445 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6446 "-no-kqemu disable KQEMU kernel module usage\n"
6447 #endif
6448 #ifdef USE_CODE_COPY
6449 "-no-code-copy disable code copy acceleration\n"
6450 #endif
6451 #ifdef TARGET_I386
6452 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6453 " (default is CL-GD5446 PCI VGA)\n"
6454 "-no-acpi disable ACPI\n"
6455 #endif
6456 "-no-reboot exit instead of rebooting\n"
6457 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6458 "-vnc display start a VNC server on display\n"
6459 #ifndef _WIN32
6460 "-daemonize daemonize QEMU after initializing\n"
6461 #endif
6462 "-option-rom rom load a file, rom, into the option ROM space\n"
6463 "\n"
6464 "During emulation, the following keys are useful:\n"
6465 "ctrl-alt-f toggle full screen\n"
6466 "ctrl-alt-n switch to virtual console 'n'\n"
6467 "ctrl-alt toggle mouse and keyboard grab\n"
6468 "\n"
6469 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6471 "qemu",
6472 DEFAULT_RAM_SIZE,
6473 #ifndef _WIN32
6474 DEFAULT_NETWORK_SCRIPT,
6475 #endif
6476 DEFAULT_GDBSTUB_PORT,
6477 "/tmp/qemu.log");
6478 exit(1);
6481 #define HAS_ARG 0x0001
6483 enum {
6484 QEMU_OPTION_h,
6486 QEMU_OPTION_M,
6487 QEMU_OPTION_cpu,
6488 QEMU_OPTION_fda,
6489 QEMU_OPTION_fdb,
6490 QEMU_OPTION_hda,
6491 QEMU_OPTION_hdb,
6492 QEMU_OPTION_hdc,
6493 QEMU_OPTION_hdd,
6494 QEMU_OPTION_cdrom,
6495 QEMU_OPTION_boot,
6496 QEMU_OPTION_snapshot,
6497 #ifdef TARGET_I386
6498 QEMU_OPTION_no_fd_bootchk,
6499 #endif
6500 QEMU_OPTION_m,
6501 QEMU_OPTION_nographic,
6502 #ifdef HAS_AUDIO
6503 QEMU_OPTION_audio_help,
6504 QEMU_OPTION_soundhw,
6505 #endif
6507 QEMU_OPTION_net,
6508 QEMU_OPTION_tftp,
6509 QEMU_OPTION_bootp,
6510 QEMU_OPTION_smb,
6511 QEMU_OPTION_redir,
6513 QEMU_OPTION_kernel,
6514 QEMU_OPTION_append,
6515 QEMU_OPTION_initrd,
6517 QEMU_OPTION_S,
6518 QEMU_OPTION_s,
6519 QEMU_OPTION_p,
6520 QEMU_OPTION_d,
6521 QEMU_OPTION_hdachs,
6522 QEMU_OPTION_L,
6523 QEMU_OPTION_no_code_copy,
6524 QEMU_OPTION_k,
6525 QEMU_OPTION_localtime,
6526 QEMU_OPTION_cirrusvga,
6527 QEMU_OPTION_g,
6528 QEMU_OPTION_std_vga,
6529 QEMU_OPTION_echr,
6530 QEMU_OPTION_monitor,
6531 QEMU_OPTION_serial,
6532 QEMU_OPTION_parallel,
6533 QEMU_OPTION_loadvm,
6534 QEMU_OPTION_full_screen,
6535 QEMU_OPTION_no_frame,
6536 QEMU_OPTION_no_quit,
6537 QEMU_OPTION_pidfile,
6538 QEMU_OPTION_no_kqemu,
6539 QEMU_OPTION_kernel_kqemu,
6540 QEMU_OPTION_win2k_hack,
6541 QEMU_OPTION_usb,
6542 QEMU_OPTION_usbdevice,
6543 QEMU_OPTION_smp,
6544 QEMU_OPTION_vnc,
6545 QEMU_OPTION_no_acpi,
6546 QEMU_OPTION_no_reboot,
6547 QEMU_OPTION_daemonize,
6548 QEMU_OPTION_option_rom,
6549 QEMU_OPTION_semihosting,
6550 QEMU_OPTION_name,
6553 typedef struct QEMUOption {
6554 const char *name;
6555 int flags;
6556 int index;
6557 } QEMUOption;
6559 const QEMUOption qemu_options[] = {
6560 { "h", 0, QEMU_OPTION_h },
6561 { "help", 0, QEMU_OPTION_h },
6563 { "M", HAS_ARG, QEMU_OPTION_M },
6564 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6565 { "fda", HAS_ARG, QEMU_OPTION_fda },
6566 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6567 { "hda", HAS_ARG, QEMU_OPTION_hda },
6568 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6569 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6570 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6571 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6572 { "boot", HAS_ARG, QEMU_OPTION_boot },
6573 { "snapshot", 0, QEMU_OPTION_snapshot },
6574 #ifdef TARGET_I386
6575 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6576 #endif
6577 { "m", HAS_ARG, QEMU_OPTION_m },
6578 { "nographic", 0, QEMU_OPTION_nographic },
6579 { "k", HAS_ARG, QEMU_OPTION_k },
6580 #ifdef HAS_AUDIO
6581 { "audio-help", 0, QEMU_OPTION_audio_help },
6582 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6583 #endif
6585 { "net", HAS_ARG, QEMU_OPTION_net},
6586 #ifdef CONFIG_SLIRP
6587 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6588 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6589 #ifndef _WIN32
6590 { "smb", HAS_ARG, QEMU_OPTION_smb },
6591 #endif
6592 { "redir", HAS_ARG, QEMU_OPTION_redir },
6593 #endif
6595 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6596 { "append", HAS_ARG, QEMU_OPTION_append },
6597 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6599 { "S", 0, QEMU_OPTION_S },
6600 { "s", 0, QEMU_OPTION_s },
6601 { "p", HAS_ARG, QEMU_OPTION_p },
6602 { "d", HAS_ARG, QEMU_OPTION_d },
6603 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6604 { "L", HAS_ARG, QEMU_OPTION_L },
6605 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6606 #ifdef USE_KQEMU
6607 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6608 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6609 #endif
6610 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6611 { "g", 1, QEMU_OPTION_g },
6612 #endif
6613 { "localtime", 0, QEMU_OPTION_localtime },
6614 { "std-vga", 0, QEMU_OPTION_std_vga },
6615 { "echr", 1, QEMU_OPTION_echr },
6616 { "monitor", 1, QEMU_OPTION_monitor },
6617 { "serial", 1, QEMU_OPTION_serial },
6618 { "parallel", 1, QEMU_OPTION_parallel },
6619 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6620 { "full-screen", 0, QEMU_OPTION_full_screen },
6621 #ifdef CONFIG_SDL
6622 { "no-frame", 0, QEMU_OPTION_no_frame },
6623 { "no-quit", 0, QEMU_OPTION_no_quit },
6624 #endif
6625 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6626 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6627 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6628 { "smp", HAS_ARG, QEMU_OPTION_smp },
6629 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6631 /* temporary options */
6632 { "usb", 0, QEMU_OPTION_usb },
6633 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6634 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6635 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6636 { "daemonize", 0, QEMU_OPTION_daemonize },
6637 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6638 #if defined(TARGET_ARM)
6639 { "semihosting", 0, QEMU_OPTION_semihosting },
6640 #endif
6641 { "name", HAS_ARG, QEMU_OPTION_name },
6642 { NULL },
6645 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6647 /* this stack is only used during signal handling */
6648 #define SIGNAL_STACK_SIZE 32768
6650 static uint8_t *signal_stack;
6652 #endif
6654 /* password input */
6656 static BlockDriverState *get_bdrv(int index)
6658 BlockDriverState *bs;
6660 if (index < 4) {
6661 bs = bs_table[index];
6662 } else if (index < 6) {
6663 bs = fd_table[index - 4];
6664 } else {
6665 bs = NULL;
6667 return bs;
6670 static void read_passwords(void)
6672 BlockDriverState *bs;
6673 int i, j;
6674 char password[256];
6676 for(i = 0; i < 6; i++) {
6677 bs = get_bdrv(i);
6678 if (bs && bdrv_is_encrypted(bs)) {
6679 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6680 for(j = 0; j < 3; j++) {
6681 monitor_readline("Password: ",
6682 1, password, sizeof(password));
6683 if (bdrv_set_key(bs, password) == 0)
6684 break;
6685 term_printf("invalid password\n");
6691 /* XXX: currently we cannot use simultaneously different CPUs */
6692 void register_machines(void)
6694 #if defined(TARGET_I386)
6695 qemu_register_machine(&pc_machine);
6696 qemu_register_machine(&isapc_machine);
6697 #elif defined(TARGET_PPC)
6698 qemu_register_machine(&heathrow_machine);
6699 qemu_register_machine(&core99_machine);
6700 qemu_register_machine(&prep_machine);
6701 #elif defined(TARGET_MIPS)
6702 qemu_register_machine(&mips_machine);
6703 qemu_register_machine(&mips_malta_machine);
6704 #elif defined(TARGET_SPARC)
6705 #ifdef TARGET_SPARC64
6706 qemu_register_machine(&sun4u_machine);
6707 #else
6708 qemu_register_machine(&sun4m_machine);
6709 #endif
6710 #elif defined(TARGET_ARM)
6711 qemu_register_machine(&integratorcp_machine);
6712 qemu_register_machine(&versatilepb_machine);
6713 qemu_register_machine(&versatileab_machine);
6714 qemu_register_machine(&realview_machine);
6715 #elif defined(TARGET_SH4)
6716 qemu_register_machine(&shix_machine);
6717 #else
6718 #error unsupported CPU
6719 #endif
6722 #ifdef HAS_AUDIO
6723 struct soundhw soundhw[] = {
6724 #ifdef TARGET_I386
6726 "pcspk",
6727 "PC speaker",
6730 { .init_isa = pcspk_audio_init }
6732 #endif
6734 "sb16",
6735 "Creative Sound Blaster 16",
6738 { .init_isa = SB16_init }
6741 #ifdef CONFIG_ADLIB
6743 "adlib",
6744 #ifdef HAS_YMF262
6745 "Yamaha YMF262 (OPL3)",
6746 #else
6747 "Yamaha YM3812 (OPL2)",
6748 #endif
6751 { .init_isa = Adlib_init }
6753 #endif
6755 #ifdef CONFIG_GUS
6757 "gus",
6758 "Gravis Ultrasound GF1",
6761 { .init_isa = GUS_init }
6763 #endif
6766 "es1370",
6767 "ENSONIQ AudioPCI ES1370",
6770 { .init_pci = es1370_init }
6773 { NULL, NULL, 0, 0, { NULL } }
6776 static void select_soundhw (const char *optarg)
6778 struct soundhw *c;
6780 if (*optarg == '?') {
6781 show_valid_cards:
6783 printf ("Valid sound card names (comma separated):\n");
6784 for (c = soundhw; c->name; ++c) {
6785 printf ("%-11s %s\n", c->name, c->descr);
6787 printf ("\n-soundhw all will enable all of the above\n");
6788 exit (*optarg != '?');
6790 else {
6791 size_t l;
6792 const char *p;
6793 char *e;
6794 int bad_card = 0;
6796 if (!strcmp (optarg, "all")) {
6797 for (c = soundhw; c->name; ++c) {
6798 c->enabled = 1;
6800 return;
6803 p = optarg;
6804 while (*p) {
6805 e = strchr (p, ',');
6806 l = !e ? strlen (p) : (size_t) (e - p);
6808 for (c = soundhw; c->name; ++c) {
6809 if (!strncmp (c->name, p, l)) {
6810 c->enabled = 1;
6811 break;
6815 if (!c->name) {
6816 if (l > 80) {
6817 fprintf (stderr,
6818 "Unknown sound card name (too big to show)\n");
6820 else {
6821 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6822 (int) l, p);
6824 bad_card = 1;
6826 p += l + (e != NULL);
6829 if (bad_card)
6830 goto show_valid_cards;
6833 #endif
6835 #ifdef _WIN32
6836 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6838 exit(STATUS_CONTROL_C_EXIT);
6839 return TRUE;
6841 #endif
6843 #define MAX_NET_CLIENTS 32
6845 int main(int argc, char **argv)
6847 #ifdef CONFIG_GDBSTUB
6848 int use_gdbstub;
6849 const char *gdbstub_port;
6850 #endif
6851 int i, cdrom_index;
6852 int snapshot, linux_boot;
6853 const char *initrd_filename;
6854 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6855 const char *kernel_filename, *kernel_cmdline;
6856 DisplayState *ds = &display_state;
6857 int cyls, heads, secs, translation;
6858 char net_clients[MAX_NET_CLIENTS][256];
6859 int nb_net_clients;
6860 int optind;
6861 const char *r, *optarg;
6862 CharDriverState *monitor_hd;
6863 char monitor_device[128];
6864 char serial_devices[MAX_SERIAL_PORTS][128];
6865 int serial_device_index;
6866 char parallel_devices[MAX_PARALLEL_PORTS][128];
6867 int parallel_device_index;
6868 const char *loadvm = NULL;
6869 QEMUMachine *machine;
6870 const char *cpu_model;
6871 char usb_devices[MAX_USB_CMDLINE][128];
6872 int usb_devices_index;
6873 int fds[2];
6874 const char *pid_file = NULL;
6876 LIST_INIT (&vm_change_state_head);
6877 #ifndef _WIN32
6879 struct sigaction act;
6880 sigfillset(&act.sa_mask);
6881 act.sa_flags = 0;
6882 act.sa_handler = SIG_IGN;
6883 sigaction(SIGPIPE, &act, NULL);
6885 #else
6886 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6887 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6888 QEMU to run on a single CPU */
6890 HANDLE h;
6891 DWORD mask, smask;
6892 int i;
6893 h = GetCurrentProcess();
6894 if (GetProcessAffinityMask(h, &mask, &smask)) {
6895 for(i = 0; i < 32; i++) {
6896 if (mask & (1 << i))
6897 break;
6899 if (i != 32) {
6900 mask = 1 << i;
6901 SetProcessAffinityMask(h, mask);
6905 #endif
6907 register_machines();
6908 machine = first_machine;
6909 cpu_model = NULL;
6910 initrd_filename = NULL;
6911 for(i = 0; i < MAX_FD; i++)
6912 fd_filename[i] = NULL;
6913 for(i = 0; i < MAX_DISKS; i++)
6914 hd_filename[i] = NULL;
6915 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6916 vga_ram_size = VGA_RAM_SIZE;
6917 #ifdef CONFIG_GDBSTUB
6918 use_gdbstub = 0;
6919 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6920 #endif
6921 snapshot = 0;
6922 nographic = 0;
6923 kernel_filename = NULL;
6924 kernel_cmdline = "";
6925 #ifdef TARGET_PPC
6926 cdrom_index = 1;
6927 #else
6928 cdrom_index = 2;
6929 #endif
6930 cyls = heads = secs = 0;
6931 translation = BIOS_ATA_TRANSLATION_AUTO;
6932 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6934 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6935 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6936 serial_devices[i][0] = '\0';
6937 serial_device_index = 0;
6939 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6940 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6941 parallel_devices[i][0] = '\0';
6942 parallel_device_index = 0;
6944 usb_devices_index = 0;
6946 nb_net_clients = 0;
6948 nb_nics = 0;
6949 /* default mac address of the first network interface */
6951 optind = 1;
6952 for(;;) {
6953 if (optind >= argc)
6954 break;
6955 r = argv[optind];
6956 if (r[0] != '-') {
6957 hd_filename[0] = argv[optind++];
6958 } else {
6959 const QEMUOption *popt;
6961 optind++;
6962 /* Treat --foo the same as -foo. */
6963 if (r[1] == '-')
6964 r++;
6965 popt = qemu_options;
6966 for(;;) {
6967 if (!popt->name) {
6968 fprintf(stderr, "%s: invalid option -- '%s'\n",
6969 argv[0], r);
6970 exit(1);
6972 if (!strcmp(popt->name, r + 1))
6973 break;
6974 popt++;
6976 if (popt->flags & HAS_ARG) {
6977 if (optind >= argc) {
6978 fprintf(stderr, "%s: option '%s' requires an argument\n",
6979 argv[0], r);
6980 exit(1);
6982 optarg = argv[optind++];
6983 } else {
6984 optarg = NULL;
6987 switch(popt->index) {
6988 case QEMU_OPTION_M:
6989 machine = find_machine(optarg);
6990 if (!machine) {
6991 QEMUMachine *m;
6992 printf("Supported machines are:\n");
6993 for(m = first_machine; m != NULL; m = m->next) {
6994 printf("%-10s %s%s\n",
6995 m->name, m->desc,
6996 m == first_machine ? " (default)" : "");
6998 exit(1);
7000 break;
7001 case QEMU_OPTION_cpu:
7002 /* hw initialization will check this */
7003 if (optarg[0] == '?') {
7004 #if defined(TARGET_PPC)
7005 ppc_cpu_list(stdout, &fprintf);
7006 #elif defined(TARGET_ARM)
7007 arm_cpu_list();
7008 #elif defined(TARGET_MIPS)
7009 mips_cpu_list(stdout, &fprintf);
7010 #endif
7011 exit(1);
7012 } else {
7013 cpu_model = optarg;
7015 break;
7016 case QEMU_OPTION_initrd:
7017 initrd_filename = optarg;
7018 break;
7019 case QEMU_OPTION_hda:
7020 case QEMU_OPTION_hdb:
7021 case QEMU_OPTION_hdc:
7022 case QEMU_OPTION_hdd:
7024 int hd_index;
7025 hd_index = popt->index - QEMU_OPTION_hda;
7026 hd_filename[hd_index] = optarg;
7027 if (hd_index == cdrom_index)
7028 cdrom_index = -1;
7030 break;
7031 case QEMU_OPTION_snapshot:
7032 snapshot = 1;
7033 break;
7034 case QEMU_OPTION_hdachs:
7036 const char *p;
7037 p = optarg;
7038 cyls = strtol(p, (char **)&p, 0);
7039 if (cyls < 1 || cyls > 16383)
7040 goto chs_fail;
7041 if (*p != ',')
7042 goto chs_fail;
7043 p++;
7044 heads = strtol(p, (char **)&p, 0);
7045 if (heads < 1 || heads > 16)
7046 goto chs_fail;
7047 if (*p != ',')
7048 goto chs_fail;
7049 p++;
7050 secs = strtol(p, (char **)&p, 0);
7051 if (secs < 1 || secs > 63)
7052 goto chs_fail;
7053 if (*p == ',') {
7054 p++;
7055 if (!strcmp(p, "none"))
7056 translation = BIOS_ATA_TRANSLATION_NONE;
7057 else if (!strcmp(p, "lba"))
7058 translation = BIOS_ATA_TRANSLATION_LBA;
7059 else if (!strcmp(p, "auto"))
7060 translation = BIOS_ATA_TRANSLATION_AUTO;
7061 else
7062 goto chs_fail;
7063 } else if (*p != '\0') {
7064 chs_fail:
7065 fprintf(stderr, "qemu: invalid physical CHS format\n");
7066 exit(1);
7069 break;
7070 case QEMU_OPTION_nographic:
7071 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7072 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7073 nographic = 1;
7074 break;
7075 case QEMU_OPTION_kernel:
7076 kernel_filename = optarg;
7077 break;
7078 case QEMU_OPTION_append:
7079 kernel_cmdline = optarg;
7080 break;
7081 case QEMU_OPTION_cdrom:
7082 if (cdrom_index >= 0) {
7083 hd_filename[cdrom_index] = optarg;
7085 break;
7086 case QEMU_OPTION_boot:
7087 boot_device = optarg[0];
7088 if (boot_device != 'a' &&
7089 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7090 // Network boot
7091 boot_device != 'n' &&
7092 #endif
7093 boot_device != 'c' && boot_device != 'd') {
7094 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7095 exit(1);
7097 break;
7098 case QEMU_OPTION_fda:
7099 fd_filename[0] = optarg;
7100 break;
7101 case QEMU_OPTION_fdb:
7102 fd_filename[1] = optarg;
7103 break;
7104 #ifdef TARGET_I386
7105 case QEMU_OPTION_no_fd_bootchk:
7106 fd_bootchk = 0;
7107 break;
7108 #endif
7109 case QEMU_OPTION_no_code_copy:
7110 code_copy_enabled = 0;
7111 break;
7112 case QEMU_OPTION_net:
7113 if (nb_net_clients >= MAX_NET_CLIENTS) {
7114 fprintf(stderr, "qemu: too many network clients\n");
7115 exit(1);
7117 pstrcpy(net_clients[nb_net_clients],
7118 sizeof(net_clients[0]),
7119 optarg);
7120 nb_net_clients++;
7121 break;
7122 #ifdef CONFIG_SLIRP
7123 case QEMU_OPTION_tftp:
7124 tftp_prefix = optarg;
7125 break;
7126 case QEMU_OPTION_bootp:
7127 bootp_filename = optarg;
7128 break;
7129 #ifndef _WIN32
7130 case QEMU_OPTION_smb:
7131 net_slirp_smb(optarg);
7132 break;
7133 #endif
7134 case QEMU_OPTION_redir:
7135 net_slirp_redir(optarg);
7136 break;
7137 #endif
7138 #ifdef HAS_AUDIO
7139 case QEMU_OPTION_audio_help:
7140 AUD_help ();
7141 exit (0);
7142 break;
7143 case QEMU_OPTION_soundhw:
7144 select_soundhw (optarg);
7145 break;
7146 #endif
7147 case QEMU_OPTION_h:
7148 help();
7149 break;
7150 case QEMU_OPTION_m:
7151 ram_size = atoi(optarg) * 1024 * 1024;
7152 if (ram_size <= 0)
7153 help();
7154 if (ram_size > PHYS_RAM_MAX_SIZE) {
7155 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7156 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7157 exit(1);
7159 break;
7160 case QEMU_OPTION_d:
7162 int mask;
7163 CPULogItem *item;
7165 mask = cpu_str_to_log_mask(optarg);
7166 if (!mask) {
7167 printf("Log items (comma separated):\n");
7168 for(item = cpu_log_items; item->mask != 0; item++) {
7169 printf("%-10s %s\n", item->name, item->help);
7171 exit(1);
7173 cpu_set_log(mask);
7175 break;
7176 #ifdef CONFIG_GDBSTUB
7177 case QEMU_OPTION_s:
7178 use_gdbstub = 1;
7179 break;
7180 case QEMU_OPTION_p:
7181 gdbstub_port = optarg;
7182 break;
7183 #endif
7184 case QEMU_OPTION_L:
7185 bios_dir = optarg;
7186 break;
7187 case QEMU_OPTION_S:
7188 autostart = 0;
7189 break;
7190 case QEMU_OPTION_k:
7191 keyboard_layout = optarg;
7192 break;
7193 case QEMU_OPTION_localtime:
7194 rtc_utc = 0;
7195 break;
7196 case QEMU_OPTION_cirrusvga:
7197 cirrus_vga_enabled = 1;
7198 break;
7199 case QEMU_OPTION_std_vga:
7200 cirrus_vga_enabled = 0;
7201 break;
7202 case QEMU_OPTION_g:
7204 const char *p;
7205 int w, h, depth;
7206 p = optarg;
7207 w = strtol(p, (char **)&p, 10);
7208 if (w <= 0) {
7209 graphic_error:
7210 fprintf(stderr, "qemu: invalid resolution or depth\n");
7211 exit(1);
7213 if (*p != 'x')
7214 goto graphic_error;
7215 p++;
7216 h = strtol(p, (char **)&p, 10);
7217 if (h <= 0)
7218 goto graphic_error;
7219 if (*p == 'x') {
7220 p++;
7221 depth = strtol(p, (char **)&p, 10);
7222 if (depth != 8 && depth != 15 && depth != 16 &&
7223 depth != 24 && depth != 32)
7224 goto graphic_error;
7225 } else if (*p == '\0') {
7226 depth = graphic_depth;
7227 } else {
7228 goto graphic_error;
7231 graphic_width = w;
7232 graphic_height = h;
7233 graphic_depth = depth;
7235 break;
7236 case QEMU_OPTION_echr:
7238 char *r;
7239 term_escape_char = strtol(optarg, &r, 0);
7240 if (r == optarg)
7241 printf("Bad argument to echr\n");
7242 break;
7244 case QEMU_OPTION_monitor:
7245 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7246 break;
7247 case QEMU_OPTION_serial:
7248 if (serial_device_index >= MAX_SERIAL_PORTS) {
7249 fprintf(stderr, "qemu: too many serial ports\n");
7250 exit(1);
7252 pstrcpy(serial_devices[serial_device_index],
7253 sizeof(serial_devices[0]), optarg);
7254 serial_device_index++;
7255 break;
7256 case QEMU_OPTION_parallel:
7257 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7258 fprintf(stderr, "qemu: too many parallel ports\n");
7259 exit(1);
7261 pstrcpy(parallel_devices[parallel_device_index],
7262 sizeof(parallel_devices[0]), optarg);
7263 parallel_device_index++;
7264 break;
7265 case QEMU_OPTION_loadvm:
7266 loadvm = optarg;
7267 break;
7268 case QEMU_OPTION_full_screen:
7269 full_screen = 1;
7270 break;
7271 #ifdef CONFIG_SDL
7272 case QEMU_OPTION_no_frame:
7273 no_frame = 1;
7274 break;
7275 case QEMU_OPTION_no_quit:
7276 no_quit = 1;
7277 break;
7278 #endif
7279 case QEMU_OPTION_pidfile:
7280 pid_file = optarg;
7281 break;
7282 #ifdef TARGET_I386
7283 case QEMU_OPTION_win2k_hack:
7284 win2k_install_hack = 1;
7285 break;
7286 #endif
7287 #ifdef USE_KQEMU
7288 case QEMU_OPTION_no_kqemu:
7289 kqemu_allowed = 0;
7290 break;
7291 case QEMU_OPTION_kernel_kqemu:
7292 kqemu_allowed = 2;
7293 break;
7294 #endif
7295 case QEMU_OPTION_usb:
7296 usb_enabled = 1;
7297 break;
7298 case QEMU_OPTION_usbdevice:
7299 usb_enabled = 1;
7300 if (usb_devices_index >= MAX_USB_CMDLINE) {
7301 fprintf(stderr, "Too many USB devices\n");
7302 exit(1);
7304 pstrcpy(usb_devices[usb_devices_index],
7305 sizeof(usb_devices[usb_devices_index]),
7306 optarg);
7307 usb_devices_index++;
7308 break;
7309 case QEMU_OPTION_smp:
7310 smp_cpus = atoi(optarg);
7311 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7312 fprintf(stderr, "Invalid number of CPUs\n");
7313 exit(1);
7315 break;
7316 case QEMU_OPTION_vnc:
7317 vnc_display = optarg;
7318 break;
7319 case QEMU_OPTION_no_acpi:
7320 acpi_enabled = 0;
7321 break;
7322 case QEMU_OPTION_no_reboot:
7323 no_reboot = 1;
7324 break;
7325 case QEMU_OPTION_daemonize:
7326 daemonize = 1;
7327 break;
7328 case QEMU_OPTION_option_rom:
7329 if (nb_option_roms >= MAX_OPTION_ROMS) {
7330 fprintf(stderr, "Too many option ROMs\n");
7331 exit(1);
7333 option_rom[nb_option_roms] = optarg;
7334 nb_option_roms++;
7335 break;
7336 case QEMU_OPTION_semihosting:
7337 semihosting_enabled = 1;
7338 break;
7339 case QEMU_OPTION_name:
7340 qemu_name = optarg;
7341 break;
7346 #ifndef _WIN32
7347 if (daemonize && !nographic && vnc_display == NULL) {
7348 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7349 daemonize = 0;
7352 if (daemonize) {
7353 pid_t pid;
7355 if (pipe(fds) == -1)
7356 exit(1);
7358 pid = fork();
7359 if (pid > 0) {
7360 uint8_t status;
7361 ssize_t len;
7363 close(fds[1]);
7365 again:
7366 len = read(fds[0], &status, 1);
7367 if (len == -1 && (errno == EINTR))
7368 goto again;
7370 if (len != 1)
7371 exit(1);
7372 else if (status == 1) {
7373 fprintf(stderr, "Could not acquire pidfile\n");
7374 exit(1);
7375 } else
7376 exit(0);
7377 } else if (pid < 0)
7378 exit(1);
7380 setsid();
7382 pid = fork();
7383 if (pid > 0)
7384 exit(0);
7385 else if (pid < 0)
7386 exit(1);
7388 umask(027);
7389 chdir("/");
7391 signal(SIGTSTP, SIG_IGN);
7392 signal(SIGTTOU, SIG_IGN);
7393 signal(SIGTTIN, SIG_IGN);
7395 #endif
7397 if (pid_file && create_pidfile(pid_file) != 0) {
7398 if (daemonize) {
7399 uint8_t status = 1;
7400 write(fds[1], &status, 1);
7401 } else
7402 fprintf(stderr, "Could not acquire pid file\n");
7403 exit(1);
7406 #ifdef USE_KQEMU
7407 if (smp_cpus > 1)
7408 kqemu_allowed = 0;
7409 #endif
7410 linux_boot = (kernel_filename != NULL);
7412 if (!linux_boot &&
7413 boot_device != 'n' &&
7414 hd_filename[0] == '\0' &&
7415 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7416 fd_filename[0] == '\0')
7417 help();
7419 /* boot to floppy or the default cd if no hard disk defined yet */
7420 if (hd_filename[0] == '\0' && boot_device == 'c') {
7421 if (fd_filename[0] != '\0')
7422 boot_device = 'a';
7423 else
7424 boot_device = 'd';
7427 setvbuf(stdout, NULL, _IOLBF, 0);
7429 init_timers();
7430 init_timer_alarm();
7431 qemu_aio_init();
7433 #ifdef _WIN32
7434 socket_init();
7435 #endif
7437 /* init network clients */
7438 if (nb_net_clients == 0) {
7439 /* if no clients, we use a default config */
7440 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7441 "nic");
7442 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7443 "user");
7444 nb_net_clients = 2;
7447 for(i = 0;i < nb_net_clients; i++) {
7448 if (net_client_init(net_clients[i]) < 0)
7449 exit(1);
7452 #ifdef TARGET_I386
7453 if (boot_device == 'n') {
7454 for (i = 0; i < nb_nics; i++) {
7455 const char *model = nd_table[i].model;
7456 char buf[1024];
7457 if (model == NULL)
7458 model = "ne2k_pci";
7459 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7460 if (get_image_size(buf) > 0) {
7461 option_rom[nb_option_roms] = strdup(buf);
7462 nb_option_roms++;
7463 break;
7466 if (i == nb_nics) {
7467 fprintf(stderr, "No valid PXE rom found for network device\n");
7468 exit(1);
7470 boot_device = 'c'; /* to prevent confusion by the BIOS */
7472 #endif
7474 /* init the memory */
7475 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7477 phys_ram_base = qemu_vmalloc(phys_ram_size);
7478 if (!phys_ram_base) {
7479 fprintf(stderr, "Could not allocate physical memory\n");
7480 exit(1);
7483 /* we always create the cdrom drive, even if no disk is there */
7484 bdrv_init();
7485 if (cdrom_index >= 0) {
7486 bs_table[cdrom_index] = bdrv_new("cdrom");
7487 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7490 /* open the virtual block devices */
7491 for(i = 0; i < MAX_DISKS; i++) {
7492 if (hd_filename[i]) {
7493 if (!bs_table[i]) {
7494 char buf[64];
7495 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7496 bs_table[i] = bdrv_new(buf);
7498 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7499 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7500 hd_filename[i]);
7501 exit(1);
7503 if (i == 0 && cyls != 0) {
7504 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7505 bdrv_set_translation_hint(bs_table[i], translation);
7510 /* we always create at least one floppy disk */
7511 fd_table[0] = bdrv_new("fda");
7512 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7514 for(i = 0; i < MAX_FD; i++) {
7515 if (fd_filename[i]) {
7516 if (!fd_table[i]) {
7517 char buf[64];
7518 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7519 fd_table[i] = bdrv_new(buf);
7520 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7522 if (fd_filename[i] != '\0') {
7523 if (bdrv_open(fd_table[i], fd_filename[i],
7524 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7525 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7526 fd_filename[i]);
7527 exit(1);
7533 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7534 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7536 init_ioports();
7538 /* terminal init */
7539 if (nographic) {
7540 dumb_display_init(ds);
7541 } else if (vnc_display != NULL) {
7542 vnc_display_init(ds, vnc_display);
7543 } else {
7544 #if defined(CONFIG_SDL)
7545 sdl_display_init(ds, full_screen, no_frame);
7546 #elif defined(CONFIG_COCOA)
7547 cocoa_display_init(ds, full_screen);
7548 #else
7549 dumb_display_init(ds);
7550 #endif
7553 /* Maintain compatibility with multiple stdio monitors */
7554 if (!strcmp(monitor_device,"stdio")) {
7555 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7556 if (!strcmp(serial_devices[i],"mon:stdio")) {
7557 monitor_device[0] = '\0';
7558 break;
7559 } else if (!strcmp(serial_devices[i],"stdio")) {
7560 monitor_device[0] = '\0';
7561 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7562 break;
7566 if (monitor_device[0] != '\0') {
7567 monitor_hd = qemu_chr_open(monitor_device);
7568 if (!monitor_hd) {
7569 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7570 exit(1);
7572 monitor_init(monitor_hd, !nographic);
7575 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7576 const char *devname = serial_devices[i];
7577 if (devname[0] != '\0' && strcmp(devname, "none")) {
7578 serial_hds[i] = qemu_chr_open(devname);
7579 if (!serial_hds[i]) {
7580 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7581 devname);
7582 exit(1);
7584 if (!strcmp(devname, "vc"))
7585 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7589 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7590 const char *devname = parallel_devices[i];
7591 if (devname[0] != '\0' && strcmp(devname, "none")) {
7592 parallel_hds[i] = qemu_chr_open(devname);
7593 if (!parallel_hds[i]) {
7594 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7595 devname);
7596 exit(1);
7598 if (!strcmp(devname, "vc"))
7599 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7603 machine->init(ram_size, vga_ram_size, boot_device,
7604 ds, fd_filename, snapshot,
7605 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7607 /* init USB devices */
7608 if (usb_enabled) {
7609 for(i = 0; i < usb_devices_index; i++) {
7610 if (usb_device_add(usb_devices[i]) < 0) {
7611 fprintf(stderr, "Warning: could not add USB device %s\n",
7612 usb_devices[i]);
7617 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7618 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7620 #ifdef CONFIG_GDBSTUB
7621 if (use_gdbstub) {
7622 /* XXX: use standard host:port notation and modify options
7623 accordingly. */
7624 if (gdbserver_start(gdbstub_port) < 0) {
7625 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7626 gdbstub_port);
7627 exit(1);
7629 } else
7630 #endif
7631 if (loadvm)
7632 do_loadvm(loadvm);
7635 /* XXX: simplify init */
7636 read_passwords();
7637 if (autostart) {
7638 vm_start();
7642 if (daemonize) {
7643 uint8_t status = 0;
7644 ssize_t len;
7645 int fd;
7647 again1:
7648 len = write(fds[1], &status, 1);
7649 if (len == -1 && (errno == EINTR))
7650 goto again1;
7652 if (len != 1)
7653 exit(1);
7655 fd = open("/dev/null", O_RDWR);
7656 if (fd == -1)
7657 exit(1);
7659 dup2(fd, 0);
7660 dup2(fd, 1);
7661 dup2(fd, 2);
7663 close(fd);
7666 main_loop();
7667 quit_timers();
7668 return 0;