Report unassigned memory access to CPU (not enabled yet)
[qemu/mini2440.git] / vl.c
blob2a864ba871acdd6f97de781e1d3cf476bfedc5a7
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
59 #else
60 #include <sys/stat.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
71 #include <net/if.h>
72 #include <syslog.h>
73 #include <stropts.h>
74 #endif
75 #endif
76 #endif
78 #if defined(CONFIG_SLIRP)
79 #include "libslirp.h"
80 #endif
82 #ifdef _WIN32
83 #include <malloc.h>
84 #include <sys/timeb.h>
85 #include <windows.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
88 #endif
90 #include "qemu_socket.h"
92 #ifdef CONFIG_SDL
93 #ifdef __APPLE__
94 #include <SDL/SDL.h>
95 #endif
96 #endif /* CONFIG_SDL */
98 #ifdef CONFIG_COCOA
99 #undef main
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
103 #include "disas.h"
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108 #ifdef __sun__
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110 #else
111 #define SMBD_COMMAND "/usr/sbin/smbd"
112 #endif
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
119 #ifdef TARGET_PPC
120 #define DEFAULT_RAM_SIZE 144
121 #else
122 #define DEFAULT_RAM_SIZE 128
123 #endif
124 /* in ms */
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141 BlockDriverState *pflash_table[MAX_PFLASH];
142 BlockDriverState *sd_bdrv;
143 BlockDriverState *mtd_bdrv;
144 /* point to the block driver where the snapshots are managed */
145 BlockDriverState *bs_snapshots;
146 int vga_ram_size;
147 static DisplayState display_state;
148 int nographic;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 int boot_device = 'c';
152 int ram_size;
153 int pit_min_timer_count = 0;
154 int nb_nics;
155 NICInfo nd_table[MAX_NICS];
156 QEMUTimer *gui_timer;
157 int vm_running;
158 int rtc_utc = 1;
159 int cirrus_vga_enabled = 1;
160 int vmsvga_enabled = 0;
161 #ifdef TARGET_SPARC
162 int graphic_width = 1024;
163 int graphic_height = 768;
164 int graphic_depth = 8;
165 #else
166 int graphic_width = 800;
167 int graphic_height = 600;
168 int graphic_depth = 15;
169 #endif
170 int full_screen = 0;
171 int no_frame = 0;
172 int no_quit = 0;
173 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
174 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
175 #ifdef TARGET_I386
176 int win2k_install_hack = 0;
177 #endif
178 int usb_enabled = 0;
179 static VLANState *first_vlan;
180 int smp_cpus = 1;
181 const char *vnc_display;
182 #if defined(TARGET_SPARC)
183 #define MAX_CPUS 16
184 #elif defined(TARGET_I386)
185 #define MAX_CPUS 255
186 #else
187 #define MAX_CPUS 1
188 #endif
189 int acpi_enabled = 1;
190 int fd_bootchk = 1;
191 int no_reboot = 0;
192 int cursor_hide = 1;
193 int graphic_rotate = 0;
194 int daemonize = 0;
195 const char *option_rom[MAX_OPTION_ROMS];
196 int nb_option_roms;
197 int semihosting_enabled = 0;
198 int autostart = 1;
199 const char *qemu_name;
200 #ifdef TARGET_SPARC
201 unsigned int nb_prom_envs = 0;
202 const char *prom_envs[MAX_PROM_ENVS];
203 #endif
205 /***********************************************************/
206 /* x86 ISA bus support */
208 target_phys_addr_t isa_mem_base = 0;
209 PicState2 *isa_pic;
211 uint32_t default_ioport_readb(void *opaque, uint32_t address)
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "unused inb: port=0x%04x\n", address);
215 #endif
216 return 0xff;
219 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
223 #endif
226 /* default is to make two byte accesses */
227 uint32_t default_ioport_readw(void *opaque, uint32_t address)
229 uint32_t data;
230 data = ioport_read_table[0][address](ioport_opaque[address], address);
231 address = (address + 1) & (MAX_IOPORTS - 1);
232 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
233 return data;
236 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
238 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
239 address = (address + 1) & (MAX_IOPORTS - 1);
240 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
243 uint32_t default_ioport_readl(void *opaque, uint32_t address)
245 #ifdef DEBUG_UNUSED_IOPORT
246 fprintf(stderr, "unused inl: port=0x%04x\n", address);
247 #endif
248 return 0xffffffff;
251 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
255 #endif
258 void init_ioports(void)
260 int i;
262 for(i = 0; i < MAX_IOPORTS; i++) {
263 ioport_read_table[0][i] = default_ioport_readb;
264 ioport_write_table[0][i] = default_ioport_writeb;
265 ioport_read_table[1][i] = default_ioport_readw;
266 ioport_write_table[1][i] = default_ioport_writew;
267 ioport_read_table[2][i] = default_ioport_readl;
268 ioport_write_table[2][i] = default_ioport_writel;
272 /* size is the word size in byte */
273 int register_ioport_read(int start, int length, int size,
274 IOPortReadFunc *func, void *opaque)
276 int i, bsize;
278 if (size == 1) {
279 bsize = 0;
280 } else if (size == 2) {
281 bsize = 1;
282 } else if (size == 4) {
283 bsize = 2;
284 } else {
285 hw_error("register_ioport_read: invalid size");
286 return -1;
288 for(i = start; i < start + length; i += size) {
289 ioport_read_table[bsize][i] = func;
290 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
291 hw_error("register_ioport_read: invalid opaque");
292 ioport_opaque[i] = opaque;
294 return 0;
297 /* size is the word size in byte */
298 int register_ioport_write(int start, int length, int size,
299 IOPortWriteFunc *func, void *opaque)
301 int i, bsize;
303 if (size == 1) {
304 bsize = 0;
305 } else if (size == 2) {
306 bsize = 1;
307 } else if (size == 4) {
308 bsize = 2;
309 } else {
310 hw_error("register_ioport_write: invalid size");
311 return -1;
313 for(i = start; i < start + length; i += size) {
314 ioport_write_table[bsize][i] = func;
315 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
316 hw_error("register_ioport_write: invalid opaque");
317 ioport_opaque[i] = opaque;
319 return 0;
322 void isa_unassign_ioport(int start, int length)
324 int i;
326 for(i = start; i < start + length; i++) {
327 ioport_read_table[0][i] = default_ioport_readb;
328 ioport_read_table[1][i] = default_ioport_readw;
329 ioport_read_table[2][i] = default_ioport_readl;
331 ioport_write_table[0][i] = default_ioport_writeb;
332 ioport_write_table[1][i] = default_ioport_writew;
333 ioport_write_table[2][i] = default_ioport_writel;
337 /***********************************************************/
339 void cpu_outb(CPUState *env, int addr, int val)
341 #ifdef DEBUG_IOPORT
342 if (loglevel & CPU_LOG_IOPORT)
343 fprintf(logfile, "outb: %04x %02x\n", addr, val);
344 #endif
345 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
346 #ifdef USE_KQEMU
347 if (env)
348 env->last_io_time = cpu_get_time_fast();
349 #endif
352 void cpu_outw(CPUState *env, int addr, int val)
354 #ifdef DEBUG_IOPORT
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "outw: %04x %04x\n", addr, val);
357 #endif
358 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
359 #ifdef USE_KQEMU
360 if (env)
361 env->last_io_time = cpu_get_time_fast();
362 #endif
365 void cpu_outl(CPUState *env, int addr, int val)
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outl: %04x %08x\n", addr, val);
370 #endif
371 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
372 #ifdef USE_KQEMU
373 if (env)
374 env->last_io_time = cpu_get_time_fast();
375 #endif
378 int cpu_inb(CPUState *env, int addr)
380 int val;
381 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inb : %04x %02x\n", addr, val);
385 #endif
386 #ifdef USE_KQEMU
387 if (env)
388 env->last_io_time = cpu_get_time_fast();
389 #endif
390 return val;
393 int cpu_inw(CPUState *env, int addr)
395 int val;
396 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
397 #ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inw : %04x %04x\n", addr, val);
400 #endif
401 #ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
404 #endif
405 return val;
408 int cpu_inl(CPUState *env, int addr)
410 int val;
411 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inl : %04x %08x\n", addr, val);
415 #endif
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
420 return val;
423 /***********************************************************/
424 void hw_error(const char *fmt, ...)
426 va_list ap;
427 CPUState *env;
429 va_start(ap, fmt);
430 fprintf(stderr, "qemu: hardware error: ");
431 vfprintf(stderr, fmt, ap);
432 fprintf(stderr, "\n");
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 #ifdef TARGET_I386
436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 #else
438 cpu_dump_state(env, stderr, fprintf, 0);
439 #endif
441 va_end(ap);
442 abort();
445 /***********************************************************/
446 /* keyboard/mouse */
448 static QEMUPutKBDEvent *qemu_put_kbd_event;
449 static void *qemu_put_kbd_event_opaque;
450 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
451 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
453 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
455 qemu_put_kbd_event_opaque = opaque;
456 qemu_put_kbd_event = func;
459 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
460 void *opaque, int absolute,
461 const char *name)
463 QEMUPutMouseEntry *s, *cursor;
465 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
466 if (!s)
467 return NULL;
469 s->qemu_put_mouse_event = func;
470 s->qemu_put_mouse_event_opaque = opaque;
471 s->qemu_put_mouse_event_absolute = absolute;
472 s->qemu_put_mouse_event_name = qemu_strdup(name);
473 s->next = NULL;
475 if (!qemu_put_mouse_event_head) {
476 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
477 return s;
480 cursor = qemu_put_mouse_event_head;
481 while (cursor->next != NULL)
482 cursor = cursor->next;
484 cursor->next = s;
485 qemu_put_mouse_event_current = s;
487 return s;
490 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
492 QEMUPutMouseEntry *prev = NULL, *cursor;
494 if (!qemu_put_mouse_event_head || entry == NULL)
495 return;
497 cursor = qemu_put_mouse_event_head;
498 while (cursor != NULL && cursor != entry) {
499 prev = cursor;
500 cursor = cursor->next;
503 if (cursor == NULL) // does not exist or list empty
504 return;
505 else if (prev == NULL) { // entry is head
506 qemu_put_mouse_event_head = cursor->next;
507 if (qemu_put_mouse_event_current == entry)
508 qemu_put_mouse_event_current = cursor->next;
509 qemu_free(entry->qemu_put_mouse_event_name);
510 qemu_free(entry);
511 return;
514 prev->next = entry->next;
516 if (qemu_put_mouse_event_current == entry)
517 qemu_put_mouse_event_current = prev;
519 qemu_free(entry->qemu_put_mouse_event_name);
520 qemu_free(entry);
523 void kbd_put_keycode(int keycode)
525 if (qemu_put_kbd_event) {
526 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
530 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
532 QEMUPutMouseEvent *mouse_event;
533 void *mouse_event_opaque;
534 int width;
536 if (!qemu_put_mouse_event_current) {
537 return;
540 mouse_event =
541 qemu_put_mouse_event_current->qemu_put_mouse_event;
542 mouse_event_opaque =
543 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
545 if (mouse_event) {
546 if (graphic_rotate) {
547 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
548 width = 0x7fff;
549 else
550 width = graphic_width;
551 mouse_event(mouse_event_opaque,
552 width - dy, dx, dz, buttons_state);
553 } else
554 mouse_event(mouse_event_opaque,
555 dx, dy, dz, buttons_state);
559 int kbd_mouse_is_absolute(void)
561 if (!qemu_put_mouse_event_current)
562 return 0;
564 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
567 void do_info_mice(void)
569 QEMUPutMouseEntry *cursor;
570 int index = 0;
572 if (!qemu_put_mouse_event_head) {
573 term_printf("No mouse devices connected\n");
574 return;
577 term_printf("Mouse devices available:\n");
578 cursor = qemu_put_mouse_event_head;
579 while (cursor != NULL) {
580 term_printf("%c Mouse #%d: %s\n",
581 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
582 index, cursor->qemu_put_mouse_event_name);
583 index++;
584 cursor = cursor->next;
588 void do_mouse_set(int index)
590 QEMUPutMouseEntry *cursor;
591 int i = 0;
593 if (!qemu_put_mouse_event_head) {
594 term_printf("No mouse devices connected\n");
595 return;
598 cursor = qemu_put_mouse_event_head;
599 while (cursor != NULL && index != i) {
600 i++;
601 cursor = cursor->next;
604 if (cursor != NULL)
605 qemu_put_mouse_event_current = cursor;
606 else
607 term_printf("Mouse at given index not found\n");
610 /* compute with 96 bit intermediate result: (a*b)/c */
611 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
613 union {
614 uint64_t ll;
615 struct {
616 #ifdef WORDS_BIGENDIAN
617 uint32_t high, low;
618 #else
619 uint32_t low, high;
620 #endif
621 } l;
622 } u, res;
623 uint64_t rl, rh;
625 u.ll = a;
626 rl = (uint64_t)u.l.low * (uint64_t)b;
627 rh = (uint64_t)u.l.high * (uint64_t)b;
628 rh += (rl >> 32);
629 res.l.high = rh / c;
630 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
631 return res.ll;
634 /***********************************************************/
635 /* real time host monotonic timer */
637 #define QEMU_TIMER_BASE 1000000000LL
639 #ifdef WIN32
641 static int64_t clock_freq;
643 static void init_get_clock(void)
645 LARGE_INTEGER freq;
646 int ret;
647 ret = QueryPerformanceFrequency(&freq);
648 if (ret == 0) {
649 fprintf(stderr, "Could not calibrate ticks\n");
650 exit(1);
652 clock_freq = freq.QuadPart;
655 static int64_t get_clock(void)
657 LARGE_INTEGER ti;
658 QueryPerformanceCounter(&ti);
659 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
662 #else
664 static int use_rt_clock;
666 static void init_get_clock(void)
668 use_rt_clock = 0;
669 #if defined(__linux__)
671 struct timespec ts;
672 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
673 use_rt_clock = 1;
676 #endif
679 static int64_t get_clock(void)
681 #if defined(__linux__)
682 if (use_rt_clock) {
683 struct timespec ts;
684 clock_gettime(CLOCK_MONOTONIC, &ts);
685 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
686 } else
687 #endif
689 /* XXX: using gettimeofday leads to problems if the date
690 changes, so it should be avoided. */
691 struct timeval tv;
692 gettimeofday(&tv, NULL);
693 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
697 #endif
699 /***********************************************************/
700 /* guest cycle counter */
702 static int64_t cpu_ticks_prev;
703 static int64_t cpu_ticks_offset;
704 static int64_t cpu_clock_offset;
705 static int cpu_ticks_enabled;
707 /* return the host CPU cycle counter and handle stop/restart */
708 int64_t cpu_get_ticks(void)
710 if (!cpu_ticks_enabled) {
711 return cpu_ticks_offset;
712 } else {
713 int64_t ticks;
714 ticks = cpu_get_real_ticks();
715 if (cpu_ticks_prev > ticks) {
716 /* Note: non increasing ticks may happen if the host uses
717 software suspend */
718 cpu_ticks_offset += cpu_ticks_prev - ticks;
720 cpu_ticks_prev = ticks;
721 return ticks + cpu_ticks_offset;
725 /* return the host CPU monotonic timer and handle stop/restart */
726 static int64_t cpu_get_clock(void)
728 int64_t ti;
729 if (!cpu_ticks_enabled) {
730 return cpu_clock_offset;
731 } else {
732 ti = get_clock();
733 return ti + cpu_clock_offset;
737 /* enable cpu_get_ticks() */
738 void cpu_enable_ticks(void)
740 if (!cpu_ticks_enabled) {
741 cpu_ticks_offset -= cpu_get_real_ticks();
742 cpu_clock_offset -= get_clock();
743 cpu_ticks_enabled = 1;
747 /* disable cpu_get_ticks() : the clock is stopped. You must not call
748 cpu_get_ticks() after that. */
749 void cpu_disable_ticks(void)
751 if (cpu_ticks_enabled) {
752 cpu_ticks_offset = cpu_get_ticks();
753 cpu_clock_offset = cpu_get_clock();
754 cpu_ticks_enabled = 0;
758 /***********************************************************/
759 /* timers */
761 #define QEMU_TIMER_REALTIME 0
762 #define QEMU_TIMER_VIRTUAL 1
764 struct QEMUClock {
765 int type;
766 /* XXX: add frequency */
769 struct QEMUTimer {
770 QEMUClock *clock;
771 int64_t expire_time;
772 QEMUTimerCB *cb;
773 void *opaque;
774 struct QEMUTimer *next;
777 QEMUClock *rt_clock;
778 QEMUClock *vm_clock;
780 static QEMUTimer *active_timers[2];
781 #ifdef _WIN32
782 static MMRESULT timerID;
783 static HANDLE host_alarm = NULL;
784 static unsigned int period = 1;
785 #else
786 /* frequency of the times() clock tick */
787 static int timer_freq;
788 #endif
790 QEMUClock *qemu_new_clock(int type)
792 QEMUClock *clock;
793 clock = qemu_mallocz(sizeof(QEMUClock));
794 if (!clock)
795 return NULL;
796 clock->type = type;
797 return clock;
800 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
802 QEMUTimer *ts;
804 ts = qemu_mallocz(sizeof(QEMUTimer));
805 ts->clock = clock;
806 ts->cb = cb;
807 ts->opaque = opaque;
808 return ts;
811 void qemu_free_timer(QEMUTimer *ts)
813 qemu_free(ts);
816 /* stop a timer, but do not dealloc it */
817 void qemu_del_timer(QEMUTimer *ts)
819 QEMUTimer **pt, *t;
821 /* NOTE: this code must be signal safe because
822 qemu_timer_expired() can be called from a signal. */
823 pt = &active_timers[ts->clock->type];
824 for(;;) {
825 t = *pt;
826 if (!t)
827 break;
828 if (t == ts) {
829 *pt = t->next;
830 break;
832 pt = &t->next;
836 /* modify the current timer so that it will be fired when current_time
837 >= expire_time. The corresponding callback will be called. */
838 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
840 QEMUTimer **pt, *t;
842 qemu_del_timer(ts);
844 /* add the timer in the sorted list */
845 /* NOTE: this code must be signal safe because
846 qemu_timer_expired() can be called from a signal. */
847 pt = &active_timers[ts->clock->type];
848 for(;;) {
849 t = *pt;
850 if (!t)
851 break;
852 if (t->expire_time > expire_time)
853 break;
854 pt = &t->next;
856 ts->expire_time = expire_time;
857 ts->next = *pt;
858 *pt = ts;
861 int qemu_timer_pending(QEMUTimer *ts)
863 QEMUTimer *t;
864 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
865 if (t == ts)
866 return 1;
868 return 0;
871 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
873 if (!timer_head)
874 return 0;
875 return (timer_head->expire_time <= current_time);
878 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
880 QEMUTimer *ts;
882 for(;;) {
883 ts = *ptimer_head;
884 if (!ts || ts->expire_time > current_time)
885 break;
886 /* remove timer from the list before calling the callback */
887 *ptimer_head = ts->next;
888 ts->next = NULL;
890 /* run the callback (the timer list can be modified) */
891 ts->cb(ts->opaque);
895 int64_t qemu_get_clock(QEMUClock *clock)
897 switch(clock->type) {
898 case QEMU_TIMER_REALTIME:
899 return get_clock() / 1000000;
900 default:
901 case QEMU_TIMER_VIRTUAL:
902 return cpu_get_clock();
906 static void init_timers(void)
908 init_get_clock();
909 ticks_per_sec = QEMU_TIMER_BASE;
910 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
911 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
914 /* save a timer */
915 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
917 uint64_t expire_time;
919 if (qemu_timer_pending(ts)) {
920 expire_time = ts->expire_time;
921 } else {
922 expire_time = -1;
924 qemu_put_be64(f, expire_time);
927 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
929 uint64_t expire_time;
931 expire_time = qemu_get_be64(f);
932 if (expire_time != -1) {
933 qemu_mod_timer(ts, expire_time);
934 } else {
935 qemu_del_timer(ts);
939 static void timer_save(QEMUFile *f, void *opaque)
941 if (cpu_ticks_enabled) {
942 hw_error("cannot save state if virtual timers are running");
944 qemu_put_be64s(f, &cpu_ticks_offset);
945 qemu_put_be64s(f, &ticks_per_sec);
946 qemu_put_be64s(f, &cpu_clock_offset);
949 static int timer_load(QEMUFile *f, void *opaque, int version_id)
951 if (version_id != 1 && version_id != 2)
952 return -EINVAL;
953 if (cpu_ticks_enabled) {
954 return -EINVAL;
956 qemu_get_be64s(f, &cpu_ticks_offset);
957 qemu_get_be64s(f, &ticks_per_sec);
958 if (version_id == 2) {
959 qemu_get_be64s(f, &cpu_clock_offset);
961 return 0;
964 #ifdef _WIN32
965 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
966 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
967 #else
968 static void host_alarm_handler(int host_signum)
969 #endif
971 #if 0
972 #define DISP_FREQ 1000
974 static int64_t delta_min = INT64_MAX;
975 static int64_t delta_max, delta_cum, last_clock, delta, ti;
976 static int count;
977 ti = qemu_get_clock(vm_clock);
978 if (last_clock != 0) {
979 delta = ti - last_clock;
980 if (delta < delta_min)
981 delta_min = delta;
982 if (delta > delta_max)
983 delta_max = delta;
984 delta_cum += delta;
985 if (++count == DISP_FREQ) {
986 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
987 muldiv64(delta_min, 1000000, ticks_per_sec),
988 muldiv64(delta_max, 1000000, ticks_per_sec),
989 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
990 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
991 count = 0;
992 delta_min = INT64_MAX;
993 delta_max = 0;
994 delta_cum = 0;
997 last_clock = ti;
999 #endif
1000 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1001 qemu_get_clock(vm_clock)) ||
1002 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1003 qemu_get_clock(rt_clock))) {
1004 #ifdef _WIN32
1005 SetEvent(host_alarm);
1006 #endif
1007 CPUState *env = cpu_single_env;
1008 if (env) {
1009 /* stop the currently executing cpu because a timer occured */
1010 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1011 #ifdef USE_KQEMU
1012 if (env->kqemu_enabled) {
1013 kqemu_cpu_interrupt(env);
1015 #endif
1020 #ifndef _WIN32
1022 #if defined(__linux__)
1024 #define RTC_FREQ 1024
1026 static int rtc_fd;
1028 static int start_rtc_timer(void)
1030 rtc_fd = open("/dev/rtc", O_RDONLY);
1031 if (rtc_fd < 0)
1032 return -1;
1033 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1034 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1035 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1036 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1037 goto fail;
1039 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1040 fail:
1041 close(rtc_fd);
1042 return -1;
1044 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1045 return 0;
1048 #else
1050 static int start_rtc_timer(void)
1052 return -1;
1055 #endif /* !defined(__linux__) */
1057 #endif /* !defined(_WIN32) */
1059 static void init_timer_alarm(void)
1061 #ifdef _WIN32
1063 int count=0;
1064 TIMECAPS tc;
1066 ZeroMemory(&tc, sizeof(TIMECAPS));
1067 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1068 if (period < tc.wPeriodMin)
1069 period = tc.wPeriodMin;
1070 timeBeginPeriod(period);
1071 timerID = timeSetEvent(1, // interval (ms)
1072 period, // resolution
1073 host_alarm_handler, // function
1074 (DWORD)&count, // user parameter
1075 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1076 if( !timerID ) {
1077 perror("failed timer alarm");
1078 exit(1);
1080 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1081 if (!host_alarm) {
1082 perror("failed CreateEvent");
1083 exit(1);
1085 qemu_add_wait_object(host_alarm, NULL, NULL);
1087 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1088 #else
1090 struct sigaction act;
1091 struct itimerval itv;
1093 /* get times() syscall frequency */
1094 timer_freq = sysconf(_SC_CLK_TCK);
1096 /* timer signal */
1097 sigfillset(&act.sa_mask);
1098 act.sa_flags = 0;
1099 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1100 act.sa_flags |= SA_ONSTACK;
1101 #endif
1102 act.sa_handler = host_alarm_handler;
1103 sigaction(SIGALRM, &act, NULL);
1105 itv.it_interval.tv_sec = 0;
1106 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1107 itv.it_value.tv_sec = 0;
1108 itv.it_value.tv_usec = 10 * 1000;
1109 setitimer(ITIMER_REAL, &itv, NULL);
1110 /* we probe the tick duration of the kernel to inform the user if
1111 the emulated kernel requested a too high timer frequency */
1112 getitimer(ITIMER_REAL, &itv);
1114 #if defined(__linux__)
1115 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1116 have timers with 1 ms resolution. The correct solution will
1117 be to use the POSIX real time timers available in recent
1118 2.6 kernels */
1119 if (itv.it_interval.tv_usec > 1000 || 1) {
1120 /* try to use /dev/rtc to have a faster timer */
1121 if (start_rtc_timer() < 0)
1122 goto use_itimer;
1123 /* disable itimer */
1124 itv.it_interval.tv_sec = 0;
1125 itv.it_interval.tv_usec = 0;
1126 itv.it_value.tv_sec = 0;
1127 itv.it_value.tv_usec = 0;
1128 setitimer(ITIMER_REAL, &itv, NULL);
1130 /* use the RTC */
1131 sigaction(SIGIO, &act, NULL);
1132 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1133 fcntl(rtc_fd, F_SETOWN, getpid());
1134 } else
1135 #endif /* defined(__linux__) */
1137 use_itimer:
1138 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1139 PIT_FREQ) / 1000000;
1142 #endif
1145 void quit_timers(void)
1147 #ifdef _WIN32
1148 timeKillEvent(timerID);
1149 timeEndPeriod(period);
1150 if (host_alarm) {
1151 CloseHandle(host_alarm);
1152 host_alarm = NULL;
1154 #endif
1157 /***********************************************************/
1158 /* character device */
1160 static void qemu_chr_event(CharDriverState *s, int event)
1162 if (!s->chr_event)
1163 return;
1164 s->chr_event(s->handler_opaque, event);
1167 static void qemu_chr_reset_bh(void *opaque)
1169 CharDriverState *s = opaque;
1170 qemu_chr_event(s, CHR_EVENT_RESET);
1171 qemu_bh_delete(s->bh);
1172 s->bh = NULL;
1175 void qemu_chr_reset(CharDriverState *s)
1177 if (s->bh == NULL) {
1178 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1179 qemu_bh_schedule(s->bh);
1183 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1185 return s->chr_write(s, buf, len);
1188 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1190 if (!s->chr_ioctl)
1191 return -ENOTSUP;
1192 return s->chr_ioctl(s, cmd, arg);
1195 int qemu_chr_can_read(CharDriverState *s)
1197 if (!s->chr_can_read)
1198 return 0;
1199 return s->chr_can_read(s->handler_opaque);
1202 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1204 s->chr_read(s->handler_opaque, buf, len);
1208 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1210 char buf[4096];
1211 va_list ap;
1212 va_start(ap, fmt);
1213 vsnprintf(buf, sizeof(buf), fmt, ap);
1214 qemu_chr_write(s, buf, strlen(buf));
1215 va_end(ap);
1218 void qemu_chr_send_event(CharDriverState *s, int event)
1220 if (s->chr_send_event)
1221 s->chr_send_event(s, event);
1224 void qemu_chr_add_handlers(CharDriverState *s,
1225 IOCanRWHandler *fd_can_read,
1226 IOReadHandler *fd_read,
1227 IOEventHandler *fd_event,
1228 void *opaque)
1230 s->chr_can_read = fd_can_read;
1231 s->chr_read = fd_read;
1232 s->chr_event = fd_event;
1233 s->handler_opaque = opaque;
1234 if (s->chr_update_read_handler)
1235 s->chr_update_read_handler(s);
1238 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1240 return len;
1243 static CharDriverState *qemu_chr_open_null(void)
1245 CharDriverState *chr;
1247 chr = qemu_mallocz(sizeof(CharDriverState));
1248 if (!chr)
1249 return NULL;
1250 chr->chr_write = null_chr_write;
1251 return chr;
1254 /* MUX driver for serial I/O splitting */
1255 static int term_timestamps;
1256 static int64_t term_timestamps_start;
1257 #define MAX_MUX 4
1258 typedef struct {
1259 IOCanRWHandler *chr_can_read[MAX_MUX];
1260 IOReadHandler *chr_read[MAX_MUX];
1261 IOEventHandler *chr_event[MAX_MUX];
1262 void *ext_opaque[MAX_MUX];
1263 CharDriverState *drv;
1264 int mux_cnt;
1265 int term_got_escape;
1266 int max_size;
1267 } MuxDriver;
1270 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1272 MuxDriver *d = chr->opaque;
1273 int ret;
1274 if (!term_timestamps) {
1275 ret = d->drv->chr_write(d->drv, buf, len);
1276 } else {
1277 int i;
1279 ret = 0;
1280 for(i = 0; i < len; i++) {
1281 ret += d->drv->chr_write(d->drv, buf+i, 1);
1282 if (buf[i] == '\n') {
1283 char buf1[64];
1284 int64_t ti;
1285 int secs;
1287 ti = get_clock();
1288 if (term_timestamps_start == -1)
1289 term_timestamps_start = ti;
1290 ti -= term_timestamps_start;
1291 secs = ti / 1000000000;
1292 snprintf(buf1, sizeof(buf1),
1293 "[%02d:%02d:%02d.%03d] ",
1294 secs / 3600,
1295 (secs / 60) % 60,
1296 secs % 60,
1297 (int)((ti / 1000000) % 1000));
1298 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1302 return ret;
1305 static char *mux_help[] = {
1306 "% h print this help\n\r",
1307 "% x exit emulator\n\r",
1308 "% s save disk data back to file (if -snapshot)\n\r",
1309 "% t toggle console timestamps\n\r"
1310 "% b send break (magic sysrq)\n\r",
1311 "% c switch between console and monitor\n\r",
1312 "% % sends %\n\r",
1313 NULL
1316 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1317 static void mux_print_help(CharDriverState *chr)
1319 int i, j;
1320 char ebuf[15] = "Escape-Char";
1321 char cbuf[50] = "\n\r";
1323 if (term_escape_char > 0 && term_escape_char < 26) {
1324 sprintf(cbuf,"\n\r");
1325 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1326 } else {
1327 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1329 chr->chr_write(chr, cbuf, strlen(cbuf));
1330 for (i = 0; mux_help[i] != NULL; i++) {
1331 for (j=0; mux_help[i][j] != '\0'; j++) {
1332 if (mux_help[i][j] == '%')
1333 chr->chr_write(chr, ebuf, strlen(ebuf));
1334 else
1335 chr->chr_write(chr, &mux_help[i][j], 1);
1340 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1342 if (d->term_got_escape) {
1343 d->term_got_escape = 0;
1344 if (ch == term_escape_char)
1345 goto send_char;
1346 switch(ch) {
1347 case '?':
1348 case 'h':
1349 mux_print_help(chr);
1350 break;
1351 case 'x':
1353 char *term = "QEMU: Terminated\n\r";
1354 chr->chr_write(chr,term,strlen(term));
1355 exit(0);
1356 break;
1358 case 's':
1360 int i;
1361 for (i = 0; i < MAX_DISKS; i++) {
1362 if (bs_table[i])
1363 bdrv_commit(bs_table[i]);
1366 break;
1367 case 'b':
1368 if (chr->chr_event)
1369 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1370 break;
1371 case 'c':
1372 /* Switch to the next registered device */
1373 chr->focus++;
1374 if (chr->focus >= d->mux_cnt)
1375 chr->focus = 0;
1376 break;
1377 case 't':
1378 term_timestamps = !term_timestamps;
1379 term_timestamps_start = -1;
1380 break;
1382 } else if (ch == term_escape_char) {
1383 d->term_got_escape = 1;
1384 } else {
1385 send_char:
1386 return 1;
1388 return 0;
1391 static int mux_chr_can_read(void *opaque)
1393 CharDriverState *chr = opaque;
1394 MuxDriver *d = chr->opaque;
1395 if (d->chr_can_read[chr->focus])
1396 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1397 return 0;
1400 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1402 CharDriverState *chr = opaque;
1403 MuxDriver *d = chr->opaque;
1404 int i;
1405 for(i = 0; i < size; i++)
1406 if (mux_proc_byte(chr, d, buf[i]))
1407 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1410 static void mux_chr_event(void *opaque, int event)
1412 CharDriverState *chr = opaque;
1413 MuxDriver *d = chr->opaque;
1414 int i;
1416 /* Send the event to all registered listeners */
1417 for (i = 0; i < d->mux_cnt; i++)
1418 if (d->chr_event[i])
1419 d->chr_event[i](d->ext_opaque[i], event);
1422 static void mux_chr_update_read_handler(CharDriverState *chr)
1424 MuxDriver *d = chr->opaque;
1426 if (d->mux_cnt >= MAX_MUX) {
1427 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1428 return;
1430 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1431 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1432 d->chr_read[d->mux_cnt] = chr->chr_read;
1433 d->chr_event[d->mux_cnt] = chr->chr_event;
1434 /* Fix up the real driver with mux routines */
1435 if (d->mux_cnt == 0) {
1436 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1437 mux_chr_event, chr);
1439 chr->focus = d->mux_cnt;
1440 d->mux_cnt++;
1443 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1445 CharDriverState *chr;
1446 MuxDriver *d;
1448 chr = qemu_mallocz(sizeof(CharDriverState));
1449 if (!chr)
1450 return NULL;
1451 d = qemu_mallocz(sizeof(MuxDriver));
1452 if (!d) {
1453 free(chr);
1454 return NULL;
1457 chr->opaque = d;
1458 d->drv = drv;
1459 chr->focus = -1;
1460 chr->chr_write = mux_chr_write;
1461 chr->chr_update_read_handler = mux_chr_update_read_handler;
1462 return chr;
1466 #ifdef _WIN32
1468 static void socket_cleanup(void)
1470 WSACleanup();
1473 static int socket_init(void)
1475 WSADATA Data;
1476 int ret, err;
1478 ret = WSAStartup(MAKEWORD(2,2), &Data);
1479 if (ret != 0) {
1480 err = WSAGetLastError();
1481 fprintf(stderr, "WSAStartup: %d\n", err);
1482 return -1;
1484 atexit(socket_cleanup);
1485 return 0;
1488 static int send_all(int fd, const uint8_t *buf, int len1)
1490 int ret, len;
1492 len = len1;
1493 while (len > 0) {
1494 ret = send(fd, buf, len, 0);
1495 if (ret < 0) {
1496 int errno;
1497 errno = WSAGetLastError();
1498 if (errno != WSAEWOULDBLOCK) {
1499 return -1;
1501 } else if (ret == 0) {
1502 break;
1503 } else {
1504 buf += ret;
1505 len -= ret;
1508 return len1 - len;
1511 void socket_set_nonblock(int fd)
1513 unsigned long opt = 1;
1514 ioctlsocket(fd, FIONBIO, &opt);
1517 #else
1519 static int unix_write(int fd, const uint8_t *buf, int len1)
1521 int ret, len;
1523 len = len1;
1524 while (len > 0) {
1525 ret = write(fd, buf, len);
1526 if (ret < 0) {
1527 if (errno != EINTR && errno != EAGAIN)
1528 return -1;
1529 } else if (ret == 0) {
1530 break;
1531 } else {
1532 buf += ret;
1533 len -= ret;
1536 return len1 - len;
1539 static inline int send_all(int fd, const uint8_t *buf, int len1)
1541 return unix_write(fd, buf, len1);
1544 void socket_set_nonblock(int fd)
1546 fcntl(fd, F_SETFL, O_NONBLOCK);
1548 #endif /* !_WIN32 */
1550 #ifndef _WIN32
1552 typedef struct {
1553 int fd_in, fd_out;
1554 int max_size;
1555 } FDCharDriver;
1557 #define STDIO_MAX_CLIENTS 1
1558 static int stdio_nb_clients = 0;
1560 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1562 FDCharDriver *s = chr->opaque;
1563 return unix_write(s->fd_out, buf, len);
1566 static int fd_chr_read_poll(void *opaque)
1568 CharDriverState *chr = opaque;
1569 FDCharDriver *s = chr->opaque;
1571 s->max_size = qemu_chr_can_read(chr);
1572 return s->max_size;
1575 static void fd_chr_read(void *opaque)
1577 CharDriverState *chr = opaque;
1578 FDCharDriver *s = chr->opaque;
1579 int size, len;
1580 uint8_t buf[1024];
1582 len = sizeof(buf);
1583 if (len > s->max_size)
1584 len = s->max_size;
1585 if (len == 0)
1586 return;
1587 size = read(s->fd_in, buf, len);
1588 if (size == 0) {
1589 /* FD has been closed. Remove it from the active list. */
1590 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1591 return;
1593 if (size > 0) {
1594 qemu_chr_read(chr, buf, size);
1598 static void fd_chr_update_read_handler(CharDriverState *chr)
1600 FDCharDriver *s = chr->opaque;
1602 if (s->fd_in >= 0) {
1603 if (nographic && s->fd_in == 0) {
1604 } else {
1605 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1606 fd_chr_read, NULL, chr);
1611 /* open a character device to a unix fd */
1612 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1614 CharDriverState *chr;
1615 FDCharDriver *s;
1617 chr = qemu_mallocz(sizeof(CharDriverState));
1618 if (!chr)
1619 return NULL;
1620 s = qemu_mallocz(sizeof(FDCharDriver));
1621 if (!s) {
1622 free(chr);
1623 return NULL;
1625 s->fd_in = fd_in;
1626 s->fd_out = fd_out;
1627 chr->opaque = s;
1628 chr->chr_write = fd_chr_write;
1629 chr->chr_update_read_handler = fd_chr_update_read_handler;
1631 qemu_chr_reset(chr);
1633 return chr;
1636 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1638 int fd_out;
1640 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1641 if (fd_out < 0)
1642 return NULL;
1643 return qemu_chr_open_fd(-1, fd_out);
1646 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1648 int fd_in, fd_out;
1649 char filename_in[256], filename_out[256];
1651 snprintf(filename_in, 256, "%s.in", filename);
1652 snprintf(filename_out, 256, "%s.out", filename);
1653 fd_in = open(filename_in, O_RDWR | O_BINARY);
1654 fd_out = open(filename_out, O_RDWR | O_BINARY);
1655 if (fd_in < 0 || fd_out < 0) {
1656 if (fd_in >= 0)
1657 close(fd_in);
1658 if (fd_out >= 0)
1659 close(fd_out);
1660 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1661 if (fd_in < 0)
1662 return NULL;
1664 return qemu_chr_open_fd(fd_in, fd_out);
1668 /* for STDIO, we handle the case where several clients use it
1669 (nographic mode) */
1671 #define TERM_FIFO_MAX_SIZE 1
1673 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1674 static int term_fifo_size;
1676 static int stdio_read_poll(void *opaque)
1678 CharDriverState *chr = opaque;
1680 /* try to flush the queue if needed */
1681 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1682 qemu_chr_read(chr, term_fifo, 1);
1683 term_fifo_size = 0;
1685 /* see if we can absorb more chars */
1686 if (term_fifo_size == 0)
1687 return 1;
1688 else
1689 return 0;
1692 static void stdio_read(void *opaque)
1694 int size;
1695 uint8_t buf[1];
1696 CharDriverState *chr = opaque;
1698 size = read(0, buf, 1);
1699 if (size == 0) {
1700 /* stdin has been closed. Remove it from the active list. */
1701 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1702 return;
1704 if (size > 0) {
1705 if (qemu_chr_can_read(chr) > 0) {
1706 qemu_chr_read(chr, buf, 1);
1707 } else if (term_fifo_size == 0) {
1708 term_fifo[term_fifo_size++] = buf[0];
1713 /* init terminal so that we can grab keys */
1714 static struct termios oldtty;
1715 static int old_fd0_flags;
1717 static void term_exit(void)
1719 tcsetattr (0, TCSANOW, &oldtty);
1720 fcntl(0, F_SETFL, old_fd0_flags);
1723 static void term_init(void)
1725 struct termios tty;
1727 tcgetattr (0, &tty);
1728 oldtty = tty;
1729 old_fd0_flags = fcntl(0, F_GETFL);
1731 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1732 |INLCR|IGNCR|ICRNL|IXON);
1733 tty.c_oflag |= OPOST;
1734 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1735 /* if graphical mode, we allow Ctrl-C handling */
1736 if (nographic)
1737 tty.c_lflag &= ~ISIG;
1738 tty.c_cflag &= ~(CSIZE|PARENB);
1739 tty.c_cflag |= CS8;
1740 tty.c_cc[VMIN] = 1;
1741 tty.c_cc[VTIME] = 0;
1743 tcsetattr (0, TCSANOW, &tty);
1745 atexit(term_exit);
1747 fcntl(0, F_SETFL, O_NONBLOCK);
1750 static CharDriverState *qemu_chr_open_stdio(void)
1752 CharDriverState *chr;
1754 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1755 return NULL;
1756 chr = qemu_chr_open_fd(0, 1);
1757 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1758 stdio_nb_clients++;
1759 term_init();
1761 return chr;
1764 #if defined(__linux__)
1765 static CharDriverState *qemu_chr_open_pty(void)
1767 struct termios tty;
1768 char slave_name[1024];
1769 int master_fd, slave_fd;
1771 /* Not satisfying */
1772 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1773 return NULL;
1776 /* Disabling local echo and line-buffered output */
1777 tcgetattr (master_fd, &tty);
1778 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1779 tty.c_cc[VMIN] = 1;
1780 tty.c_cc[VTIME] = 0;
1781 tcsetattr (master_fd, TCSAFLUSH, &tty);
1783 fprintf(stderr, "char device redirected to %s\n", slave_name);
1784 return qemu_chr_open_fd(master_fd, master_fd);
1787 static void tty_serial_init(int fd, int speed,
1788 int parity, int data_bits, int stop_bits)
1790 struct termios tty;
1791 speed_t spd;
1793 #if 0
1794 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1795 speed, parity, data_bits, stop_bits);
1796 #endif
1797 tcgetattr (fd, &tty);
1799 switch(speed) {
1800 case 50:
1801 spd = B50;
1802 break;
1803 case 75:
1804 spd = B75;
1805 break;
1806 case 300:
1807 spd = B300;
1808 break;
1809 case 600:
1810 spd = B600;
1811 break;
1812 case 1200:
1813 spd = B1200;
1814 break;
1815 case 2400:
1816 spd = B2400;
1817 break;
1818 case 4800:
1819 spd = B4800;
1820 break;
1821 case 9600:
1822 spd = B9600;
1823 break;
1824 case 19200:
1825 spd = B19200;
1826 break;
1827 case 38400:
1828 spd = B38400;
1829 break;
1830 case 57600:
1831 spd = B57600;
1832 break;
1833 default:
1834 case 115200:
1835 spd = B115200;
1836 break;
1839 cfsetispeed(&tty, spd);
1840 cfsetospeed(&tty, spd);
1842 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1843 |INLCR|IGNCR|ICRNL|IXON);
1844 tty.c_oflag |= OPOST;
1845 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1846 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1847 switch(data_bits) {
1848 default:
1849 case 8:
1850 tty.c_cflag |= CS8;
1851 break;
1852 case 7:
1853 tty.c_cflag |= CS7;
1854 break;
1855 case 6:
1856 tty.c_cflag |= CS6;
1857 break;
1858 case 5:
1859 tty.c_cflag |= CS5;
1860 break;
1862 switch(parity) {
1863 default:
1864 case 'N':
1865 break;
1866 case 'E':
1867 tty.c_cflag |= PARENB;
1868 break;
1869 case 'O':
1870 tty.c_cflag |= PARENB | PARODD;
1871 break;
1873 if (stop_bits == 2)
1874 tty.c_cflag |= CSTOPB;
1876 tcsetattr (fd, TCSANOW, &tty);
1879 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1881 FDCharDriver *s = chr->opaque;
1883 switch(cmd) {
1884 case CHR_IOCTL_SERIAL_SET_PARAMS:
1886 QEMUSerialSetParams *ssp = arg;
1887 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1888 ssp->data_bits, ssp->stop_bits);
1890 break;
1891 case CHR_IOCTL_SERIAL_SET_BREAK:
1893 int enable = *(int *)arg;
1894 if (enable)
1895 tcsendbreak(s->fd_in, 1);
1897 break;
1898 default:
1899 return -ENOTSUP;
1901 return 0;
1904 static CharDriverState *qemu_chr_open_tty(const char *filename)
1906 CharDriverState *chr;
1907 int fd;
1909 fd = open(filename, O_RDWR | O_NONBLOCK);
1910 if (fd < 0)
1911 return NULL;
1912 fcntl(fd, F_SETFL, O_NONBLOCK);
1913 tty_serial_init(fd, 115200, 'N', 8, 1);
1914 chr = qemu_chr_open_fd(fd, fd);
1915 if (!chr)
1916 return NULL;
1917 chr->chr_ioctl = tty_serial_ioctl;
1918 qemu_chr_reset(chr);
1919 return chr;
1922 typedef struct {
1923 int fd;
1924 int mode;
1925 } ParallelCharDriver;
1927 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1929 if (s->mode != mode) {
1930 int m = mode;
1931 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1932 return 0;
1933 s->mode = mode;
1935 return 1;
1938 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1940 ParallelCharDriver *drv = chr->opaque;
1941 int fd = drv->fd;
1942 uint8_t b;
1944 switch(cmd) {
1945 case CHR_IOCTL_PP_READ_DATA:
1946 if (ioctl(fd, PPRDATA, &b) < 0)
1947 return -ENOTSUP;
1948 *(uint8_t *)arg = b;
1949 break;
1950 case CHR_IOCTL_PP_WRITE_DATA:
1951 b = *(uint8_t *)arg;
1952 if (ioctl(fd, PPWDATA, &b) < 0)
1953 return -ENOTSUP;
1954 break;
1955 case CHR_IOCTL_PP_READ_CONTROL:
1956 if (ioctl(fd, PPRCONTROL, &b) < 0)
1957 return -ENOTSUP;
1958 /* Linux gives only the lowest bits, and no way to know data
1959 direction! For better compatibility set the fixed upper
1960 bits. */
1961 *(uint8_t *)arg = b | 0xc0;
1962 break;
1963 case CHR_IOCTL_PP_WRITE_CONTROL:
1964 b = *(uint8_t *)arg;
1965 if (ioctl(fd, PPWCONTROL, &b) < 0)
1966 return -ENOTSUP;
1967 break;
1968 case CHR_IOCTL_PP_READ_STATUS:
1969 if (ioctl(fd, PPRSTATUS, &b) < 0)
1970 return -ENOTSUP;
1971 *(uint8_t *)arg = b;
1972 break;
1973 case CHR_IOCTL_PP_EPP_READ_ADDR:
1974 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1975 struct ParallelIOArg *parg = arg;
1976 int n = read(fd, parg->buffer, parg->count);
1977 if (n != parg->count) {
1978 return -EIO;
1981 break;
1982 case CHR_IOCTL_PP_EPP_READ:
1983 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1984 struct ParallelIOArg *parg = arg;
1985 int n = read(fd, parg->buffer, parg->count);
1986 if (n != parg->count) {
1987 return -EIO;
1990 break;
1991 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1992 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1993 struct ParallelIOArg *parg = arg;
1994 int n = write(fd, parg->buffer, parg->count);
1995 if (n != parg->count) {
1996 return -EIO;
1999 break;
2000 case CHR_IOCTL_PP_EPP_WRITE:
2001 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2002 struct ParallelIOArg *parg = arg;
2003 int n = write(fd, parg->buffer, parg->count);
2004 if (n != parg->count) {
2005 return -EIO;
2008 break;
2009 default:
2010 return -ENOTSUP;
2012 return 0;
2015 static void pp_close(CharDriverState *chr)
2017 ParallelCharDriver *drv = chr->opaque;
2018 int fd = drv->fd;
2020 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2021 ioctl(fd, PPRELEASE);
2022 close(fd);
2023 qemu_free(drv);
2026 static CharDriverState *qemu_chr_open_pp(const char *filename)
2028 CharDriverState *chr;
2029 ParallelCharDriver *drv;
2030 int fd;
2032 fd = open(filename, O_RDWR);
2033 if (fd < 0)
2034 return NULL;
2036 if (ioctl(fd, PPCLAIM) < 0) {
2037 close(fd);
2038 return NULL;
2041 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2042 if (!drv) {
2043 close(fd);
2044 return NULL;
2046 drv->fd = fd;
2047 drv->mode = IEEE1284_MODE_COMPAT;
2049 chr = qemu_mallocz(sizeof(CharDriverState));
2050 if (!chr) {
2051 qemu_free(drv);
2052 close(fd);
2053 return NULL;
2055 chr->chr_write = null_chr_write;
2056 chr->chr_ioctl = pp_ioctl;
2057 chr->chr_close = pp_close;
2058 chr->opaque = drv;
2060 qemu_chr_reset(chr);
2062 return chr;
2065 #else
2066 static CharDriverState *qemu_chr_open_pty(void)
2068 return NULL;
2070 #endif
2072 #endif /* !defined(_WIN32) */
2074 #ifdef _WIN32
2075 typedef struct {
2076 int max_size;
2077 HANDLE hcom, hrecv, hsend;
2078 OVERLAPPED orecv, osend;
2079 BOOL fpipe;
2080 DWORD len;
2081 } WinCharState;
2083 #define NSENDBUF 2048
2084 #define NRECVBUF 2048
2085 #define MAXCONNECT 1
2086 #define NTIMEOUT 5000
2088 static int win_chr_poll(void *opaque);
2089 static int win_chr_pipe_poll(void *opaque);
2091 static void win_chr_close(CharDriverState *chr)
2093 WinCharState *s = chr->opaque;
2095 if (s->hsend) {
2096 CloseHandle(s->hsend);
2097 s->hsend = NULL;
2099 if (s->hrecv) {
2100 CloseHandle(s->hrecv);
2101 s->hrecv = NULL;
2103 if (s->hcom) {
2104 CloseHandle(s->hcom);
2105 s->hcom = NULL;
2107 if (s->fpipe)
2108 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2109 else
2110 qemu_del_polling_cb(win_chr_poll, chr);
2113 static int win_chr_init(CharDriverState *chr, const char *filename)
2115 WinCharState *s = chr->opaque;
2116 COMMCONFIG comcfg;
2117 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2118 COMSTAT comstat;
2119 DWORD size;
2120 DWORD err;
2122 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2123 if (!s->hsend) {
2124 fprintf(stderr, "Failed CreateEvent\n");
2125 goto fail;
2127 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 if (!s->hrecv) {
2129 fprintf(stderr, "Failed CreateEvent\n");
2130 goto fail;
2133 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2134 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2135 if (s->hcom == INVALID_HANDLE_VALUE) {
2136 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2137 s->hcom = NULL;
2138 goto fail;
2141 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2142 fprintf(stderr, "Failed SetupComm\n");
2143 goto fail;
2146 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2147 size = sizeof(COMMCONFIG);
2148 GetDefaultCommConfig(filename, &comcfg, &size);
2149 comcfg.dcb.DCBlength = sizeof(DCB);
2150 CommConfigDialog(filename, NULL, &comcfg);
2152 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2153 fprintf(stderr, "Failed SetCommState\n");
2154 goto fail;
2157 if (!SetCommMask(s->hcom, EV_ERR)) {
2158 fprintf(stderr, "Failed SetCommMask\n");
2159 goto fail;
2162 cto.ReadIntervalTimeout = MAXDWORD;
2163 if (!SetCommTimeouts(s->hcom, &cto)) {
2164 fprintf(stderr, "Failed SetCommTimeouts\n");
2165 goto fail;
2168 if (!ClearCommError(s->hcom, &err, &comstat)) {
2169 fprintf(stderr, "Failed ClearCommError\n");
2170 goto fail;
2172 qemu_add_polling_cb(win_chr_poll, chr);
2173 return 0;
2175 fail:
2176 win_chr_close(chr);
2177 return -1;
2180 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2182 WinCharState *s = chr->opaque;
2183 DWORD len, ret, size, err;
2185 len = len1;
2186 ZeroMemory(&s->osend, sizeof(s->osend));
2187 s->osend.hEvent = s->hsend;
2188 while (len > 0) {
2189 if (s->hsend)
2190 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2191 else
2192 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2193 if (!ret) {
2194 err = GetLastError();
2195 if (err == ERROR_IO_PENDING) {
2196 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2197 if (ret) {
2198 buf += size;
2199 len -= size;
2200 } else {
2201 break;
2203 } else {
2204 break;
2206 } else {
2207 buf += size;
2208 len -= size;
2211 return len1 - len;
2214 static int win_chr_read_poll(CharDriverState *chr)
2216 WinCharState *s = chr->opaque;
2218 s->max_size = qemu_chr_can_read(chr);
2219 return s->max_size;
2222 static void win_chr_readfile(CharDriverState *chr)
2224 WinCharState *s = chr->opaque;
2225 int ret, err;
2226 uint8_t buf[1024];
2227 DWORD size;
2229 ZeroMemory(&s->orecv, sizeof(s->orecv));
2230 s->orecv.hEvent = s->hrecv;
2231 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2232 if (!ret) {
2233 err = GetLastError();
2234 if (err == ERROR_IO_PENDING) {
2235 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2239 if (size > 0) {
2240 qemu_chr_read(chr, buf, size);
2244 static void win_chr_read(CharDriverState *chr)
2246 WinCharState *s = chr->opaque;
2248 if (s->len > s->max_size)
2249 s->len = s->max_size;
2250 if (s->len == 0)
2251 return;
2253 win_chr_readfile(chr);
2256 static int win_chr_poll(void *opaque)
2258 CharDriverState *chr = opaque;
2259 WinCharState *s = chr->opaque;
2260 COMSTAT status;
2261 DWORD comerr;
2263 ClearCommError(s->hcom, &comerr, &status);
2264 if (status.cbInQue > 0) {
2265 s->len = status.cbInQue;
2266 win_chr_read_poll(chr);
2267 win_chr_read(chr);
2268 return 1;
2270 return 0;
2273 static CharDriverState *qemu_chr_open_win(const char *filename)
2275 CharDriverState *chr;
2276 WinCharState *s;
2278 chr = qemu_mallocz(sizeof(CharDriverState));
2279 if (!chr)
2280 return NULL;
2281 s = qemu_mallocz(sizeof(WinCharState));
2282 if (!s) {
2283 free(chr);
2284 return NULL;
2286 chr->opaque = s;
2287 chr->chr_write = win_chr_write;
2288 chr->chr_close = win_chr_close;
2290 if (win_chr_init(chr, filename) < 0) {
2291 free(s);
2292 free(chr);
2293 return NULL;
2295 qemu_chr_reset(chr);
2296 return chr;
2299 static int win_chr_pipe_poll(void *opaque)
2301 CharDriverState *chr = opaque;
2302 WinCharState *s = chr->opaque;
2303 DWORD size;
2305 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2306 if (size > 0) {
2307 s->len = size;
2308 win_chr_read_poll(chr);
2309 win_chr_read(chr);
2310 return 1;
2312 return 0;
2315 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2317 WinCharState *s = chr->opaque;
2318 OVERLAPPED ov;
2319 int ret;
2320 DWORD size;
2321 char openname[256];
2323 s->fpipe = TRUE;
2325 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2326 if (!s->hsend) {
2327 fprintf(stderr, "Failed CreateEvent\n");
2328 goto fail;
2330 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2331 if (!s->hrecv) {
2332 fprintf(stderr, "Failed CreateEvent\n");
2333 goto fail;
2336 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2337 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2338 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2339 PIPE_WAIT,
2340 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2341 if (s->hcom == INVALID_HANDLE_VALUE) {
2342 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2343 s->hcom = NULL;
2344 goto fail;
2347 ZeroMemory(&ov, sizeof(ov));
2348 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2349 ret = ConnectNamedPipe(s->hcom, &ov);
2350 if (ret) {
2351 fprintf(stderr, "Failed ConnectNamedPipe\n");
2352 goto fail;
2355 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2356 if (!ret) {
2357 fprintf(stderr, "Failed GetOverlappedResult\n");
2358 if (ov.hEvent) {
2359 CloseHandle(ov.hEvent);
2360 ov.hEvent = NULL;
2362 goto fail;
2365 if (ov.hEvent) {
2366 CloseHandle(ov.hEvent);
2367 ov.hEvent = NULL;
2369 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2370 return 0;
2372 fail:
2373 win_chr_close(chr);
2374 return -1;
2378 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2380 CharDriverState *chr;
2381 WinCharState *s;
2383 chr = qemu_mallocz(sizeof(CharDriverState));
2384 if (!chr)
2385 return NULL;
2386 s = qemu_mallocz(sizeof(WinCharState));
2387 if (!s) {
2388 free(chr);
2389 return NULL;
2391 chr->opaque = s;
2392 chr->chr_write = win_chr_write;
2393 chr->chr_close = win_chr_close;
2395 if (win_chr_pipe_init(chr, filename) < 0) {
2396 free(s);
2397 free(chr);
2398 return NULL;
2400 qemu_chr_reset(chr);
2401 return chr;
2404 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2406 CharDriverState *chr;
2407 WinCharState *s;
2409 chr = qemu_mallocz(sizeof(CharDriverState));
2410 if (!chr)
2411 return NULL;
2412 s = qemu_mallocz(sizeof(WinCharState));
2413 if (!s) {
2414 free(chr);
2415 return NULL;
2417 s->hcom = fd_out;
2418 chr->opaque = s;
2419 chr->chr_write = win_chr_write;
2420 qemu_chr_reset(chr);
2421 return chr;
2424 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2426 HANDLE fd_out;
2428 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2429 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2430 if (fd_out == INVALID_HANDLE_VALUE)
2431 return NULL;
2433 return qemu_chr_open_win_file(fd_out);
2435 #endif
2437 /***********************************************************/
2438 /* UDP Net console */
2440 typedef struct {
2441 int fd;
2442 struct sockaddr_in daddr;
2443 char buf[1024];
2444 int bufcnt;
2445 int bufptr;
2446 int max_size;
2447 } NetCharDriver;
2449 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2451 NetCharDriver *s = chr->opaque;
2453 return sendto(s->fd, buf, len, 0,
2454 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2457 static int udp_chr_read_poll(void *opaque)
2459 CharDriverState *chr = opaque;
2460 NetCharDriver *s = chr->opaque;
2462 s->max_size = qemu_chr_can_read(chr);
2464 /* If there were any stray characters in the queue process them
2465 * first
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);
2472 return s->max_size;
2475 static void udp_chr_read(void *opaque)
2477 CharDriverState *chr = opaque;
2478 NetCharDriver *s = chr->opaque;
2480 if (s->max_size == 0)
2481 return;
2482 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2483 s->bufptr = s->bufcnt;
2484 if (s->bufcnt <= 0)
2485 return;
2487 s->bufptr = 0;
2488 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2489 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2490 s->bufptr++;
2491 s->max_size = qemu_chr_can_read(chr);
2495 static void udp_chr_update_read_handler(CharDriverState *chr)
2497 NetCharDriver *s = chr->opaque;
2499 if (s->fd >= 0) {
2500 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2501 udp_chr_read, NULL, chr);
2505 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2506 #ifndef _WIN32
2507 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2508 #endif
2509 int parse_host_src_port(struct sockaddr_in *haddr,
2510 struct sockaddr_in *saddr,
2511 const char *str);
2513 static CharDriverState *qemu_chr_open_udp(const char *def)
2515 CharDriverState *chr = NULL;
2516 NetCharDriver *s = NULL;
2517 int fd = -1;
2518 struct sockaddr_in saddr;
2520 chr = qemu_mallocz(sizeof(CharDriverState));
2521 if (!chr)
2522 goto return_err;
2523 s = qemu_mallocz(sizeof(NetCharDriver));
2524 if (!s)
2525 goto return_err;
2527 fd = socket(PF_INET, SOCK_DGRAM, 0);
2528 if (fd < 0) {
2529 perror("socket(PF_INET, SOCK_DGRAM)");
2530 goto return_err;
2533 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2534 printf("Could not parse: %s\n", def);
2535 goto return_err;
2538 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2540 perror("bind");
2541 goto return_err;
2544 s->fd = fd;
2545 s->bufcnt = 0;
2546 s->bufptr = 0;
2547 chr->opaque = s;
2548 chr->chr_write = udp_chr_write;
2549 chr->chr_update_read_handler = udp_chr_update_read_handler;
2550 return chr;
2552 return_err:
2553 if (chr)
2554 free(chr);
2555 if (s)
2556 free(s);
2557 if (fd >= 0)
2558 closesocket(fd);
2559 return NULL;
2562 /***********************************************************/
2563 /* TCP Net console */
2565 typedef struct {
2566 int fd, listen_fd;
2567 int connected;
2568 int max_size;
2569 int do_telnetopt;
2570 int do_nodelay;
2571 int is_unix;
2572 } TCPCharDriver;
2574 static void tcp_chr_accept(void *opaque);
2576 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2578 TCPCharDriver *s = chr->opaque;
2579 if (s->connected) {
2580 return send_all(s->fd, buf, len);
2581 } else {
2582 /* XXX: indicate an error ? */
2583 return len;
2587 static int tcp_chr_read_poll(void *opaque)
2589 CharDriverState *chr = opaque;
2590 TCPCharDriver *s = chr->opaque;
2591 if (!s->connected)
2592 return 0;
2593 s->max_size = qemu_chr_can_read(chr);
2594 return s->max_size;
2597 #define IAC 255
2598 #define IAC_BREAK 243
2599 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2600 TCPCharDriver *s,
2601 char *buf, int *size)
2603 /* Handle any telnet client's basic IAC options to satisfy char by
2604 * char mode with no echo. All IAC options will be removed from
2605 * the buf and the do_telnetopt variable will be used to track the
2606 * state of the width of the IAC information.
2608 * IAC commands come in sets of 3 bytes with the exception of the
2609 * "IAC BREAK" command and the double IAC.
2612 int i;
2613 int j = 0;
2615 for (i = 0; i < *size; i++) {
2616 if (s->do_telnetopt > 1) {
2617 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2618 /* Double IAC means send an IAC */
2619 if (j != i)
2620 buf[j] = buf[i];
2621 j++;
2622 s->do_telnetopt = 1;
2623 } else {
2624 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2625 /* Handle IAC break commands by sending a serial break */
2626 qemu_chr_event(chr, CHR_EVENT_BREAK);
2627 s->do_telnetopt++;
2629 s->do_telnetopt++;
2631 if (s->do_telnetopt >= 4) {
2632 s->do_telnetopt = 1;
2634 } else {
2635 if ((unsigned char)buf[i] == IAC) {
2636 s->do_telnetopt = 2;
2637 } else {
2638 if (j != i)
2639 buf[j] = buf[i];
2640 j++;
2644 *size = j;
2647 static void tcp_chr_read(void *opaque)
2649 CharDriverState *chr = opaque;
2650 TCPCharDriver *s = chr->opaque;
2651 uint8_t buf[1024];
2652 int len, size;
2654 if (!s->connected || s->max_size <= 0)
2655 return;
2656 len = sizeof(buf);
2657 if (len > s->max_size)
2658 len = s->max_size;
2659 size = recv(s->fd, buf, len, 0);
2660 if (size == 0) {
2661 /* connection closed */
2662 s->connected = 0;
2663 if (s->listen_fd >= 0) {
2664 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2666 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2667 closesocket(s->fd);
2668 s->fd = -1;
2669 } else if (size > 0) {
2670 if (s->do_telnetopt)
2671 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2672 if (size > 0)
2673 qemu_chr_read(chr, buf, size);
2677 static void tcp_chr_connect(void *opaque)
2679 CharDriverState *chr = opaque;
2680 TCPCharDriver *s = chr->opaque;
2682 s->connected = 1;
2683 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2684 tcp_chr_read, NULL, chr);
2685 qemu_chr_reset(chr);
2688 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2689 static void tcp_chr_telnet_init(int fd)
2691 char buf[3];
2692 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2693 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2694 send(fd, (char *)buf, 3, 0);
2695 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2696 send(fd, (char *)buf, 3, 0);
2697 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2698 send(fd, (char *)buf, 3, 0);
2699 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2700 send(fd, (char *)buf, 3, 0);
2703 static void socket_set_nodelay(int fd)
2705 int val = 1;
2706 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2709 static void tcp_chr_accept(void *opaque)
2711 CharDriverState *chr = opaque;
2712 TCPCharDriver *s = chr->opaque;
2713 struct sockaddr_in saddr;
2714 #ifndef _WIN32
2715 struct sockaddr_un uaddr;
2716 #endif
2717 struct sockaddr *addr;
2718 socklen_t len;
2719 int fd;
2721 for(;;) {
2722 #ifndef _WIN32
2723 if (s->is_unix) {
2724 len = sizeof(uaddr);
2725 addr = (struct sockaddr *)&uaddr;
2726 } else
2727 #endif
2729 len = sizeof(saddr);
2730 addr = (struct sockaddr *)&saddr;
2732 fd = accept(s->listen_fd, addr, &len);
2733 if (fd < 0 && errno != EINTR) {
2734 return;
2735 } else if (fd >= 0) {
2736 if (s->do_telnetopt)
2737 tcp_chr_telnet_init(fd);
2738 break;
2741 socket_set_nonblock(fd);
2742 if (s->do_nodelay)
2743 socket_set_nodelay(fd);
2744 s->fd = fd;
2745 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2746 tcp_chr_connect(chr);
2749 static void tcp_chr_close(CharDriverState *chr)
2751 TCPCharDriver *s = chr->opaque;
2752 if (s->fd >= 0)
2753 closesocket(s->fd);
2754 if (s->listen_fd >= 0)
2755 closesocket(s->listen_fd);
2756 qemu_free(s);
2759 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2760 int is_telnet,
2761 int is_unix)
2763 CharDriverState *chr = NULL;
2764 TCPCharDriver *s = NULL;
2765 int fd = -1, ret, err, val;
2766 int is_listen = 0;
2767 int is_waitconnect = 1;
2768 int do_nodelay = 0;
2769 const char *ptr;
2770 struct sockaddr_in saddr;
2771 #ifndef _WIN32
2772 struct sockaddr_un uaddr;
2773 #endif
2774 struct sockaddr *addr;
2775 socklen_t addrlen;
2777 #ifndef _WIN32
2778 if (is_unix) {
2779 addr = (struct sockaddr *)&uaddr;
2780 addrlen = sizeof(uaddr);
2781 if (parse_unix_path(&uaddr, host_str) < 0)
2782 goto fail;
2783 } else
2784 #endif
2786 addr = (struct sockaddr *)&saddr;
2787 addrlen = sizeof(saddr);
2788 if (parse_host_port(&saddr, host_str) < 0)
2789 goto fail;
2792 ptr = host_str;
2793 while((ptr = strchr(ptr,','))) {
2794 ptr++;
2795 if (!strncmp(ptr,"server",6)) {
2796 is_listen = 1;
2797 } else if (!strncmp(ptr,"nowait",6)) {
2798 is_waitconnect = 0;
2799 } else if (!strncmp(ptr,"nodelay",6)) {
2800 do_nodelay = 1;
2801 } else {
2802 printf("Unknown option: %s\n", ptr);
2803 goto fail;
2806 if (!is_listen)
2807 is_waitconnect = 0;
2809 chr = qemu_mallocz(sizeof(CharDriverState));
2810 if (!chr)
2811 goto fail;
2812 s = qemu_mallocz(sizeof(TCPCharDriver));
2813 if (!s)
2814 goto fail;
2816 #ifndef _WIN32
2817 if (is_unix)
2818 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2819 else
2820 #endif
2821 fd = socket(PF_INET, SOCK_STREAM, 0);
2823 if (fd < 0)
2824 goto fail;
2826 if (!is_waitconnect)
2827 socket_set_nonblock(fd);
2829 s->connected = 0;
2830 s->fd = -1;
2831 s->listen_fd = -1;
2832 s->is_unix = is_unix;
2833 s->do_nodelay = do_nodelay && !is_unix;
2835 chr->opaque = s;
2836 chr->chr_write = tcp_chr_write;
2837 chr->chr_close = tcp_chr_close;
2839 if (is_listen) {
2840 /* allow fast reuse */
2841 #ifndef _WIN32
2842 if (is_unix) {
2843 char path[109];
2844 strncpy(path, uaddr.sun_path, 108);
2845 path[108] = 0;
2846 unlink(path);
2847 } else
2848 #endif
2850 val = 1;
2851 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2854 ret = bind(fd, addr, addrlen);
2855 if (ret < 0)
2856 goto fail;
2858 ret = listen(fd, 0);
2859 if (ret < 0)
2860 goto fail;
2862 s->listen_fd = fd;
2863 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2864 if (is_telnet)
2865 s->do_telnetopt = 1;
2866 } else {
2867 for(;;) {
2868 ret = connect(fd, addr, addrlen);
2869 if (ret < 0) {
2870 err = socket_error();
2871 if (err == EINTR || err == EWOULDBLOCK) {
2872 } else if (err == EINPROGRESS) {
2873 break;
2874 #ifdef _WIN32
2875 } else if (err == WSAEALREADY) {
2876 break;
2877 #endif
2878 } else {
2879 goto fail;
2881 } else {
2882 s->connected = 1;
2883 break;
2886 s->fd = fd;
2887 socket_set_nodelay(fd);
2888 if (s->connected)
2889 tcp_chr_connect(chr);
2890 else
2891 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2894 if (is_listen && is_waitconnect) {
2895 printf("QEMU waiting for connection on: %s\n", host_str);
2896 tcp_chr_accept(chr);
2897 socket_set_nonblock(s->listen_fd);
2900 return chr;
2901 fail:
2902 if (fd >= 0)
2903 closesocket(fd);
2904 qemu_free(s);
2905 qemu_free(chr);
2906 return NULL;
2909 CharDriverState *qemu_chr_open(const char *filename)
2911 const char *p;
2913 if (!strcmp(filename, "vc")) {
2914 return text_console_init(&display_state);
2915 } else if (!strcmp(filename, "null")) {
2916 return qemu_chr_open_null();
2917 } else
2918 if (strstart(filename, "tcp:", &p)) {
2919 return qemu_chr_open_tcp(p, 0, 0);
2920 } else
2921 if (strstart(filename, "telnet:", &p)) {
2922 return qemu_chr_open_tcp(p, 1, 0);
2923 } else
2924 if (strstart(filename, "udp:", &p)) {
2925 return qemu_chr_open_udp(p);
2926 } else
2927 if (strstart(filename, "mon:", &p)) {
2928 CharDriverState *drv = qemu_chr_open(p);
2929 if (drv) {
2930 drv = qemu_chr_open_mux(drv);
2931 monitor_init(drv, !nographic);
2932 return drv;
2934 printf("Unable to open driver: %s\n", p);
2935 return 0;
2936 } else
2937 #ifndef _WIN32
2938 if (strstart(filename, "unix:", &p)) {
2939 return qemu_chr_open_tcp(p, 0, 1);
2940 } else if (strstart(filename, "file:", &p)) {
2941 return qemu_chr_open_file_out(p);
2942 } else if (strstart(filename, "pipe:", &p)) {
2943 return qemu_chr_open_pipe(p);
2944 } else if (!strcmp(filename, "pty")) {
2945 return qemu_chr_open_pty();
2946 } else if (!strcmp(filename, "stdio")) {
2947 return qemu_chr_open_stdio();
2948 } else
2949 #endif
2950 #if defined(__linux__)
2951 if (strstart(filename, "/dev/parport", NULL)) {
2952 return qemu_chr_open_pp(filename);
2953 } else
2954 if (strstart(filename, "/dev/", NULL)) {
2955 return qemu_chr_open_tty(filename);
2956 } else
2957 #endif
2958 #ifdef _WIN32
2959 if (strstart(filename, "COM", NULL)) {
2960 return qemu_chr_open_win(filename);
2961 } else
2962 if (strstart(filename, "pipe:", &p)) {
2963 return qemu_chr_open_win_pipe(p);
2964 } else
2965 if (strstart(filename, "file:", &p)) {
2966 return qemu_chr_open_win_file_out(p);
2968 #endif
2970 return NULL;
2974 void qemu_chr_close(CharDriverState *chr)
2976 if (chr->chr_close)
2977 chr->chr_close(chr);
2980 /***********************************************************/
2981 /* network device redirectors */
2983 void hex_dump(FILE *f, const uint8_t *buf, int size)
2985 int len, i, j, c;
2987 for(i=0;i<size;i+=16) {
2988 len = size - i;
2989 if (len > 16)
2990 len = 16;
2991 fprintf(f, "%08x ", i);
2992 for(j=0;j<16;j++) {
2993 if (j < len)
2994 fprintf(f, " %02x", buf[i+j]);
2995 else
2996 fprintf(f, " ");
2998 fprintf(f, " ");
2999 for(j=0;j<len;j++) {
3000 c = buf[i+j];
3001 if (c < ' ' || c > '~')
3002 c = '.';
3003 fprintf(f, "%c", c);
3005 fprintf(f, "\n");
3009 static int parse_macaddr(uint8_t *macaddr, const char *p)
3011 int i;
3012 for(i = 0; i < 6; i++) {
3013 macaddr[i] = strtol(p, (char **)&p, 16);
3014 if (i == 5) {
3015 if (*p != '\0')
3016 return -1;
3017 } else {
3018 if (*p != ':')
3019 return -1;
3020 p++;
3023 return 0;
3026 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3028 const char *p, *p1;
3029 int len;
3030 p = *pp;
3031 p1 = strchr(p, sep);
3032 if (!p1)
3033 return -1;
3034 len = p1 - p;
3035 p1++;
3036 if (buf_size > 0) {
3037 if (len > buf_size - 1)
3038 len = buf_size - 1;
3039 memcpy(buf, p, len);
3040 buf[len] = '\0';
3042 *pp = p1;
3043 return 0;
3046 int parse_host_src_port(struct sockaddr_in *haddr,
3047 struct sockaddr_in *saddr,
3048 const char *input_str)
3050 char *str = strdup(input_str);
3051 char *host_str = str;
3052 char *src_str;
3053 char *ptr;
3056 * Chop off any extra arguments at the end of the string which
3057 * would start with a comma, then fill in the src port information
3058 * if it was provided else use the "any address" and "any port".
3060 if ((ptr = strchr(str,',')))
3061 *ptr = '\0';
3063 if ((src_str = strchr(input_str,'@'))) {
3064 *src_str = '\0';
3065 src_str++;
3068 if (parse_host_port(haddr, host_str) < 0)
3069 goto fail;
3071 if (!src_str || *src_str == '\0')
3072 src_str = ":0";
3074 if (parse_host_port(saddr, src_str) < 0)
3075 goto fail;
3077 free(str);
3078 return(0);
3080 fail:
3081 free(str);
3082 return -1;
3085 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3087 char buf[512];
3088 struct hostent *he;
3089 const char *p, *r;
3090 int port;
3092 p = str;
3093 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3094 return -1;
3095 saddr->sin_family = AF_INET;
3096 if (buf[0] == '\0') {
3097 saddr->sin_addr.s_addr = 0;
3098 } else {
3099 if (isdigit(buf[0])) {
3100 if (!inet_aton(buf, &saddr->sin_addr))
3101 return -1;
3102 } else {
3103 if ((he = gethostbyname(buf)) == NULL)
3104 return - 1;
3105 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3108 port = strtol(p, (char **)&r, 0);
3109 if (r == p)
3110 return -1;
3111 saddr->sin_port = htons(port);
3112 return 0;
3115 #ifndef _WIN32
3116 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3118 const char *p;
3119 int len;
3121 len = MIN(108, strlen(str));
3122 p = strchr(str, ',');
3123 if (p)
3124 len = MIN(len, p - str);
3126 memset(uaddr, 0, sizeof(*uaddr));
3128 uaddr->sun_family = AF_UNIX;
3129 memcpy(uaddr->sun_path, str, len);
3131 return 0;
3133 #endif
3135 /* find or alloc a new VLAN */
3136 VLANState *qemu_find_vlan(int id)
3138 VLANState **pvlan, *vlan;
3139 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3140 if (vlan->id == id)
3141 return vlan;
3143 vlan = qemu_mallocz(sizeof(VLANState));
3144 if (!vlan)
3145 return NULL;
3146 vlan->id = id;
3147 vlan->next = NULL;
3148 pvlan = &first_vlan;
3149 while (*pvlan != NULL)
3150 pvlan = &(*pvlan)->next;
3151 *pvlan = vlan;
3152 return vlan;
3155 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3156 IOReadHandler *fd_read,
3157 IOCanRWHandler *fd_can_read,
3158 void *opaque)
3160 VLANClientState *vc, **pvc;
3161 vc = qemu_mallocz(sizeof(VLANClientState));
3162 if (!vc)
3163 return NULL;
3164 vc->fd_read = fd_read;
3165 vc->fd_can_read = fd_can_read;
3166 vc->opaque = opaque;
3167 vc->vlan = vlan;
3169 vc->next = NULL;
3170 pvc = &vlan->first_client;
3171 while (*pvc != NULL)
3172 pvc = &(*pvc)->next;
3173 *pvc = vc;
3174 return vc;
3177 int qemu_can_send_packet(VLANClientState *vc1)
3179 VLANState *vlan = vc1->vlan;
3180 VLANClientState *vc;
3182 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3183 if (vc != vc1) {
3184 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3185 return 0;
3188 return 1;
3191 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3193 VLANState *vlan = vc1->vlan;
3194 VLANClientState *vc;
3196 #if 0
3197 printf("vlan %d send:\n", vlan->id);
3198 hex_dump(stdout, buf, size);
3199 #endif
3200 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3201 if (vc != vc1) {
3202 vc->fd_read(vc->opaque, buf, size);
3207 #if defined(CONFIG_SLIRP)
3209 /* slirp network adapter */
3211 static int slirp_inited;
3212 static VLANClientState *slirp_vc;
3214 int slirp_can_output(void)
3216 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3219 void slirp_output(const uint8_t *pkt, int pkt_len)
3221 #if 0
3222 printf("slirp output:\n");
3223 hex_dump(stdout, pkt, pkt_len);
3224 #endif
3225 if (!slirp_vc)
3226 return;
3227 qemu_send_packet(slirp_vc, pkt, pkt_len);
3230 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3232 #if 0
3233 printf("slirp input:\n");
3234 hex_dump(stdout, buf, size);
3235 #endif
3236 slirp_input(buf, size);
3239 static int net_slirp_init(VLANState *vlan)
3241 if (!slirp_inited) {
3242 slirp_inited = 1;
3243 slirp_init();
3245 slirp_vc = qemu_new_vlan_client(vlan,
3246 slirp_receive, NULL, NULL);
3247 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3248 return 0;
3251 static void net_slirp_redir(const char *redir_str)
3253 int is_udp;
3254 char buf[256], *r;
3255 const char *p;
3256 struct in_addr guest_addr;
3257 int host_port, guest_port;
3259 if (!slirp_inited) {
3260 slirp_inited = 1;
3261 slirp_init();
3264 p = redir_str;
3265 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3266 goto fail;
3267 if (!strcmp(buf, "tcp")) {
3268 is_udp = 0;
3269 } else if (!strcmp(buf, "udp")) {
3270 is_udp = 1;
3271 } else {
3272 goto fail;
3275 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3276 goto fail;
3277 host_port = strtol(buf, &r, 0);
3278 if (r == buf)
3279 goto fail;
3281 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3282 goto fail;
3283 if (buf[0] == '\0') {
3284 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3286 if (!inet_aton(buf, &guest_addr))
3287 goto fail;
3289 guest_port = strtol(p, &r, 0);
3290 if (r == p)
3291 goto fail;
3293 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3294 fprintf(stderr, "qemu: could not set up redirection\n");
3295 exit(1);
3297 return;
3298 fail:
3299 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3300 exit(1);
3303 #ifndef _WIN32
3305 char smb_dir[1024];
3307 static void smb_exit(void)
3309 DIR *d;
3310 struct dirent *de;
3311 char filename[1024];
3313 /* erase all the files in the directory */
3314 d = opendir(smb_dir);
3315 for(;;) {
3316 de = readdir(d);
3317 if (!de)
3318 break;
3319 if (strcmp(de->d_name, ".") != 0 &&
3320 strcmp(de->d_name, "..") != 0) {
3321 snprintf(filename, sizeof(filename), "%s/%s",
3322 smb_dir, de->d_name);
3323 unlink(filename);
3326 closedir(d);
3327 rmdir(smb_dir);
3330 /* automatic user mode samba server configuration */
3331 void net_slirp_smb(const char *exported_dir)
3333 char smb_conf[1024];
3334 char smb_cmdline[1024];
3335 FILE *f;
3337 if (!slirp_inited) {
3338 slirp_inited = 1;
3339 slirp_init();
3342 /* XXX: better tmp dir construction */
3343 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3344 if (mkdir(smb_dir, 0700) < 0) {
3345 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3346 exit(1);
3348 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3350 f = fopen(smb_conf, "w");
3351 if (!f) {
3352 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3353 exit(1);
3355 fprintf(f,
3356 "[global]\n"
3357 "private dir=%s\n"
3358 "smb ports=0\n"
3359 "socket address=127.0.0.1\n"
3360 "pid directory=%s\n"
3361 "lock directory=%s\n"
3362 "log file=%s/log.smbd\n"
3363 "smb passwd file=%s/smbpasswd\n"
3364 "security = share\n"
3365 "[qemu]\n"
3366 "path=%s\n"
3367 "read only=no\n"
3368 "guest ok=yes\n",
3369 smb_dir,
3370 smb_dir,
3371 smb_dir,
3372 smb_dir,
3373 smb_dir,
3374 exported_dir
3376 fclose(f);
3377 atexit(smb_exit);
3379 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3380 SMBD_COMMAND, smb_conf);
3382 slirp_add_exec(0, smb_cmdline, 4, 139);
3385 #endif /* !defined(_WIN32) */
3387 #endif /* CONFIG_SLIRP */
3389 #if !defined(_WIN32)
3391 typedef struct TAPState {
3392 VLANClientState *vc;
3393 int fd;
3394 } TAPState;
3396 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3398 TAPState *s = opaque;
3399 int ret;
3400 for(;;) {
3401 ret = write(s->fd, buf, size);
3402 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3403 } else {
3404 break;
3409 static void tap_send(void *opaque)
3411 TAPState *s = opaque;
3412 uint8_t buf[4096];
3413 int size;
3415 #ifdef __sun__
3416 struct strbuf sbuf;
3417 int f = 0;
3418 sbuf.maxlen = sizeof(buf);
3419 sbuf.buf = buf;
3420 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3421 #else
3422 size = read(s->fd, buf, sizeof(buf));
3423 #endif
3424 if (size > 0) {
3425 qemu_send_packet(s->vc, buf, size);
3429 /* fd support */
3431 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3433 TAPState *s;
3435 s = qemu_mallocz(sizeof(TAPState));
3436 if (!s)
3437 return NULL;
3438 s->fd = fd;
3439 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3440 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3441 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3442 return s;
3445 #ifdef _BSD
3446 static int tap_open(char *ifname, int ifname_size)
3448 int fd;
3449 char *dev;
3450 struct stat s;
3452 fd = open("/dev/tap", O_RDWR);
3453 if (fd < 0) {
3454 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3455 return -1;
3458 fstat(fd, &s);
3459 dev = devname(s.st_rdev, S_IFCHR);
3460 pstrcpy(ifname, ifname_size, dev);
3462 fcntl(fd, F_SETFL, O_NONBLOCK);
3463 return fd;
3465 #elif defined(__sun__)
3466 #define TUNNEWPPA (('T'<<16) | 0x0001)
3468 * Allocate TAP device, returns opened fd.
3469 * Stores dev name in the first arg(must be large enough).
3471 int tap_alloc(char *dev)
3473 int tap_fd, if_fd, ppa = -1;
3474 static int ip_fd = 0;
3475 char *ptr;
3477 static int arp_fd = 0;
3478 int ip_muxid, arp_muxid;
3479 struct strioctl strioc_if, strioc_ppa;
3480 int link_type = I_PLINK;;
3481 struct lifreq ifr;
3482 char actual_name[32] = "";
3484 memset(&ifr, 0x0, sizeof(ifr));
3486 if( *dev ){
3487 ptr = dev;
3488 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3489 ppa = atoi(ptr);
3492 /* Check if IP device was opened */
3493 if( ip_fd )
3494 close(ip_fd);
3496 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3497 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3498 return -1;
3501 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3502 syslog(LOG_ERR, "Can't open /dev/tap");
3503 return -1;
3506 /* Assign a new PPA and get its unit number. */
3507 strioc_ppa.ic_cmd = TUNNEWPPA;
3508 strioc_ppa.ic_timout = 0;
3509 strioc_ppa.ic_len = sizeof(ppa);
3510 strioc_ppa.ic_dp = (char *)&ppa;
3511 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3512 syslog (LOG_ERR, "Can't assign new interface");
3514 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3515 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3516 return -1;
3518 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3519 syslog(LOG_ERR, "Can't push IP module");
3520 return -1;
3523 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3524 syslog(LOG_ERR, "Can't get flags\n");
3526 snprintf (actual_name, 32, "tap%d", ppa);
3527 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3529 ifr.lifr_ppa = ppa;
3530 /* Assign ppa according to the unit number returned by tun device */
3532 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3533 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3534 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3535 syslog (LOG_ERR, "Can't get flags\n");
3536 /* Push arp module to if_fd */
3537 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3538 syslog (LOG_ERR, "Can't push ARP module (2)");
3540 /* Push arp module to ip_fd */
3541 if (ioctl (ip_fd, I_POP, NULL) < 0)
3542 syslog (LOG_ERR, "I_POP failed\n");
3543 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3544 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3545 /* Open arp_fd */
3546 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3547 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3549 /* Set ifname to arp */
3550 strioc_if.ic_cmd = SIOCSLIFNAME;
3551 strioc_if.ic_timout = 0;
3552 strioc_if.ic_len = sizeof(ifr);
3553 strioc_if.ic_dp = (char *)&ifr;
3554 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3555 syslog (LOG_ERR, "Can't set ifname to arp\n");
3558 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3559 syslog(LOG_ERR, "Can't link TAP device to IP");
3560 return -1;
3563 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3564 syslog (LOG_ERR, "Can't link TAP device to ARP");
3566 close (if_fd);
3568 memset(&ifr, 0x0, sizeof(ifr));
3569 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3570 ifr.lifr_ip_muxid = ip_muxid;
3571 ifr.lifr_arp_muxid = arp_muxid;
3573 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3575 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3576 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3577 syslog (LOG_ERR, "Can't set multiplexor id");
3580 sprintf(dev, "tap%d", ppa);
3581 return tap_fd;
3584 static int tap_open(char *ifname, int ifname_size)
3586 char dev[10]="";
3587 int fd;
3588 if( (fd = tap_alloc(dev)) < 0 ){
3589 fprintf(stderr, "Cannot allocate TAP device\n");
3590 return -1;
3592 pstrcpy(ifname, ifname_size, dev);
3593 fcntl(fd, F_SETFL, O_NONBLOCK);
3594 return fd;
3596 #else
3597 static int tap_open(char *ifname, int ifname_size)
3599 struct ifreq ifr;
3600 int fd, ret;
3602 fd = open("/dev/net/tun", O_RDWR);
3603 if (fd < 0) {
3604 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3605 return -1;
3607 memset(&ifr, 0, sizeof(ifr));
3608 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3609 if (ifname[0] != '\0')
3610 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3611 else
3612 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3613 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3614 if (ret != 0) {
3615 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3616 close(fd);
3617 return -1;
3619 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3620 fcntl(fd, F_SETFL, O_NONBLOCK);
3621 return fd;
3623 #endif
3625 static int net_tap_init(VLANState *vlan, const char *ifname1,
3626 const char *setup_script)
3628 TAPState *s;
3629 int pid, status, fd;
3630 char *args[3];
3631 char **parg;
3632 char ifname[128];
3634 if (ifname1 != NULL)
3635 pstrcpy(ifname, sizeof(ifname), ifname1);
3636 else
3637 ifname[0] = '\0';
3638 fd = tap_open(ifname, sizeof(ifname));
3639 if (fd < 0)
3640 return -1;
3642 if (!setup_script || !strcmp(setup_script, "no"))
3643 setup_script = "";
3644 if (setup_script[0] != '\0') {
3645 /* try to launch network init script */
3646 pid = fork();
3647 if (pid >= 0) {
3648 if (pid == 0) {
3649 int open_max = sysconf (_SC_OPEN_MAX), i;
3650 for (i = 0; i < open_max; i++)
3651 if (i != STDIN_FILENO &&
3652 i != STDOUT_FILENO &&
3653 i != STDERR_FILENO &&
3654 i != fd)
3655 close(i);
3657 parg = args;
3658 *parg++ = (char *)setup_script;
3659 *parg++ = ifname;
3660 *parg++ = NULL;
3661 execv(setup_script, args);
3662 _exit(1);
3664 while (waitpid(pid, &status, 0) != pid);
3665 if (!WIFEXITED(status) ||
3666 WEXITSTATUS(status) != 0) {
3667 fprintf(stderr, "%s: could not launch network script\n",
3668 setup_script);
3669 return -1;
3673 s = net_tap_fd_init(vlan, fd);
3674 if (!s)
3675 return -1;
3676 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3677 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3678 return 0;
3681 #endif /* !_WIN32 */
3683 /* network connection */
3684 typedef struct NetSocketState {
3685 VLANClientState *vc;
3686 int fd;
3687 int state; /* 0 = getting length, 1 = getting data */
3688 int index;
3689 int packet_len;
3690 uint8_t buf[4096];
3691 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3692 } NetSocketState;
3694 typedef struct NetSocketListenState {
3695 VLANState *vlan;
3696 int fd;
3697 } NetSocketListenState;
3699 /* XXX: we consider we can send the whole packet without blocking */
3700 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3702 NetSocketState *s = opaque;
3703 uint32_t len;
3704 len = htonl(size);
3706 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3707 send_all(s->fd, buf, size);
3710 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3712 NetSocketState *s = opaque;
3713 sendto(s->fd, buf, size, 0,
3714 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3717 static void net_socket_send(void *opaque)
3719 NetSocketState *s = opaque;
3720 int l, size, err;
3721 uint8_t buf1[4096];
3722 const uint8_t *buf;
3724 size = recv(s->fd, buf1, sizeof(buf1), 0);
3725 if (size < 0) {
3726 err = socket_error();
3727 if (err != EWOULDBLOCK)
3728 goto eoc;
3729 } else if (size == 0) {
3730 /* end of connection */
3731 eoc:
3732 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3733 closesocket(s->fd);
3734 return;
3736 buf = buf1;
3737 while (size > 0) {
3738 /* reassemble a packet from the network */
3739 switch(s->state) {
3740 case 0:
3741 l = 4 - s->index;
3742 if (l > size)
3743 l = size;
3744 memcpy(s->buf + s->index, buf, l);
3745 buf += l;
3746 size -= l;
3747 s->index += l;
3748 if (s->index == 4) {
3749 /* got length */
3750 s->packet_len = ntohl(*(uint32_t *)s->buf);
3751 s->index = 0;
3752 s->state = 1;
3754 break;
3755 case 1:
3756 l = s->packet_len - s->index;
3757 if (l > size)
3758 l = size;
3759 memcpy(s->buf + s->index, buf, l);
3760 s->index += l;
3761 buf += l;
3762 size -= l;
3763 if (s->index >= s->packet_len) {
3764 qemu_send_packet(s->vc, s->buf, s->packet_len);
3765 s->index = 0;
3766 s->state = 0;
3768 break;
3773 static void net_socket_send_dgram(void *opaque)
3775 NetSocketState *s = opaque;
3776 int size;
3778 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3779 if (size < 0)
3780 return;
3781 if (size == 0) {
3782 /* end of connection */
3783 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3784 return;
3786 qemu_send_packet(s->vc, s->buf, size);
3789 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3791 struct ip_mreq imr;
3792 int fd;
3793 int val, ret;
3794 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3795 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3796 inet_ntoa(mcastaddr->sin_addr),
3797 (int)ntohl(mcastaddr->sin_addr.s_addr));
3798 return -1;
3801 fd = socket(PF_INET, SOCK_DGRAM, 0);
3802 if (fd < 0) {
3803 perror("socket(PF_INET, SOCK_DGRAM)");
3804 return -1;
3807 val = 1;
3808 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3809 (const char *)&val, sizeof(val));
3810 if (ret < 0) {
3811 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3812 goto fail;
3815 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3816 if (ret < 0) {
3817 perror("bind");
3818 goto fail;
3821 /* Add host to multicast group */
3822 imr.imr_multiaddr = mcastaddr->sin_addr;
3823 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3825 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3826 (const char *)&imr, sizeof(struct ip_mreq));
3827 if (ret < 0) {
3828 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3829 goto fail;
3832 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3833 val = 1;
3834 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3835 (const char *)&val, sizeof(val));
3836 if (ret < 0) {
3837 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3838 goto fail;
3841 socket_set_nonblock(fd);
3842 return fd;
3843 fail:
3844 if (fd >= 0)
3845 closesocket(fd);
3846 return -1;
3849 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3850 int is_connected)
3852 struct sockaddr_in saddr;
3853 int newfd;
3854 socklen_t saddr_len;
3855 NetSocketState *s;
3857 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3858 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3859 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3862 if (is_connected) {
3863 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3864 /* must be bound */
3865 if (saddr.sin_addr.s_addr==0) {
3866 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3867 fd);
3868 return NULL;
3870 /* clone dgram socket */
3871 newfd = net_socket_mcast_create(&saddr);
3872 if (newfd < 0) {
3873 /* error already reported by net_socket_mcast_create() */
3874 close(fd);
3875 return NULL;
3877 /* clone newfd to fd, close newfd */
3878 dup2(newfd, fd);
3879 close(newfd);
3881 } else {
3882 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3883 fd, strerror(errno));
3884 return NULL;
3888 s = qemu_mallocz(sizeof(NetSocketState));
3889 if (!s)
3890 return NULL;
3891 s->fd = fd;
3893 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3894 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3896 /* mcast: save bound address as dst */
3897 if (is_connected) s->dgram_dst=saddr;
3899 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3900 "socket: fd=%d (%s mcast=%s:%d)",
3901 fd, is_connected? "cloned" : "",
3902 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3903 return s;
3906 static void net_socket_connect(void *opaque)
3908 NetSocketState *s = opaque;
3909 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3912 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3913 int is_connected)
3915 NetSocketState *s;
3916 s = qemu_mallocz(sizeof(NetSocketState));
3917 if (!s)
3918 return NULL;
3919 s->fd = fd;
3920 s->vc = qemu_new_vlan_client(vlan,
3921 net_socket_receive, NULL, s);
3922 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3923 "socket: fd=%d", fd);
3924 if (is_connected) {
3925 net_socket_connect(s);
3926 } else {
3927 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3929 return s;
3932 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3933 int is_connected)
3935 int so_type=-1, optlen=sizeof(so_type);
3937 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3938 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3939 return NULL;
3941 switch(so_type) {
3942 case SOCK_DGRAM:
3943 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3944 case SOCK_STREAM:
3945 return net_socket_fd_init_stream(vlan, fd, is_connected);
3946 default:
3947 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3948 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3949 return net_socket_fd_init_stream(vlan, fd, is_connected);
3951 return NULL;
3954 static void net_socket_accept(void *opaque)
3956 NetSocketListenState *s = opaque;
3957 NetSocketState *s1;
3958 struct sockaddr_in saddr;
3959 socklen_t len;
3960 int fd;
3962 for(;;) {
3963 len = sizeof(saddr);
3964 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3965 if (fd < 0 && errno != EINTR) {
3966 return;
3967 } else if (fd >= 0) {
3968 break;
3971 s1 = net_socket_fd_init(s->vlan, fd, 1);
3972 if (!s1) {
3973 closesocket(fd);
3974 } else {
3975 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3976 "socket: connection from %s:%d",
3977 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3981 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3983 NetSocketListenState *s;
3984 int fd, val, ret;
3985 struct sockaddr_in saddr;
3987 if (parse_host_port(&saddr, host_str) < 0)
3988 return -1;
3990 s = qemu_mallocz(sizeof(NetSocketListenState));
3991 if (!s)
3992 return -1;
3994 fd = socket(PF_INET, SOCK_STREAM, 0);
3995 if (fd < 0) {
3996 perror("socket");
3997 return -1;
3999 socket_set_nonblock(fd);
4001 /* allow fast reuse */
4002 val = 1;
4003 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4005 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4006 if (ret < 0) {
4007 perror("bind");
4008 return -1;
4010 ret = listen(fd, 0);
4011 if (ret < 0) {
4012 perror("listen");
4013 return -1;
4015 s->vlan = vlan;
4016 s->fd = fd;
4017 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4018 return 0;
4021 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4023 NetSocketState *s;
4024 int fd, connected, ret, err;
4025 struct sockaddr_in saddr;
4027 if (parse_host_port(&saddr, host_str) < 0)
4028 return -1;
4030 fd = socket(PF_INET, SOCK_STREAM, 0);
4031 if (fd < 0) {
4032 perror("socket");
4033 return -1;
4035 socket_set_nonblock(fd);
4037 connected = 0;
4038 for(;;) {
4039 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4040 if (ret < 0) {
4041 err = socket_error();
4042 if (err == EINTR || err == EWOULDBLOCK) {
4043 } else if (err == EINPROGRESS) {
4044 break;
4045 #ifdef _WIN32
4046 } else if (err == WSAEALREADY) {
4047 break;
4048 #endif
4049 } else {
4050 perror("connect");
4051 closesocket(fd);
4052 return -1;
4054 } else {
4055 connected = 1;
4056 break;
4059 s = net_socket_fd_init(vlan, fd, connected);
4060 if (!s)
4061 return -1;
4062 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4063 "socket: connect to %s:%d",
4064 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4065 return 0;
4068 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4070 NetSocketState *s;
4071 int fd;
4072 struct sockaddr_in saddr;
4074 if (parse_host_port(&saddr, host_str) < 0)
4075 return -1;
4078 fd = net_socket_mcast_create(&saddr);
4079 if (fd < 0)
4080 return -1;
4082 s = net_socket_fd_init(vlan, fd, 0);
4083 if (!s)
4084 return -1;
4086 s->dgram_dst = saddr;
4088 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4089 "socket: mcast=%s:%d",
4090 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4091 return 0;
4095 static int get_param_value(char *buf, int buf_size,
4096 const char *tag, const char *str)
4098 const char *p;
4099 char *q;
4100 char option[128];
4102 p = str;
4103 for(;;) {
4104 q = option;
4105 while (*p != '\0' && *p != '=') {
4106 if ((q - option) < sizeof(option) - 1)
4107 *q++ = *p;
4108 p++;
4110 *q = '\0';
4111 if (*p != '=')
4112 break;
4113 p++;
4114 if (!strcmp(tag, option)) {
4115 q = buf;
4116 while (*p != '\0' && *p != ',') {
4117 if ((q - buf) < buf_size - 1)
4118 *q++ = *p;
4119 p++;
4121 *q = '\0';
4122 return q - buf;
4123 } else {
4124 while (*p != '\0' && *p != ',') {
4125 p++;
4128 if (*p != ',')
4129 break;
4130 p++;
4132 return 0;
4135 static int net_client_init(const char *str)
4137 const char *p;
4138 char *q;
4139 char device[64];
4140 char buf[1024];
4141 int vlan_id, ret;
4142 VLANState *vlan;
4144 p = str;
4145 q = device;
4146 while (*p != '\0' && *p != ',') {
4147 if ((q - device) < sizeof(device) - 1)
4148 *q++ = *p;
4149 p++;
4151 *q = '\0';
4152 if (*p == ',')
4153 p++;
4154 vlan_id = 0;
4155 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4156 vlan_id = strtol(buf, NULL, 0);
4158 vlan = qemu_find_vlan(vlan_id);
4159 if (!vlan) {
4160 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4161 return -1;
4163 if (!strcmp(device, "nic")) {
4164 NICInfo *nd;
4165 uint8_t *macaddr;
4167 if (nb_nics >= MAX_NICS) {
4168 fprintf(stderr, "Too Many NICs\n");
4169 return -1;
4171 nd = &nd_table[nb_nics];
4172 macaddr = nd->macaddr;
4173 macaddr[0] = 0x52;
4174 macaddr[1] = 0x54;
4175 macaddr[2] = 0x00;
4176 macaddr[3] = 0x12;
4177 macaddr[4] = 0x34;
4178 macaddr[5] = 0x56 + nb_nics;
4180 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4181 if (parse_macaddr(macaddr, buf) < 0) {
4182 fprintf(stderr, "invalid syntax for ethernet address\n");
4183 return -1;
4186 if (get_param_value(buf, sizeof(buf), "model", p)) {
4187 nd->model = strdup(buf);
4189 nd->vlan = vlan;
4190 nb_nics++;
4191 ret = 0;
4192 } else
4193 if (!strcmp(device, "none")) {
4194 /* does nothing. It is needed to signal that no network cards
4195 are wanted */
4196 ret = 0;
4197 } else
4198 #ifdef CONFIG_SLIRP
4199 if (!strcmp(device, "user")) {
4200 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4201 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4203 ret = net_slirp_init(vlan);
4204 } else
4205 #endif
4206 #ifdef _WIN32
4207 if (!strcmp(device, "tap")) {
4208 char ifname[64];
4209 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4210 fprintf(stderr, "tap: no interface name\n");
4211 return -1;
4213 ret = tap_win32_init(vlan, ifname);
4214 } else
4215 #else
4216 if (!strcmp(device, "tap")) {
4217 char ifname[64];
4218 char setup_script[1024];
4219 int fd;
4220 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4221 fd = strtol(buf, NULL, 0);
4222 ret = -1;
4223 if (net_tap_fd_init(vlan, fd))
4224 ret = 0;
4225 } else {
4226 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4227 ifname[0] = '\0';
4229 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4230 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4232 ret = net_tap_init(vlan, ifname, setup_script);
4234 } else
4235 #endif
4236 if (!strcmp(device, "socket")) {
4237 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4238 int fd;
4239 fd = strtol(buf, NULL, 0);
4240 ret = -1;
4241 if (net_socket_fd_init(vlan, fd, 1))
4242 ret = 0;
4243 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4244 ret = net_socket_listen_init(vlan, buf);
4245 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4246 ret = net_socket_connect_init(vlan, buf);
4247 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4248 ret = net_socket_mcast_init(vlan, buf);
4249 } else {
4250 fprintf(stderr, "Unknown socket options: %s\n", p);
4251 return -1;
4253 } else
4255 fprintf(stderr, "Unknown network device: %s\n", device);
4256 return -1;
4258 if (ret < 0) {
4259 fprintf(stderr, "Could not initialize device '%s'\n", device);
4262 return ret;
4265 void do_info_network(void)
4267 VLANState *vlan;
4268 VLANClientState *vc;
4270 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4271 term_printf("VLAN %d devices:\n", vlan->id);
4272 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4273 term_printf(" %s\n", vc->info_str);
4277 /***********************************************************/
4278 /* USB devices */
4280 static USBPort *used_usb_ports;
4281 static USBPort *free_usb_ports;
4283 /* ??? Maybe change this to register a hub to keep track of the topology. */
4284 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4285 usb_attachfn attach)
4287 port->opaque = opaque;
4288 port->index = index;
4289 port->attach = attach;
4290 port->next = free_usb_ports;
4291 free_usb_ports = port;
4294 static int usb_device_add(const char *devname)
4296 const char *p;
4297 USBDevice *dev;
4298 USBPort *port;
4300 if (!free_usb_ports)
4301 return -1;
4303 if (strstart(devname, "host:", &p)) {
4304 dev = usb_host_device_open(p);
4305 } else if (!strcmp(devname, "mouse")) {
4306 dev = usb_mouse_init();
4307 } else if (!strcmp(devname, "tablet")) {
4308 dev = usb_tablet_init();
4309 } else if (strstart(devname, "disk:", &p)) {
4310 dev = usb_msd_init(p);
4311 } else {
4312 return -1;
4314 if (!dev)
4315 return -1;
4317 /* Find a USB port to add the device to. */
4318 port = free_usb_ports;
4319 if (!port->next) {
4320 USBDevice *hub;
4322 /* Create a new hub and chain it on. */
4323 free_usb_ports = NULL;
4324 port->next = used_usb_ports;
4325 used_usb_ports = port;
4327 hub = usb_hub_init(VM_USB_HUB_SIZE);
4328 usb_attach(port, hub);
4329 port = free_usb_ports;
4332 free_usb_ports = port->next;
4333 port->next = used_usb_ports;
4334 used_usb_ports = port;
4335 usb_attach(port, dev);
4336 return 0;
4339 static int usb_device_del(const char *devname)
4341 USBPort *port;
4342 USBPort **lastp;
4343 USBDevice *dev;
4344 int bus_num, addr;
4345 const char *p;
4347 if (!used_usb_ports)
4348 return -1;
4350 p = strchr(devname, '.');
4351 if (!p)
4352 return -1;
4353 bus_num = strtoul(devname, NULL, 0);
4354 addr = strtoul(p + 1, NULL, 0);
4355 if (bus_num != 0)
4356 return -1;
4358 lastp = &used_usb_ports;
4359 port = used_usb_ports;
4360 while (port && port->dev->addr != addr) {
4361 lastp = &port->next;
4362 port = port->next;
4365 if (!port)
4366 return -1;
4368 dev = port->dev;
4369 *lastp = port->next;
4370 usb_attach(port, NULL);
4371 dev->handle_destroy(dev);
4372 port->next = free_usb_ports;
4373 free_usb_ports = port;
4374 return 0;
4377 void do_usb_add(const char *devname)
4379 int ret;
4380 ret = usb_device_add(devname);
4381 if (ret < 0)
4382 term_printf("Could not add USB device '%s'\n", devname);
4385 void do_usb_del(const char *devname)
4387 int ret;
4388 ret = usb_device_del(devname);
4389 if (ret < 0)
4390 term_printf("Could not remove USB device '%s'\n", devname);
4393 void usb_info(void)
4395 USBDevice *dev;
4396 USBPort *port;
4397 const char *speed_str;
4399 if (!usb_enabled) {
4400 term_printf("USB support not enabled\n");
4401 return;
4404 for (port = used_usb_ports; port; port = port->next) {
4405 dev = port->dev;
4406 if (!dev)
4407 continue;
4408 switch(dev->speed) {
4409 case USB_SPEED_LOW:
4410 speed_str = "1.5";
4411 break;
4412 case USB_SPEED_FULL:
4413 speed_str = "12";
4414 break;
4415 case USB_SPEED_HIGH:
4416 speed_str = "480";
4417 break;
4418 default:
4419 speed_str = "?";
4420 break;
4422 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4423 0, dev->addr, speed_str, dev->devname);
4427 /***********************************************************/
4428 /* PCMCIA/Cardbus */
4430 static struct pcmcia_socket_entry_s {
4431 struct pcmcia_socket_s *socket;
4432 struct pcmcia_socket_entry_s *next;
4433 } *pcmcia_sockets = 0;
4435 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4437 struct pcmcia_socket_entry_s *entry;
4439 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4440 entry->socket = socket;
4441 entry->next = pcmcia_sockets;
4442 pcmcia_sockets = entry;
4445 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4447 struct pcmcia_socket_entry_s *entry, **ptr;
4449 ptr = &pcmcia_sockets;
4450 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4451 if (entry->socket == socket) {
4452 *ptr = entry->next;
4453 qemu_free(entry);
4457 void pcmcia_info(void)
4459 struct pcmcia_socket_entry_s *iter;
4460 if (!pcmcia_sockets)
4461 term_printf("No PCMCIA sockets\n");
4463 for (iter = pcmcia_sockets; iter; iter = iter->next)
4464 term_printf("%s: %s\n", iter->socket->slot_string,
4465 iter->socket->attached ? iter->socket->card_string :
4466 "Empty");
4469 /***********************************************************/
4470 /* dumb display */
4472 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4476 static void dumb_resize(DisplayState *ds, int w, int h)
4480 static void dumb_refresh(DisplayState *ds)
4482 vga_hw_update();
4485 void dumb_display_init(DisplayState *ds)
4487 ds->data = NULL;
4488 ds->linesize = 0;
4489 ds->depth = 0;
4490 ds->dpy_update = dumb_update;
4491 ds->dpy_resize = dumb_resize;
4492 ds->dpy_refresh = dumb_refresh;
4495 /***********************************************************/
4496 /* I/O handling */
4498 #define MAX_IO_HANDLERS 64
4500 typedef struct IOHandlerRecord {
4501 int fd;
4502 IOCanRWHandler *fd_read_poll;
4503 IOHandler *fd_read;
4504 IOHandler *fd_write;
4505 int deleted;
4506 void *opaque;
4507 /* temporary data */
4508 struct pollfd *ufd;
4509 struct IOHandlerRecord *next;
4510 } IOHandlerRecord;
4512 static IOHandlerRecord *first_io_handler;
4514 /* XXX: fd_read_poll should be suppressed, but an API change is
4515 necessary in the character devices to suppress fd_can_read(). */
4516 int qemu_set_fd_handler2(int fd,
4517 IOCanRWHandler *fd_read_poll,
4518 IOHandler *fd_read,
4519 IOHandler *fd_write,
4520 void *opaque)
4522 IOHandlerRecord **pioh, *ioh;
4524 if (!fd_read && !fd_write) {
4525 pioh = &first_io_handler;
4526 for(;;) {
4527 ioh = *pioh;
4528 if (ioh == NULL)
4529 break;
4530 if (ioh->fd == fd) {
4531 ioh->deleted = 1;
4532 break;
4534 pioh = &ioh->next;
4536 } else {
4537 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4538 if (ioh->fd == fd)
4539 goto found;
4541 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4542 if (!ioh)
4543 return -1;
4544 ioh->next = first_io_handler;
4545 first_io_handler = ioh;
4546 found:
4547 ioh->fd = fd;
4548 ioh->fd_read_poll = fd_read_poll;
4549 ioh->fd_read = fd_read;
4550 ioh->fd_write = fd_write;
4551 ioh->opaque = opaque;
4552 ioh->deleted = 0;
4554 return 0;
4557 int qemu_set_fd_handler(int fd,
4558 IOHandler *fd_read,
4559 IOHandler *fd_write,
4560 void *opaque)
4562 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4565 /***********************************************************/
4566 /* Polling handling */
4568 typedef struct PollingEntry {
4569 PollingFunc *func;
4570 void *opaque;
4571 struct PollingEntry *next;
4572 } PollingEntry;
4574 static PollingEntry *first_polling_entry;
4576 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4578 PollingEntry **ppe, *pe;
4579 pe = qemu_mallocz(sizeof(PollingEntry));
4580 if (!pe)
4581 return -1;
4582 pe->func = func;
4583 pe->opaque = opaque;
4584 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4585 *ppe = pe;
4586 return 0;
4589 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4591 PollingEntry **ppe, *pe;
4592 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4593 pe = *ppe;
4594 if (pe->func == func && pe->opaque == opaque) {
4595 *ppe = pe->next;
4596 qemu_free(pe);
4597 break;
4602 #ifdef _WIN32
4603 /***********************************************************/
4604 /* Wait objects support */
4605 typedef struct WaitObjects {
4606 int num;
4607 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4608 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4609 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4610 } WaitObjects;
4612 static WaitObjects wait_objects = {0};
4614 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4616 WaitObjects *w = &wait_objects;
4618 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4619 return -1;
4620 w->events[w->num] = handle;
4621 w->func[w->num] = func;
4622 w->opaque[w->num] = opaque;
4623 w->num++;
4624 return 0;
4627 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4629 int i, found;
4630 WaitObjects *w = &wait_objects;
4632 found = 0;
4633 for (i = 0; i < w->num; i++) {
4634 if (w->events[i] == handle)
4635 found = 1;
4636 if (found) {
4637 w->events[i] = w->events[i + 1];
4638 w->func[i] = w->func[i + 1];
4639 w->opaque[i] = w->opaque[i + 1];
4642 if (found)
4643 w->num--;
4645 #endif
4647 /***********************************************************/
4648 /* savevm/loadvm support */
4650 #define IO_BUF_SIZE 32768
4652 struct QEMUFile {
4653 FILE *outfile;
4654 BlockDriverState *bs;
4655 int is_file;
4656 int is_writable;
4657 int64_t base_offset;
4658 int64_t buf_offset; /* start of buffer when writing, end of buffer
4659 when reading */
4660 int buf_index;
4661 int buf_size; /* 0 when writing */
4662 uint8_t buf[IO_BUF_SIZE];
4665 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4667 QEMUFile *f;
4669 f = qemu_mallocz(sizeof(QEMUFile));
4670 if (!f)
4671 return NULL;
4672 if (!strcmp(mode, "wb")) {
4673 f->is_writable = 1;
4674 } else if (!strcmp(mode, "rb")) {
4675 f->is_writable = 0;
4676 } else {
4677 goto fail;
4679 f->outfile = fopen(filename, mode);
4680 if (!f->outfile)
4681 goto fail;
4682 f->is_file = 1;
4683 return f;
4684 fail:
4685 if (f->outfile)
4686 fclose(f->outfile);
4687 qemu_free(f);
4688 return NULL;
4691 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4693 QEMUFile *f;
4695 f = qemu_mallocz(sizeof(QEMUFile));
4696 if (!f)
4697 return NULL;
4698 f->is_file = 0;
4699 f->bs = bs;
4700 f->is_writable = is_writable;
4701 f->base_offset = offset;
4702 return f;
4705 void qemu_fflush(QEMUFile *f)
4707 if (!f->is_writable)
4708 return;
4709 if (f->buf_index > 0) {
4710 if (f->is_file) {
4711 fseek(f->outfile, f->buf_offset, SEEK_SET);
4712 fwrite(f->buf, 1, f->buf_index, f->outfile);
4713 } else {
4714 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4715 f->buf, f->buf_index);
4717 f->buf_offset += f->buf_index;
4718 f->buf_index = 0;
4722 static void qemu_fill_buffer(QEMUFile *f)
4724 int len;
4726 if (f->is_writable)
4727 return;
4728 if (f->is_file) {
4729 fseek(f->outfile, f->buf_offset, SEEK_SET);
4730 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4731 if (len < 0)
4732 len = 0;
4733 } else {
4734 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4735 f->buf, IO_BUF_SIZE);
4736 if (len < 0)
4737 len = 0;
4739 f->buf_index = 0;
4740 f->buf_size = len;
4741 f->buf_offset += len;
4744 void qemu_fclose(QEMUFile *f)
4746 if (f->is_writable)
4747 qemu_fflush(f);
4748 if (f->is_file) {
4749 fclose(f->outfile);
4751 qemu_free(f);
4754 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4756 int l;
4757 while (size > 0) {
4758 l = IO_BUF_SIZE - f->buf_index;
4759 if (l > size)
4760 l = size;
4761 memcpy(f->buf + f->buf_index, buf, l);
4762 f->buf_index += l;
4763 buf += l;
4764 size -= l;
4765 if (f->buf_index >= IO_BUF_SIZE)
4766 qemu_fflush(f);
4770 void qemu_put_byte(QEMUFile *f, int v)
4772 f->buf[f->buf_index++] = v;
4773 if (f->buf_index >= IO_BUF_SIZE)
4774 qemu_fflush(f);
4777 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4779 int size, l;
4781 size = size1;
4782 while (size > 0) {
4783 l = f->buf_size - f->buf_index;
4784 if (l == 0) {
4785 qemu_fill_buffer(f);
4786 l = f->buf_size - f->buf_index;
4787 if (l == 0)
4788 break;
4790 if (l > size)
4791 l = size;
4792 memcpy(buf, f->buf + f->buf_index, l);
4793 f->buf_index += l;
4794 buf += l;
4795 size -= l;
4797 return size1 - size;
4800 int qemu_get_byte(QEMUFile *f)
4802 if (f->buf_index >= f->buf_size) {
4803 qemu_fill_buffer(f);
4804 if (f->buf_index >= f->buf_size)
4805 return 0;
4807 return f->buf[f->buf_index++];
4810 int64_t qemu_ftell(QEMUFile *f)
4812 return f->buf_offset - f->buf_size + f->buf_index;
4815 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4817 if (whence == SEEK_SET) {
4818 /* nothing to do */
4819 } else if (whence == SEEK_CUR) {
4820 pos += qemu_ftell(f);
4821 } else {
4822 /* SEEK_END not supported */
4823 return -1;
4825 if (f->is_writable) {
4826 qemu_fflush(f);
4827 f->buf_offset = pos;
4828 } else {
4829 f->buf_offset = pos;
4830 f->buf_index = 0;
4831 f->buf_size = 0;
4833 return pos;
4836 void qemu_put_be16(QEMUFile *f, unsigned int v)
4838 qemu_put_byte(f, v >> 8);
4839 qemu_put_byte(f, v);
4842 void qemu_put_be32(QEMUFile *f, unsigned int v)
4844 qemu_put_byte(f, v >> 24);
4845 qemu_put_byte(f, v >> 16);
4846 qemu_put_byte(f, v >> 8);
4847 qemu_put_byte(f, v);
4850 void qemu_put_be64(QEMUFile *f, uint64_t v)
4852 qemu_put_be32(f, v >> 32);
4853 qemu_put_be32(f, v);
4856 unsigned int qemu_get_be16(QEMUFile *f)
4858 unsigned int v;
4859 v = qemu_get_byte(f) << 8;
4860 v |= qemu_get_byte(f);
4861 return v;
4864 unsigned int qemu_get_be32(QEMUFile *f)
4866 unsigned int v;
4867 v = qemu_get_byte(f) << 24;
4868 v |= qemu_get_byte(f) << 16;
4869 v |= qemu_get_byte(f) << 8;
4870 v |= qemu_get_byte(f);
4871 return v;
4874 uint64_t qemu_get_be64(QEMUFile *f)
4876 uint64_t v;
4877 v = (uint64_t)qemu_get_be32(f) << 32;
4878 v |= qemu_get_be32(f);
4879 return v;
4882 typedef struct SaveStateEntry {
4883 char idstr[256];
4884 int instance_id;
4885 int version_id;
4886 SaveStateHandler *save_state;
4887 LoadStateHandler *load_state;
4888 void *opaque;
4889 struct SaveStateEntry *next;
4890 } SaveStateEntry;
4892 static SaveStateEntry *first_se;
4894 int register_savevm(const char *idstr,
4895 int instance_id,
4896 int version_id,
4897 SaveStateHandler *save_state,
4898 LoadStateHandler *load_state,
4899 void *opaque)
4901 SaveStateEntry *se, **pse;
4903 se = qemu_malloc(sizeof(SaveStateEntry));
4904 if (!se)
4905 return -1;
4906 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4907 se->instance_id = instance_id;
4908 se->version_id = version_id;
4909 se->save_state = save_state;
4910 se->load_state = load_state;
4911 se->opaque = opaque;
4912 se->next = NULL;
4914 /* add at the end of list */
4915 pse = &first_se;
4916 while (*pse != NULL)
4917 pse = &(*pse)->next;
4918 *pse = se;
4919 return 0;
4922 #define QEMU_VM_FILE_MAGIC 0x5145564d
4923 #define QEMU_VM_FILE_VERSION 0x00000002
4925 int qemu_savevm_state(QEMUFile *f)
4927 SaveStateEntry *se;
4928 int len, ret;
4929 int64_t cur_pos, len_pos, total_len_pos;
4931 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4932 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4933 total_len_pos = qemu_ftell(f);
4934 qemu_put_be64(f, 0); /* total size */
4936 for(se = first_se; se != NULL; se = se->next) {
4937 /* ID string */
4938 len = strlen(se->idstr);
4939 qemu_put_byte(f, len);
4940 qemu_put_buffer(f, se->idstr, len);
4942 qemu_put_be32(f, se->instance_id);
4943 qemu_put_be32(f, se->version_id);
4945 /* record size: filled later */
4946 len_pos = qemu_ftell(f);
4947 qemu_put_be32(f, 0);
4949 se->save_state(f, se->opaque);
4951 /* fill record size */
4952 cur_pos = qemu_ftell(f);
4953 len = cur_pos - len_pos - 4;
4954 qemu_fseek(f, len_pos, SEEK_SET);
4955 qemu_put_be32(f, len);
4956 qemu_fseek(f, cur_pos, SEEK_SET);
4958 cur_pos = qemu_ftell(f);
4959 qemu_fseek(f, total_len_pos, SEEK_SET);
4960 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4961 qemu_fseek(f, cur_pos, SEEK_SET);
4963 ret = 0;
4964 return ret;
4967 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4969 SaveStateEntry *se;
4971 for(se = first_se; se != NULL; se = se->next) {
4972 if (!strcmp(se->idstr, idstr) &&
4973 instance_id == se->instance_id)
4974 return se;
4976 return NULL;
4979 int qemu_loadvm_state(QEMUFile *f)
4981 SaveStateEntry *se;
4982 int len, ret, instance_id, record_len, version_id;
4983 int64_t total_len, end_pos, cur_pos;
4984 unsigned int v;
4985 char idstr[256];
4987 v = qemu_get_be32(f);
4988 if (v != QEMU_VM_FILE_MAGIC)
4989 goto fail;
4990 v = qemu_get_be32(f);
4991 if (v != QEMU_VM_FILE_VERSION) {
4992 fail:
4993 ret = -1;
4994 goto the_end;
4996 total_len = qemu_get_be64(f);
4997 end_pos = total_len + qemu_ftell(f);
4998 for(;;) {
4999 if (qemu_ftell(f) >= end_pos)
5000 break;
5001 len = qemu_get_byte(f);
5002 qemu_get_buffer(f, idstr, len);
5003 idstr[len] = '\0';
5004 instance_id = qemu_get_be32(f);
5005 version_id = qemu_get_be32(f);
5006 record_len = qemu_get_be32(f);
5007 #if 0
5008 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5009 idstr, instance_id, version_id, record_len);
5010 #endif
5011 cur_pos = qemu_ftell(f);
5012 se = find_se(idstr, instance_id);
5013 if (!se) {
5014 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5015 instance_id, idstr);
5016 } else {
5017 ret = se->load_state(f, se->opaque, version_id);
5018 if (ret < 0) {
5019 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5020 instance_id, idstr);
5023 /* always seek to exact end of record */
5024 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5026 ret = 0;
5027 the_end:
5028 return ret;
5031 /* device can contain snapshots */
5032 static int bdrv_can_snapshot(BlockDriverState *bs)
5034 return (bs &&
5035 !bdrv_is_removable(bs) &&
5036 !bdrv_is_read_only(bs));
5039 /* device must be snapshots in order to have a reliable snapshot */
5040 static int bdrv_has_snapshot(BlockDriverState *bs)
5042 return (bs &&
5043 !bdrv_is_removable(bs) &&
5044 !bdrv_is_read_only(bs));
5047 static BlockDriverState *get_bs_snapshots(void)
5049 BlockDriverState *bs;
5050 int i;
5052 if (bs_snapshots)
5053 return bs_snapshots;
5054 for(i = 0; i <= MAX_DISKS; i++) {
5055 bs = bs_table[i];
5056 if (bdrv_can_snapshot(bs))
5057 goto ok;
5059 return NULL;
5061 bs_snapshots = bs;
5062 return bs;
5065 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5066 const char *name)
5068 QEMUSnapshotInfo *sn_tab, *sn;
5069 int nb_sns, i, ret;
5071 ret = -ENOENT;
5072 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5073 if (nb_sns < 0)
5074 return ret;
5075 for(i = 0; i < nb_sns; i++) {
5076 sn = &sn_tab[i];
5077 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5078 *sn_info = *sn;
5079 ret = 0;
5080 break;
5083 qemu_free(sn_tab);
5084 return ret;
5087 void do_savevm(const char *name)
5089 BlockDriverState *bs, *bs1;
5090 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5091 int must_delete, ret, i;
5092 BlockDriverInfo bdi1, *bdi = &bdi1;
5093 QEMUFile *f;
5094 int saved_vm_running;
5095 #ifdef _WIN32
5096 struct _timeb tb;
5097 #else
5098 struct timeval tv;
5099 #endif
5101 bs = get_bs_snapshots();
5102 if (!bs) {
5103 term_printf("No block device can accept snapshots\n");
5104 return;
5107 /* ??? Should this occur after vm_stop? */
5108 qemu_aio_flush();
5110 saved_vm_running = vm_running;
5111 vm_stop(0);
5113 must_delete = 0;
5114 if (name) {
5115 ret = bdrv_snapshot_find(bs, old_sn, name);
5116 if (ret >= 0) {
5117 must_delete = 1;
5120 memset(sn, 0, sizeof(*sn));
5121 if (must_delete) {
5122 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5123 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5124 } else {
5125 if (name)
5126 pstrcpy(sn->name, sizeof(sn->name), name);
5129 /* fill auxiliary fields */
5130 #ifdef _WIN32
5131 _ftime(&tb);
5132 sn->date_sec = tb.time;
5133 sn->date_nsec = tb.millitm * 1000000;
5134 #else
5135 gettimeofday(&tv, NULL);
5136 sn->date_sec = tv.tv_sec;
5137 sn->date_nsec = tv.tv_usec * 1000;
5138 #endif
5139 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5141 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5142 term_printf("Device %s does not support VM state snapshots\n",
5143 bdrv_get_device_name(bs));
5144 goto the_end;
5147 /* save the VM state */
5148 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5149 if (!f) {
5150 term_printf("Could not open VM state file\n");
5151 goto the_end;
5153 ret = qemu_savevm_state(f);
5154 sn->vm_state_size = qemu_ftell(f);
5155 qemu_fclose(f);
5156 if (ret < 0) {
5157 term_printf("Error %d while writing VM\n", ret);
5158 goto the_end;
5161 /* create the snapshots */
5163 for(i = 0; i < MAX_DISKS; i++) {
5164 bs1 = bs_table[i];
5165 if (bdrv_has_snapshot(bs1)) {
5166 if (must_delete) {
5167 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5168 if (ret < 0) {
5169 term_printf("Error while deleting snapshot on '%s'\n",
5170 bdrv_get_device_name(bs1));
5173 ret = bdrv_snapshot_create(bs1, sn);
5174 if (ret < 0) {
5175 term_printf("Error while creating snapshot on '%s'\n",
5176 bdrv_get_device_name(bs1));
5181 the_end:
5182 if (saved_vm_running)
5183 vm_start();
5186 void do_loadvm(const char *name)
5188 BlockDriverState *bs, *bs1;
5189 BlockDriverInfo bdi1, *bdi = &bdi1;
5190 QEMUFile *f;
5191 int i, ret;
5192 int saved_vm_running;
5194 bs = get_bs_snapshots();
5195 if (!bs) {
5196 term_printf("No block device supports snapshots\n");
5197 return;
5200 /* Flush all IO requests so they don't interfere with the new state. */
5201 qemu_aio_flush();
5203 saved_vm_running = vm_running;
5204 vm_stop(0);
5206 for(i = 0; i <= MAX_DISKS; i++) {
5207 bs1 = bs_table[i];
5208 if (bdrv_has_snapshot(bs1)) {
5209 ret = bdrv_snapshot_goto(bs1, name);
5210 if (ret < 0) {
5211 if (bs != bs1)
5212 term_printf("Warning: ");
5213 switch(ret) {
5214 case -ENOTSUP:
5215 term_printf("Snapshots not supported on device '%s'\n",
5216 bdrv_get_device_name(bs1));
5217 break;
5218 case -ENOENT:
5219 term_printf("Could not find snapshot '%s' on device '%s'\n",
5220 name, bdrv_get_device_name(bs1));
5221 break;
5222 default:
5223 term_printf("Error %d while activating snapshot on '%s'\n",
5224 ret, bdrv_get_device_name(bs1));
5225 break;
5227 /* fatal on snapshot block device */
5228 if (bs == bs1)
5229 goto the_end;
5234 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5235 term_printf("Device %s does not support VM state snapshots\n",
5236 bdrv_get_device_name(bs));
5237 return;
5240 /* restore the VM state */
5241 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5242 if (!f) {
5243 term_printf("Could not open VM state file\n");
5244 goto the_end;
5246 ret = qemu_loadvm_state(f);
5247 qemu_fclose(f);
5248 if (ret < 0) {
5249 term_printf("Error %d while loading VM state\n", ret);
5251 the_end:
5252 if (saved_vm_running)
5253 vm_start();
5256 void do_delvm(const char *name)
5258 BlockDriverState *bs, *bs1;
5259 int i, ret;
5261 bs = get_bs_snapshots();
5262 if (!bs) {
5263 term_printf("No block device supports snapshots\n");
5264 return;
5267 for(i = 0; i <= MAX_DISKS; i++) {
5268 bs1 = bs_table[i];
5269 if (bdrv_has_snapshot(bs1)) {
5270 ret = bdrv_snapshot_delete(bs1, name);
5271 if (ret < 0) {
5272 if (ret == -ENOTSUP)
5273 term_printf("Snapshots not supported on device '%s'\n",
5274 bdrv_get_device_name(bs1));
5275 else
5276 term_printf("Error %d while deleting snapshot on '%s'\n",
5277 ret, bdrv_get_device_name(bs1));
5283 void do_info_snapshots(void)
5285 BlockDriverState *bs, *bs1;
5286 QEMUSnapshotInfo *sn_tab, *sn;
5287 int nb_sns, i;
5288 char buf[256];
5290 bs = get_bs_snapshots();
5291 if (!bs) {
5292 term_printf("No available block device supports snapshots\n");
5293 return;
5295 term_printf("Snapshot devices:");
5296 for(i = 0; i <= MAX_DISKS; i++) {
5297 bs1 = bs_table[i];
5298 if (bdrv_has_snapshot(bs1)) {
5299 if (bs == bs1)
5300 term_printf(" %s", bdrv_get_device_name(bs1));
5303 term_printf("\n");
5305 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5306 if (nb_sns < 0) {
5307 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5308 return;
5310 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5311 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5312 for(i = 0; i < nb_sns; i++) {
5313 sn = &sn_tab[i];
5314 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5316 qemu_free(sn_tab);
5319 /***********************************************************/
5320 /* cpu save/restore */
5322 #if defined(TARGET_I386)
5324 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5326 qemu_put_be32(f, dt->selector);
5327 qemu_put_betl(f, dt->base);
5328 qemu_put_be32(f, dt->limit);
5329 qemu_put_be32(f, dt->flags);
5332 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5334 dt->selector = qemu_get_be32(f);
5335 dt->base = qemu_get_betl(f);
5336 dt->limit = qemu_get_be32(f);
5337 dt->flags = qemu_get_be32(f);
5340 void cpu_save(QEMUFile *f, void *opaque)
5342 CPUState *env = opaque;
5343 uint16_t fptag, fpus, fpuc, fpregs_format;
5344 uint32_t hflags;
5345 int i;
5347 for(i = 0; i < CPU_NB_REGS; i++)
5348 qemu_put_betls(f, &env->regs[i]);
5349 qemu_put_betls(f, &env->eip);
5350 qemu_put_betls(f, &env->eflags);
5351 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5352 qemu_put_be32s(f, &hflags);
5354 /* FPU */
5355 fpuc = env->fpuc;
5356 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5357 fptag = 0;
5358 for(i = 0; i < 8; i++) {
5359 fptag |= ((!env->fptags[i]) << i);
5362 qemu_put_be16s(f, &fpuc);
5363 qemu_put_be16s(f, &fpus);
5364 qemu_put_be16s(f, &fptag);
5366 #ifdef USE_X86LDOUBLE
5367 fpregs_format = 0;
5368 #else
5369 fpregs_format = 1;
5370 #endif
5371 qemu_put_be16s(f, &fpregs_format);
5373 for(i = 0; i < 8; i++) {
5374 #ifdef USE_X86LDOUBLE
5376 uint64_t mant;
5377 uint16_t exp;
5378 /* we save the real CPU data (in case of MMX usage only 'mant'
5379 contains the MMX register */
5380 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5381 qemu_put_be64(f, mant);
5382 qemu_put_be16(f, exp);
5384 #else
5385 /* if we use doubles for float emulation, we save the doubles to
5386 avoid losing information in case of MMX usage. It can give
5387 problems if the image is restored on a CPU where long
5388 doubles are used instead. */
5389 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5390 #endif
5393 for(i = 0; i < 6; i++)
5394 cpu_put_seg(f, &env->segs[i]);
5395 cpu_put_seg(f, &env->ldt);
5396 cpu_put_seg(f, &env->tr);
5397 cpu_put_seg(f, &env->gdt);
5398 cpu_put_seg(f, &env->idt);
5400 qemu_put_be32s(f, &env->sysenter_cs);
5401 qemu_put_be32s(f, &env->sysenter_esp);
5402 qemu_put_be32s(f, &env->sysenter_eip);
5404 qemu_put_betls(f, &env->cr[0]);
5405 qemu_put_betls(f, &env->cr[2]);
5406 qemu_put_betls(f, &env->cr[3]);
5407 qemu_put_betls(f, &env->cr[4]);
5409 for(i = 0; i < 8; i++)
5410 qemu_put_betls(f, &env->dr[i]);
5412 /* MMU */
5413 qemu_put_be32s(f, &env->a20_mask);
5415 /* XMM */
5416 qemu_put_be32s(f, &env->mxcsr);
5417 for(i = 0; i < CPU_NB_REGS; i++) {
5418 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5419 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5422 #ifdef TARGET_X86_64
5423 qemu_put_be64s(f, &env->efer);
5424 qemu_put_be64s(f, &env->star);
5425 qemu_put_be64s(f, &env->lstar);
5426 qemu_put_be64s(f, &env->cstar);
5427 qemu_put_be64s(f, &env->fmask);
5428 qemu_put_be64s(f, &env->kernelgsbase);
5429 #endif
5430 qemu_put_be32s(f, &env->smbase);
5433 #ifdef USE_X86LDOUBLE
5434 /* XXX: add that in a FPU generic layer */
5435 union x86_longdouble {
5436 uint64_t mant;
5437 uint16_t exp;
5440 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5441 #define EXPBIAS1 1023
5442 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5443 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5445 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5447 int e;
5448 /* mantissa */
5449 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5450 /* exponent + sign */
5451 e = EXPD1(temp) - EXPBIAS1 + 16383;
5452 e |= SIGND1(temp) >> 16;
5453 p->exp = e;
5455 #endif
5457 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5459 CPUState *env = opaque;
5460 int i, guess_mmx;
5461 uint32_t hflags;
5462 uint16_t fpus, fpuc, fptag, fpregs_format;
5464 if (version_id != 3 && version_id != 4)
5465 return -EINVAL;
5466 for(i = 0; i < CPU_NB_REGS; i++)
5467 qemu_get_betls(f, &env->regs[i]);
5468 qemu_get_betls(f, &env->eip);
5469 qemu_get_betls(f, &env->eflags);
5470 qemu_get_be32s(f, &hflags);
5472 qemu_get_be16s(f, &fpuc);
5473 qemu_get_be16s(f, &fpus);
5474 qemu_get_be16s(f, &fptag);
5475 qemu_get_be16s(f, &fpregs_format);
5477 /* NOTE: we cannot always restore the FPU state if the image come
5478 from a host with a different 'USE_X86LDOUBLE' define. We guess
5479 if we are in an MMX state to restore correctly in that case. */
5480 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5481 for(i = 0; i < 8; i++) {
5482 uint64_t mant;
5483 uint16_t exp;
5485 switch(fpregs_format) {
5486 case 0:
5487 mant = qemu_get_be64(f);
5488 exp = qemu_get_be16(f);
5489 #ifdef USE_X86LDOUBLE
5490 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5491 #else
5492 /* difficult case */
5493 if (guess_mmx)
5494 env->fpregs[i].mmx.MMX_Q(0) = mant;
5495 else
5496 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5497 #endif
5498 break;
5499 case 1:
5500 mant = qemu_get_be64(f);
5501 #ifdef USE_X86LDOUBLE
5503 union x86_longdouble *p;
5504 /* difficult case */
5505 p = (void *)&env->fpregs[i];
5506 if (guess_mmx) {
5507 p->mant = mant;
5508 p->exp = 0xffff;
5509 } else {
5510 fp64_to_fp80(p, mant);
5513 #else
5514 env->fpregs[i].mmx.MMX_Q(0) = mant;
5515 #endif
5516 break;
5517 default:
5518 return -EINVAL;
5522 env->fpuc = fpuc;
5523 /* XXX: restore FPU round state */
5524 env->fpstt = (fpus >> 11) & 7;
5525 env->fpus = fpus & ~0x3800;
5526 fptag ^= 0xff;
5527 for(i = 0; i < 8; i++) {
5528 env->fptags[i] = (fptag >> i) & 1;
5531 for(i = 0; i < 6; i++)
5532 cpu_get_seg(f, &env->segs[i]);
5533 cpu_get_seg(f, &env->ldt);
5534 cpu_get_seg(f, &env->tr);
5535 cpu_get_seg(f, &env->gdt);
5536 cpu_get_seg(f, &env->idt);
5538 qemu_get_be32s(f, &env->sysenter_cs);
5539 qemu_get_be32s(f, &env->sysenter_esp);
5540 qemu_get_be32s(f, &env->sysenter_eip);
5542 qemu_get_betls(f, &env->cr[0]);
5543 qemu_get_betls(f, &env->cr[2]);
5544 qemu_get_betls(f, &env->cr[3]);
5545 qemu_get_betls(f, &env->cr[4]);
5547 for(i = 0; i < 8; i++)
5548 qemu_get_betls(f, &env->dr[i]);
5550 /* MMU */
5551 qemu_get_be32s(f, &env->a20_mask);
5553 qemu_get_be32s(f, &env->mxcsr);
5554 for(i = 0; i < CPU_NB_REGS; i++) {
5555 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5556 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5559 #ifdef TARGET_X86_64
5560 qemu_get_be64s(f, &env->efer);
5561 qemu_get_be64s(f, &env->star);
5562 qemu_get_be64s(f, &env->lstar);
5563 qemu_get_be64s(f, &env->cstar);
5564 qemu_get_be64s(f, &env->fmask);
5565 qemu_get_be64s(f, &env->kernelgsbase);
5566 #endif
5567 if (version_id >= 4)
5568 qemu_get_be32s(f, &env->smbase);
5570 /* XXX: compute hflags from scratch, except for CPL and IIF */
5571 env->hflags = hflags;
5572 tlb_flush(env, 1);
5573 return 0;
5576 #elif defined(TARGET_PPC)
5577 void cpu_save(QEMUFile *f, void *opaque)
5581 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5583 return 0;
5586 #elif defined(TARGET_MIPS)
5587 void cpu_save(QEMUFile *f, void *opaque)
5591 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5593 return 0;
5596 #elif defined(TARGET_SPARC)
5597 void cpu_save(QEMUFile *f, void *opaque)
5599 CPUState *env = opaque;
5600 int i;
5601 uint32_t tmp;
5603 for(i = 0; i < 8; i++)
5604 qemu_put_betls(f, &env->gregs[i]);
5605 for(i = 0; i < NWINDOWS * 16; i++)
5606 qemu_put_betls(f, &env->regbase[i]);
5608 /* FPU */
5609 for(i = 0; i < TARGET_FPREGS; i++) {
5610 union {
5611 float32 f;
5612 uint32_t i;
5613 } u;
5614 u.f = env->fpr[i];
5615 qemu_put_be32(f, u.i);
5618 qemu_put_betls(f, &env->pc);
5619 qemu_put_betls(f, &env->npc);
5620 qemu_put_betls(f, &env->y);
5621 tmp = GET_PSR(env);
5622 qemu_put_be32(f, tmp);
5623 qemu_put_betls(f, &env->fsr);
5624 qemu_put_betls(f, &env->tbr);
5625 #ifndef TARGET_SPARC64
5626 qemu_put_be32s(f, &env->wim);
5627 /* MMU */
5628 for(i = 0; i < 16; i++)
5629 qemu_put_be32s(f, &env->mmuregs[i]);
5630 #endif
5633 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5635 CPUState *env = opaque;
5636 int i;
5637 uint32_t tmp;
5639 for(i = 0; i < 8; i++)
5640 qemu_get_betls(f, &env->gregs[i]);
5641 for(i = 0; i < NWINDOWS * 16; i++)
5642 qemu_get_betls(f, &env->regbase[i]);
5644 /* FPU */
5645 for(i = 0; i < TARGET_FPREGS; i++) {
5646 union {
5647 float32 f;
5648 uint32_t i;
5649 } u;
5650 u.i = qemu_get_be32(f);
5651 env->fpr[i] = u.f;
5654 qemu_get_betls(f, &env->pc);
5655 qemu_get_betls(f, &env->npc);
5656 qemu_get_betls(f, &env->y);
5657 tmp = qemu_get_be32(f);
5658 env->cwp = 0; /* needed to ensure that the wrapping registers are
5659 correctly updated */
5660 PUT_PSR(env, tmp);
5661 qemu_get_betls(f, &env->fsr);
5662 qemu_get_betls(f, &env->tbr);
5663 #ifndef TARGET_SPARC64
5664 qemu_get_be32s(f, &env->wim);
5665 /* MMU */
5666 for(i = 0; i < 16; i++)
5667 qemu_get_be32s(f, &env->mmuregs[i]);
5668 #endif
5669 tlb_flush(env, 1);
5670 return 0;
5673 #elif defined(TARGET_ARM)
5675 /* ??? Need to implement these. */
5676 void cpu_save(QEMUFile *f, void *opaque)
5680 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5682 return 0;
5685 #else
5687 #warning No CPU save/restore functions
5689 #endif
5691 /***********************************************************/
5692 /* ram save/restore */
5694 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5696 int v;
5698 v = qemu_get_byte(f);
5699 switch(v) {
5700 case 0:
5701 if (qemu_get_buffer(f, buf, len) != len)
5702 return -EIO;
5703 break;
5704 case 1:
5705 v = qemu_get_byte(f);
5706 memset(buf, v, len);
5707 break;
5708 default:
5709 return -EINVAL;
5711 return 0;
5714 static int ram_load_v1(QEMUFile *f, void *opaque)
5716 int i, ret;
5718 if (qemu_get_be32(f) != phys_ram_size)
5719 return -EINVAL;
5720 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5721 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5722 if (ret)
5723 return ret;
5725 return 0;
5728 #define BDRV_HASH_BLOCK_SIZE 1024
5729 #define IOBUF_SIZE 4096
5730 #define RAM_CBLOCK_MAGIC 0xfabe
5732 typedef struct RamCompressState {
5733 z_stream zstream;
5734 QEMUFile *f;
5735 uint8_t buf[IOBUF_SIZE];
5736 } RamCompressState;
5738 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5740 int ret;
5741 memset(s, 0, sizeof(*s));
5742 s->f = f;
5743 ret = deflateInit2(&s->zstream, 1,
5744 Z_DEFLATED, 15,
5745 9, Z_DEFAULT_STRATEGY);
5746 if (ret != Z_OK)
5747 return -1;
5748 s->zstream.avail_out = IOBUF_SIZE;
5749 s->zstream.next_out = s->buf;
5750 return 0;
5753 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5755 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5756 qemu_put_be16(s->f, len);
5757 qemu_put_buffer(s->f, buf, len);
5760 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5762 int ret;
5764 s->zstream.avail_in = len;
5765 s->zstream.next_in = (uint8_t *)buf;
5766 while (s->zstream.avail_in > 0) {
5767 ret = deflate(&s->zstream, Z_NO_FLUSH);
5768 if (ret != Z_OK)
5769 return -1;
5770 if (s->zstream.avail_out == 0) {
5771 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5772 s->zstream.avail_out = IOBUF_SIZE;
5773 s->zstream.next_out = s->buf;
5776 return 0;
5779 static void ram_compress_close(RamCompressState *s)
5781 int len, ret;
5783 /* compress last bytes */
5784 for(;;) {
5785 ret = deflate(&s->zstream, Z_FINISH);
5786 if (ret == Z_OK || ret == Z_STREAM_END) {
5787 len = IOBUF_SIZE - s->zstream.avail_out;
5788 if (len > 0) {
5789 ram_put_cblock(s, s->buf, len);
5791 s->zstream.avail_out = IOBUF_SIZE;
5792 s->zstream.next_out = s->buf;
5793 if (ret == Z_STREAM_END)
5794 break;
5795 } else {
5796 goto fail;
5799 fail:
5800 deflateEnd(&s->zstream);
5803 typedef struct RamDecompressState {
5804 z_stream zstream;
5805 QEMUFile *f;
5806 uint8_t buf[IOBUF_SIZE];
5807 } RamDecompressState;
5809 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5811 int ret;
5812 memset(s, 0, sizeof(*s));
5813 s->f = f;
5814 ret = inflateInit(&s->zstream);
5815 if (ret != Z_OK)
5816 return -1;
5817 return 0;
5820 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5822 int ret, clen;
5824 s->zstream.avail_out = len;
5825 s->zstream.next_out = buf;
5826 while (s->zstream.avail_out > 0) {
5827 if (s->zstream.avail_in == 0) {
5828 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5829 return -1;
5830 clen = qemu_get_be16(s->f);
5831 if (clen > IOBUF_SIZE)
5832 return -1;
5833 qemu_get_buffer(s->f, s->buf, clen);
5834 s->zstream.avail_in = clen;
5835 s->zstream.next_in = s->buf;
5837 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5838 if (ret != Z_OK && ret != Z_STREAM_END) {
5839 return -1;
5842 return 0;
5845 static void ram_decompress_close(RamDecompressState *s)
5847 inflateEnd(&s->zstream);
5850 static void ram_save(QEMUFile *f, void *opaque)
5852 int i;
5853 RamCompressState s1, *s = &s1;
5854 uint8_t buf[10];
5856 qemu_put_be32(f, phys_ram_size);
5857 if (ram_compress_open(s, f) < 0)
5858 return;
5859 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5860 #if 0
5861 if (tight_savevm_enabled) {
5862 int64_t sector_num;
5863 int j;
5865 /* find if the memory block is available on a virtual
5866 block device */
5867 sector_num = -1;
5868 for(j = 0; j < MAX_DISKS; j++) {
5869 if (bs_table[j]) {
5870 sector_num = bdrv_hash_find(bs_table[j],
5871 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5872 if (sector_num >= 0)
5873 break;
5876 if (j == MAX_DISKS)
5877 goto normal_compress;
5878 buf[0] = 1;
5879 buf[1] = j;
5880 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5881 ram_compress_buf(s, buf, 10);
5882 } else
5883 #endif
5885 // normal_compress:
5886 buf[0] = 0;
5887 ram_compress_buf(s, buf, 1);
5888 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5891 ram_compress_close(s);
5894 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5896 RamDecompressState s1, *s = &s1;
5897 uint8_t buf[10];
5898 int i;
5900 if (version_id == 1)
5901 return ram_load_v1(f, opaque);
5902 if (version_id != 2)
5903 return -EINVAL;
5904 if (qemu_get_be32(f) != phys_ram_size)
5905 return -EINVAL;
5906 if (ram_decompress_open(s, f) < 0)
5907 return -EINVAL;
5908 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5909 if (ram_decompress_buf(s, buf, 1) < 0) {
5910 fprintf(stderr, "Error while reading ram block header\n");
5911 goto error;
5913 if (buf[0] == 0) {
5914 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5915 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5916 goto error;
5918 } else
5919 #if 0
5920 if (buf[0] == 1) {
5921 int bs_index;
5922 int64_t sector_num;
5924 ram_decompress_buf(s, buf + 1, 9);
5925 bs_index = buf[1];
5926 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5927 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5928 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5929 goto error;
5931 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5932 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5933 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5934 bs_index, sector_num);
5935 goto error;
5937 } else
5938 #endif
5940 error:
5941 printf("Error block header\n");
5942 return -EINVAL;
5945 ram_decompress_close(s);
5946 return 0;
5949 /***********************************************************/
5950 /* bottom halves (can be seen as timers which expire ASAP) */
5952 struct QEMUBH {
5953 QEMUBHFunc *cb;
5954 void *opaque;
5955 int scheduled;
5956 QEMUBH *next;
5959 static QEMUBH *first_bh = NULL;
5961 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5963 QEMUBH *bh;
5964 bh = qemu_mallocz(sizeof(QEMUBH));
5965 if (!bh)
5966 return NULL;
5967 bh->cb = cb;
5968 bh->opaque = opaque;
5969 return bh;
5972 int qemu_bh_poll(void)
5974 QEMUBH *bh, **pbh;
5975 int ret;
5977 ret = 0;
5978 for(;;) {
5979 pbh = &first_bh;
5980 bh = *pbh;
5981 if (!bh)
5982 break;
5983 ret = 1;
5984 *pbh = bh->next;
5985 bh->scheduled = 0;
5986 bh->cb(bh->opaque);
5988 return ret;
5991 void qemu_bh_schedule(QEMUBH *bh)
5993 CPUState *env = cpu_single_env;
5994 if (bh->scheduled)
5995 return;
5996 bh->scheduled = 1;
5997 bh->next = first_bh;
5998 first_bh = bh;
6000 /* stop the currently executing CPU to execute the BH ASAP */
6001 if (env) {
6002 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6006 void qemu_bh_cancel(QEMUBH *bh)
6008 QEMUBH **pbh;
6009 if (bh->scheduled) {
6010 pbh = &first_bh;
6011 while (*pbh != bh)
6012 pbh = &(*pbh)->next;
6013 *pbh = bh->next;
6014 bh->scheduled = 0;
6018 void qemu_bh_delete(QEMUBH *bh)
6020 qemu_bh_cancel(bh);
6021 qemu_free(bh);
6024 /***********************************************************/
6025 /* machine registration */
6027 QEMUMachine *first_machine = NULL;
6029 int qemu_register_machine(QEMUMachine *m)
6031 QEMUMachine **pm;
6032 pm = &first_machine;
6033 while (*pm != NULL)
6034 pm = &(*pm)->next;
6035 m->next = NULL;
6036 *pm = m;
6037 return 0;
6040 QEMUMachine *find_machine(const char *name)
6042 QEMUMachine *m;
6044 for(m = first_machine; m != NULL; m = m->next) {
6045 if (!strcmp(m->name, name))
6046 return m;
6048 return NULL;
6051 /***********************************************************/
6052 /* main execution loop */
6054 void gui_update(void *opaque)
6056 display_state.dpy_refresh(&display_state);
6057 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6060 struct vm_change_state_entry {
6061 VMChangeStateHandler *cb;
6062 void *opaque;
6063 LIST_ENTRY (vm_change_state_entry) entries;
6066 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6068 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6069 void *opaque)
6071 VMChangeStateEntry *e;
6073 e = qemu_mallocz(sizeof (*e));
6074 if (!e)
6075 return NULL;
6077 e->cb = cb;
6078 e->opaque = opaque;
6079 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6080 return e;
6083 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6085 LIST_REMOVE (e, entries);
6086 qemu_free (e);
6089 static void vm_state_notify(int running)
6091 VMChangeStateEntry *e;
6093 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6094 e->cb(e->opaque, running);
6098 /* XXX: support several handlers */
6099 static VMStopHandler *vm_stop_cb;
6100 static void *vm_stop_opaque;
6102 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6104 vm_stop_cb = cb;
6105 vm_stop_opaque = opaque;
6106 return 0;
6109 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6111 vm_stop_cb = NULL;
6114 void vm_start(void)
6116 if (!vm_running) {
6117 cpu_enable_ticks();
6118 vm_running = 1;
6119 vm_state_notify(1);
6123 void vm_stop(int reason)
6125 if (vm_running) {
6126 cpu_disable_ticks();
6127 vm_running = 0;
6128 if (reason != 0) {
6129 if (vm_stop_cb) {
6130 vm_stop_cb(vm_stop_opaque, reason);
6133 vm_state_notify(0);
6137 /* reset/shutdown handler */
6139 typedef struct QEMUResetEntry {
6140 QEMUResetHandler *func;
6141 void *opaque;
6142 struct QEMUResetEntry *next;
6143 } QEMUResetEntry;
6145 static QEMUResetEntry *first_reset_entry;
6146 static int reset_requested;
6147 static int shutdown_requested;
6148 static int powerdown_requested;
6150 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6152 QEMUResetEntry **pre, *re;
6154 pre = &first_reset_entry;
6155 while (*pre != NULL)
6156 pre = &(*pre)->next;
6157 re = qemu_mallocz(sizeof(QEMUResetEntry));
6158 re->func = func;
6159 re->opaque = opaque;
6160 re->next = NULL;
6161 *pre = re;
6164 static void qemu_system_reset(void)
6166 QEMUResetEntry *re;
6168 /* reset all devices */
6169 for(re = first_reset_entry; re != NULL; re = re->next) {
6170 re->func(re->opaque);
6174 void qemu_system_reset_request(void)
6176 if (no_reboot) {
6177 shutdown_requested = 1;
6178 } else {
6179 reset_requested = 1;
6181 if (cpu_single_env)
6182 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6185 void qemu_system_shutdown_request(void)
6187 shutdown_requested = 1;
6188 if (cpu_single_env)
6189 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6192 void qemu_system_powerdown_request(void)
6194 powerdown_requested = 1;
6195 if (cpu_single_env)
6196 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6199 void main_loop_wait(int timeout)
6201 IOHandlerRecord *ioh;
6202 fd_set rfds, wfds, xfds;
6203 int ret, nfds;
6204 #ifdef _WIN32
6205 int ret2, i;
6206 #endif
6207 struct timeval tv;
6208 PollingEntry *pe;
6211 /* XXX: need to suppress polling by better using win32 events */
6212 ret = 0;
6213 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6214 ret |= pe->func(pe->opaque);
6216 #ifdef _WIN32
6217 if (ret == 0) {
6218 int err;
6219 WaitObjects *w = &wait_objects;
6221 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6222 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6223 if (w->func[ret - WAIT_OBJECT_0])
6224 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6226 /* Check for additional signaled events */
6227 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6229 /* Check if event is signaled */
6230 ret2 = WaitForSingleObject(w->events[i], 0);
6231 if(ret2 == WAIT_OBJECT_0) {
6232 if (w->func[i])
6233 w->func[i](w->opaque[i]);
6234 } else if (ret2 == WAIT_TIMEOUT) {
6235 } else {
6236 err = GetLastError();
6237 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6240 } else if (ret == WAIT_TIMEOUT) {
6241 } else {
6242 err = GetLastError();
6243 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6246 #endif
6247 /* poll any events */
6248 /* XXX: separate device handlers from system ones */
6249 nfds = -1;
6250 FD_ZERO(&rfds);
6251 FD_ZERO(&wfds);
6252 FD_ZERO(&xfds);
6253 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6254 if (ioh->deleted)
6255 continue;
6256 if (ioh->fd_read &&
6257 (!ioh->fd_read_poll ||
6258 ioh->fd_read_poll(ioh->opaque) != 0)) {
6259 FD_SET(ioh->fd, &rfds);
6260 if (ioh->fd > nfds)
6261 nfds = ioh->fd;
6263 if (ioh->fd_write) {
6264 FD_SET(ioh->fd, &wfds);
6265 if (ioh->fd > nfds)
6266 nfds = ioh->fd;
6270 tv.tv_sec = 0;
6271 #ifdef _WIN32
6272 tv.tv_usec = 0;
6273 #else
6274 tv.tv_usec = timeout * 1000;
6275 #endif
6276 #if defined(CONFIG_SLIRP)
6277 if (slirp_inited) {
6278 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6280 #endif
6281 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6282 if (ret > 0) {
6283 IOHandlerRecord **pioh;
6285 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6286 if (ioh->deleted)
6287 continue;
6288 if (FD_ISSET(ioh->fd, &rfds)) {
6289 ioh->fd_read(ioh->opaque);
6291 if (FD_ISSET(ioh->fd, &wfds)) {
6292 ioh->fd_write(ioh->opaque);
6296 /* remove deleted IO handlers */
6297 pioh = &first_io_handler;
6298 while (*pioh) {
6299 ioh = *pioh;
6300 if (ioh->deleted) {
6301 *pioh = ioh->next;
6302 qemu_free(ioh);
6303 } else
6304 pioh = &ioh->next;
6307 #if defined(CONFIG_SLIRP)
6308 if (slirp_inited) {
6309 if (ret < 0) {
6310 FD_ZERO(&rfds);
6311 FD_ZERO(&wfds);
6312 FD_ZERO(&xfds);
6314 slirp_select_poll(&rfds, &wfds, &xfds);
6316 #endif
6317 qemu_aio_poll();
6318 qemu_bh_poll();
6320 if (vm_running) {
6321 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6322 qemu_get_clock(vm_clock));
6323 /* run dma transfers, if any */
6324 DMA_run();
6327 /* real time timers */
6328 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6329 qemu_get_clock(rt_clock));
6332 static CPUState *cur_cpu;
6334 int main_loop(void)
6336 int ret, timeout;
6337 #ifdef CONFIG_PROFILER
6338 int64_t ti;
6339 #endif
6340 CPUState *env;
6342 cur_cpu = first_cpu;
6343 for(;;) {
6344 if (vm_running) {
6346 env = cur_cpu;
6347 for(;;) {
6348 /* get next cpu */
6349 env = env->next_cpu;
6350 if (!env)
6351 env = first_cpu;
6352 #ifdef CONFIG_PROFILER
6353 ti = profile_getclock();
6354 #endif
6355 ret = cpu_exec(env);
6356 #ifdef CONFIG_PROFILER
6357 qemu_time += profile_getclock() - ti;
6358 #endif
6359 if (ret == EXCP_HLT) {
6360 /* Give the next CPU a chance to run. */
6361 cur_cpu = env;
6362 continue;
6364 if (ret != EXCP_HALTED)
6365 break;
6366 /* all CPUs are halted ? */
6367 if (env == cur_cpu)
6368 break;
6370 cur_cpu = env;
6372 if (shutdown_requested) {
6373 ret = EXCP_INTERRUPT;
6374 break;
6376 if (reset_requested) {
6377 reset_requested = 0;
6378 qemu_system_reset();
6379 ret = EXCP_INTERRUPT;
6381 if (powerdown_requested) {
6382 powerdown_requested = 0;
6383 qemu_system_powerdown();
6384 ret = EXCP_INTERRUPT;
6386 if (ret == EXCP_DEBUG) {
6387 vm_stop(EXCP_DEBUG);
6389 /* If all cpus are halted then wait until the next IRQ */
6390 /* XXX: use timeout computed from timers */
6391 if (ret == EXCP_HALTED)
6392 timeout = 10;
6393 else
6394 timeout = 0;
6395 } else {
6396 timeout = 10;
6398 #ifdef CONFIG_PROFILER
6399 ti = profile_getclock();
6400 #endif
6401 main_loop_wait(timeout);
6402 #ifdef CONFIG_PROFILER
6403 dev_time += profile_getclock() - ti;
6404 #endif
6406 cpu_disable_ticks();
6407 return ret;
6410 void help(void)
6412 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6413 "usage: %s [options] [disk_image]\n"
6414 "\n"
6415 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6416 "\n"
6417 "Standard options:\n"
6418 "-M machine select emulated machine (-M ? for list)\n"
6419 "-cpu cpu select CPU (-cpu ? for list)\n"
6420 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6421 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6422 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6423 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6424 "-mtdblock file use 'file' as on-board Flash memory image\n"
6425 "-sd file use 'file' as SecureDigital card image\n"
6426 "-pflash file use 'file' as a parallel flash image\n"
6427 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6428 "-snapshot write to temporary files instead of disk image files\n"
6429 #ifdef CONFIG_SDL
6430 "-no-frame open SDL window without a frame and window decorations\n"
6431 "-no-quit disable SDL window close capability\n"
6432 #endif
6433 #ifdef TARGET_I386
6434 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6435 #endif
6436 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6437 "-smp n set the number of CPUs to 'n' [default=1]\n"
6438 "-nographic disable graphical output and redirect serial I/Os to console\n"
6439 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6440 #ifndef _WIN32
6441 "-k language use keyboard layout (for example \"fr\" for French)\n"
6442 #endif
6443 #ifdef HAS_AUDIO
6444 "-audio-help print list of audio drivers and their options\n"
6445 "-soundhw c1,... enable audio support\n"
6446 " and only specified sound cards (comma separated list)\n"
6447 " use -soundhw ? to get the list of supported cards\n"
6448 " use -soundhw all to enable all of them\n"
6449 #endif
6450 "-localtime set the real time clock to local time [default=utc]\n"
6451 "-full-screen start in full screen\n"
6452 #ifdef TARGET_I386
6453 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6454 #endif
6455 "-usb enable the USB driver (will be the default soon)\n"
6456 "-usbdevice name add the host or guest USB device 'name'\n"
6457 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6458 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6459 #endif
6460 "-name string set the name of the guest\n"
6461 "\n"
6462 "Network options:\n"
6463 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6464 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6465 #ifdef CONFIG_SLIRP
6466 "-net user[,vlan=n][,hostname=host]\n"
6467 " connect the user mode network stack to VLAN 'n' and send\n"
6468 " hostname 'host' to DHCP clients\n"
6469 #endif
6470 #ifdef _WIN32
6471 "-net tap[,vlan=n],ifname=name\n"
6472 " connect the host TAP network interface to VLAN 'n'\n"
6473 #else
6474 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6475 " connect the host TAP network interface to VLAN 'n' and use\n"
6476 " the network script 'file' (default=%s);\n"
6477 " use 'script=no' to disable script execution;\n"
6478 " use 'fd=h' to connect to an already opened TAP interface\n"
6479 #endif
6480 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6481 " connect the vlan 'n' to another VLAN using a socket connection\n"
6482 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6483 " connect the vlan 'n' to multicast maddr and port\n"
6484 "-net none use it alone to have zero network devices; if no -net option\n"
6485 " is provided, the default is '-net nic -net user'\n"
6486 "\n"
6487 #ifdef CONFIG_SLIRP
6488 "-tftp dir allow tftp access to files in dir [-net user]\n"
6489 "-bootp file advertise file in BOOTP replies\n"
6490 #ifndef _WIN32
6491 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6492 #endif
6493 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6494 " redirect TCP or UDP connections from host to guest [-net user]\n"
6495 #endif
6496 "\n"
6497 "Linux boot specific:\n"
6498 "-kernel bzImage use 'bzImage' as kernel image\n"
6499 "-append cmdline use 'cmdline' as kernel command line\n"
6500 "-initrd file use 'file' as initial ram disk\n"
6501 "\n"
6502 "Debug/Expert options:\n"
6503 "-monitor dev redirect the monitor to char device 'dev'\n"
6504 "-serial dev redirect the serial port to char device 'dev'\n"
6505 "-parallel dev redirect the parallel port to char device 'dev'\n"
6506 "-pidfile file Write PID to 'file'\n"
6507 "-S freeze CPU at startup (use 'c' to start execution)\n"
6508 "-s wait gdb connection to port\n"
6509 "-p port set gdb connection port [default=%s]\n"
6510 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6511 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6512 " translation (t=none or lba) (usually qemu can guess them)\n"
6513 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6514 #ifdef USE_KQEMU
6515 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6516 "-no-kqemu disable KQEMU kernel module usage\n"
6517 #endif
6518 #ifdef USE_CODE_COPY
6519 "-no-code-copy disable code copy acceleration\n"
6520 #endif
6521 #ifdef TARGET_I386
6522 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6523 " (default is CL-GD5446 PCI VGA)\n"
6524 "-no-acpi disable ACPI\n"
6525 #endif
6526 "-no-reboot exit instead of rebooting\n"
6527 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6528 "-vnc display start a VNC server on display\n"
6529 #ifndef _WIN32
6530 "-daemonize daemonize QEMU after initializing\n"
6531 #endif
6532 "-option-rom rom load a file, rom, into the option ROM space\n"
6533 #ifdef TARGET_SPARC
6534 "-prom-env variable=value set OpenBIOS nvram variables\n"
6535 #endif
6536 "\n"
6537 "During emulation, the following keys are useful:\n"
6538 "ctrl-alt-f toggle full screen\n"
6539 "ctrl-alt-n switch to virtual console 'n'\n"
6540 "ctrl-alt toggle mouse and keyboard grab\n"
6541 "\n"
6542 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6544 "qemu",
6545 DEFAULT_RAM_SIZE,
6546 #ifndef _WIN32
6547 DEFAULT_NETWORK_SCRIPT,
6548 #endif
6549 DEFAULT_GDBSTUB_PORT,
6550 "/tmp/qemu.log");
6551 exit(1);
6554 #define HAS_ARG 0x0001
6556 enum {
6557 QEMU_OPTION_h,
6559 QEMU_OPTION_M,
6560 QEMU_OPTION_cpu,
6561 QEMU_OPTION_fda,
6562 QEMU_OPTION_fdb,
6563 QEMU_OPTION_hda,
6564 QEMU_OPTION_hdb,
6565 QEMU_OPTION_hdc,
6566 QEMU_OPTION_hdd,
6567 QEMU_OPTION_cdrom,
6568 QEMU_OPTION_mtdblock,
6569 QEMU_OPTION_sd,
6570 QEMU_OPTION_pflash,
6571 QEMU_OPTION_boot,
6572 QEMU_OPTION_snapshot,
6573 #ifdef TARGET_I386
6574 QEMU_OPTION_no_fd_bootchk,
6575 #endif
6576 QEMU_OPTION_m,
6577 QEMU_OPTION_nographic,
6578 QEMU_OPTION_portrait,
6579 #ifdef HAS_AUDIO
6580 QEMU_OPTION_audio_help,
6581 QEMU_OPTION_soundhw,
6582 #endif
6584 QEMU_OPTION_net,
6585 QEMU_OPTION_tftp,
6586 QEMU_OPTION_bootp,
6587 QEMU_OPTION_smb,
6588 QEMU_OPTION_redir,
6590 QEMU_OPTION_kernel,
6591 QEMU_OPTION_append,
6592 QEMU_OPTION_initrd,
6594 QEMU_OPTION_S,
6595 QEMU_OPTION_s,
6596 QEMU_OPTION_p,
6597 QEMU_OPTION_d,
6598 QEMU_OPTION_hdachs,
6599 QEMU_OPTION_L,
6600 QEMU_OPTION_no_code_copy,
6601 QEMU_OPTION_k,
6602 QEMU_OPTION_localtime,
6603 QEMU_OPTION_cirrusvga,
6604 QEMU_OPTION_vmsvga,
6605 QEMU_OPTION_g,
6606 QEMU_OPTION_std_vga,
6607 QEMU_OPTION_echr,
6608 QEMU_OPTION_monitor,
6609 QEMU_OPTION_serial,
6610 QEMU_OPTION_parallel,
6611 QEMU_OPTION_loadvm,
6612 QEMU_OPTION_full_screen,
6613 QEMU_OPTION_no_frame,
6614 QEMU_OPTION_no_quit,
6615 QEMU_OPTION_pidfile,
6616 QEMU_OPTION_no_kqemu,
6617 QEMU_OPTION_kernel_kqemu,
6618 QEMU_OPTION_win2k_hack,
6619 QEMU_OPTION_usb,
6620 QEMU_OPTION_usbdevice,
6621 QEMU_OPTION_smp,
6622 QEMU_OPTION_vnc,
6623 QEMU_OPTION_no_acpi,
6624 QEMU_OPTION_no_reboot,
6625 QEMU_OPTION_show_cursor,
6626 QEMU_OPTION_daemonize,
6627 QEMU_OPTION_option_rom,
6628 QEMU_OPTION_semihosting,
6629 QEMU_OPTION_name,
6630 QEMU_OPTION_prom_env,
6633 typedef struct QEMUOption {
6634 const char *name;
6635 int flags;
6636 int index;
6637 } QEMUOption;
6639 const QEMUOption qemu_options[] = {
6640 { "h", 0, QEMU_OPTION_h },
6641 { "help", 0, QEMU_OPTION_h },
6643 { "M", HAS_ARG, QEMU_OPTION_M },
6644 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6645 { "fda", HAS_ARG, QEMU_OPTION_fda },
6646 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6647 { "hda", HAS_ARG, QEMU_OPTION_hda },
6648 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6649 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6650 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6651 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6652 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6653 { "sd", HAS_ARG, QEMU_OPTION_sd },
6654 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6655 { "boot", HAS_ARG, QEMU_OPTION_boot },
6656 { "snapshot", 0, QEMU_OPTION_snapshot },
6657 #ifdef TARGET_I386
6658 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6659 #endif
6660 { "m", HAS_ARG, QEMU_OPTION_m },
6661 { "nographic", 0, QEMU_OPTION_nographic },
6662 { "portrait", 0, QEMU_OPTION_portrait },
6663 { "k", HAS_ARG, QEMU_OPTION_k },
6664 #ifdef HAS_AUDIO
6665 { "audio-help", 0, QEMU_OPTION_audio_help },
6666 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6667 #endif
6669 { "net", HAS_ARG, QEMU_OPTION_net},
6670 #ifdef CONFIG_SLIRP
6671 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6672 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6673 #ifndef _WIN32
6674 { "smb", HAS_ARG, QEMU_OPTION_smb },
6675 #endif
6676 { "redir", HAS_ARG, QEMU_OPTION_redir },
6677 #endif
6679 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6680 { "append", HAS_ARG, QEMU_OPTION_append },
6681 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6683 { "S", 0, QEMU_OPTION_S },
6684 { "s", 0, QEMU_OPTION_s },
6685 { "p", HAS_ARG, QEMU_OPTION_p },
6686 { "d", HAS_ARG, QEMU_OPTION_d },
6687 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6688 { "L", HAS_ARG, QEMU_OPTION_L },
6689 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6690 #ifdef USE_KQEMU
6691 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6692 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6693 #endif
6694 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6695 { "g", 1, QEMU_OPTION_g },
6696 #endif
6697 { "localtime", 0, QEMU_OPTION_localtime },
6698 { "std-vga", 0, QEMU_OPTION_std_vga },
6699 { "echr", 1, QEMU_OPTION_echr },
6700 { "monitor", 1, QEMU_OPTION_monitor },
6701 { "serial", 1, QEMU_OPTION_serial },
6702 { "parallel", 1, QEMU_OPTION_parallel },
6703 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6704 { "full-screen", 0, QEMU_OPTION_full_screen },
6705 #ifdef CONFIG_SDL
6706 { "no-frame", 0, QEMU_OPTION_no_frame },
6707 { "no-quit", 0, QEMU_OPTION_no_quit },
6708 #endif
6709 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6710 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6711 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6712 { "smp", HAS_ARG, QEMU_OPTION_smp },
6713 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6715 /* temporary options */
6716 { "usb", 0, QEMU_OPTION_usb },
6717 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6718 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6719 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6720 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6721 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6722 { "daemonize", 0, QEMU_OPTION_daemonize },
6723 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6724 #if defined(TARGET_ARM)
6725 { "semihosting", 0, QEMU_OPTION_semihosting },
6726 #endif
6727 { "name", HAS_ARG, QEMU_OPTION_name },
6728 #if defined(TARGET_SPARC)
6729 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6730 #endif
6731 { NULL },
6734 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6736 /* this stack is only used during signal handling */
6737 #define SIGNAL_STACK_SIZE 32768
6739 static uint8_t *signal_stack;
6741 #endif
6743 /* password input */
6745 int qemu_key_check(BlockDriverState *bs, const char *name)
6747 char password[256];
6748 int i;
6750 if (!bdrv_is_encrypted(bs))
6751 return 0;
6753 term_printf("%s is encrypted.\n", name);
6754 for(i = 0; i < 3; i++) {
6755 monitor_readline("Password: ", 1, password, sizeof(password));
6756 if (bdrv_set_key(bs, password) == 0)
6757 return 0;
6758 term_printf("invalid password\n");
6760 return -EPERM;
6763 static BlockDriverState *get_bdrv(int index)
6765 BlockDriverState *bs;
6767 if (index < 4) {
6768 bs = bs_table[index];
6769 } else if (index < 6) {
6770 bs = fd_table[index - 4];
6771 } else {
6772 bs = NULL;
6774 return bs;
6777 static void read_passwords(void)
6779 BlockDriverState *bs;
6780 int i;
6782 for(i = 0; i < 6; i++) {
6783 bs = get_bdrv(i);
6784 if (bs)
6785 qemu_key_check(bs, bdrv_get_device_name(bs));
6789 /* XXX: currently we cannot use simultaneously different CPUs */
6790 void register_machines(void)
6792 #if defined(TARGET_I386)
6793 qemu_register_machine(&pc_machine);
6794 qemu_register_machine(&isapc_machine);
6795 #elif defined(TARGET_PPC)
6796 qemu_register_machine(&heathrow_machine);
6797 qemu_register_machine(&core99_machine);
6798 qemu_register_machine(&prep_machine);
6799 qemu_register_machine(&ref405ep_machine);
6800 qemu_register_machine(&taihu_machine);
6801 #elif defined(TARGET_MIPS)
6802 qemu_register_machine(&mips_machine);
6803 qemu_register_machine(&mips_malta_machine);
6804 qemu_register_machine(&mips_pica61_machine);
6805 #elif defined(TARGET_SPARC)
6806 #ifdef TARGET_SPARC64
6807 qemu_register_machine(&sun4u_machine);
6808 #else
6809 qemu_register_machine(&ss5_machine);
6810 qemu_register_machine(&ss10_machine);
6811 #endif
6812 #elif defined(TARGET_ARM)
6813 qemu_register_machine(&integratorcp_machine);
6814 qemu_register_machine(&versatilepb_machine);
6815 qemu_register_machine(&versatileab_machine);
6816 qemu_register_machine(&realview_machine);
6817 qemu_register_machine(&akitapda_machine);
6818 qemu_register_machine(&spitzpda_machine);
6819 qemu_register_machine(&borzoipda_machine);
6820 qemu_register_machine(&terrierpda_machine);
6821 #elif defined(TARGET_SH4)
6822 qemu_register_machine(&shix_machine);
6823 #elif defined(TARGET_ALPHA)
6824 /* XXX: TODO */
6825 #else
6826 #error unsupported CPU
6827 #endif
6830 #ifdef HAS_AUDIO
6831 struct soundhw soundhw[] = {
6832 #ifdef HAS_AUDIO_CHOICE
6833 #ifdef TARGET_I386
6835 "pcspk",
6836 "PC speaker",
6839 { .init_isa = pcspk_audio_init }
6841 #endif
6843 "sb16",
6844 "Creative Sound Blaster 16",
6847 { .init_isa = SB16_init }
6850 #ifdef CONFIG_ADLIB
6852 "adlib",
6853 #ifdef HAS_YMF262
6854 "Yamaha YMF262 (OPL3)",
6855 #else
6856 "Yamaha YM3812 (OPL2)",
6857 #endif
6860 { .init_isa = Adlib_init }
6862 #endif
6864 #ifdef CONFIG_GUS
6866 "gus",
6867 "Gravis Ultrasound GF1",
6870 { .init_isa = GUS_init }
6872 #endif
6875 "es1370",
6876 "ENSONIQ AudioPCI ES1370",
6879 { .init_pci = es1370_init }
6881 #endif
6883 { NULL, NULL, 0, 0, { NULL } }
6886 static void select_soundhw (const char *optarg)
6888 struct soundhw *c;
6890 if (*optarg == '?') {
6891 show_valid_cards:
6893 printf ("Valid sound card names (comma separated):\n");
6894 for (c = soundhw; c->name; ++c) {
6895 printf ("%-11s %s\n", c->name, c->descr);
6897 printf ("\n-soundhw all will enable all of the above\n");
6898 exit (*optarg != '?');
6900 else {
6901 size_t l;
6902 const char *p;
6903 char *e;
6904 int bad_card = 0;
6906 if (!strcmp (optarg, "all")) {
6907 for (c = soundhw; c->name; ++c) {
6908 c->enabled = 1;
6910 return;
6913 p = optarg;
6914 while (*p) {
6915 e = strchr (p, ',');
6916 l = !e ? strlen (p) : (size_t) (e - p);
6918 for (c = soundhw; c->name; ++c) {
6919 if (!strncmp (c->name, p, l)) {
6920 c->enabled = 1;
6921 break;
6925 if (!c->name) {
6926 if (l > 80) {
6927 fprintf (stderr,
6928 "Unknown sound card name (too big to show)\n");
6930 else {
6931 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6932 (int) l, p);
6934 bad_card = 1;
6936 p += l + (e != NULL);
6939 if (bad_card)
6940 goto show_valid_cards;
6943 #endif
6945 #ifdef _WIN32
6946 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6948 exit(STATUS_CONTROL_C_EXIT);
6949 return TRUE;
6951 #endif
6953 #define MAX_NET_CLIENTS 32
6955 int main(int argc, char **argv)
6957 #ifdef CONFIG_GDBSTUB
6958 int use_gdbstub;
6959 const char *gdbstub_port;
6960 #endif
6961 int i, cdrom_index, pflash_index;
6962 int snapshot, linux_boot;
6963 const char *initrd_filename;
6964 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6965 const char *pflash_filename[MAX_PFLASH];
6966 const char *sd_filename;
6967 const char *mtd_filename;
6968 const char *kernel_filename, *kernel_cmdline;
6969 DisplayState *ds = &display_state;
6970 int cyls, heads, secs, translation;
6971 char net_clients[MAX_NET_CLIENTS][256];
6972 int nb_net_clients;
6973 int optind;
6974 const char *r, *optarg;
6975 CharDriverState *monitor_hd;
6976 char monitor_device[128];
6977 char serial_devices[MAX_SERIAL_PORTS][128];
6978 int serial_device_index;
6979 char parallel_devices[MAX_PARALLEL_PORTS][128];
6980 int parallel_device_index;
6981 const char *loadvm = NULL;
6982 QEMUMachine *machine;
6983 const char *cpu_model;
6984 char usb_devices[MAX_USB_CMDLINE][128];
6985 int usb_devices_index;
6986 int fds[2];
6987 const char *pid_file = NULL;
6989 LIST_INIT (&vm_change_state_head);
6990 #ifndef _WIN32
6992 struct sigaction act;
6993 sigfillset(&act.sa_mask);
6994 act.sa_flags = 0;
6995 act.sa_handler = SIG_IGN;
6996 sigaction(SIGPIPE, &act, NULL);
6998 #else
6999 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7000 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7001 QEMU to run on a single CPU */
7003 HANDLE h;
7004 DWORD mask, smask;
7005 int i;
7006 h = GetCurrentProcess();
7007 if (GetProcessAffinityMask(h, &mask, &smask)) {
7008 for(i = 0; i < 32; i++) {
7009 if (mask & (1 << i))
7010 break;
7012 if (i != 32) {
7013 mask = 1 << i;
7014 SetProcessAffinityMask(h, mask);
7018 #endif
7020 register_machines();
7021 machine = first_machine;
7022 cpu_model = NULL;
7023 initrd_filename = NULL;
7024 for(i = 0; i < MAX_FD; i++)
7025 fd_filename[i] = NULL;
7026 for(i = 0; i < MAX_DISKS; i++)
7027 hd_filename[i] = NULL;
7028 for(i = 0; i < MAX_PFLASH; i++)
7029 pflash_filename[i] = NULL;
7030 pflash_index = 0;
7031 sd_filename = NULL;
7032 mtd_filename = NULL;
7033 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7034 vga_ram_size = VGA_RAM_SIZE;
7035 #ifdef CONFIG_GDBSTUB
7036 use_gdbstub = 0;
7037 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7038 #endif
7039 snapshot = 0;
7040 nographic = 0;
7041 kernel_filename = NULL;
7042 kernel_cmdline = "";
7043 #ifdef TARGET_PPC
7044 cdrom_index = 1;
7045 #else
7046 cdrom_index = 2;
7047 #endif
7048 cyls = heads = secs = 0;
7049 translation = BIOS_ATA_TRANSLATION_AUTO;
7050 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7052 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7053 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7054 serial_devices[i][0] = '\0';
7055 serial_device_index = 0;
7057 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7058 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7059 parallel_devices[i][0] = '\0';
7060 parallel_device_index = 0;
7062 usb_devices_index = 0;
7064 nb_net_clients = 0;
7066 nb_nics = 0;
7067 /* default mac address of the first network interface */
7069 optind = 1;
7070 for(;;) {
7071 if (optind >= argc)
7072 break;
7073 r = argv[optind];
7074 if (r[0] != '-') {
7075 hd_filename[0] = argv[optind++];
7076 } else {
7077 const QEMUOption *popt;
7079 optind++;
7080 /* Treat --foo the same as -foo. */
7081 if (r[1] == '-')
7082 r++;
7083 popt = qemu_options;
7084 for(;;) {
7085 if (!popt->name) {
7086 fprintf(stderr, "%s: invalid option -- '%s'\n",
7087 argv[0], r);
7088 exit(1);
7090 if (!strcmp(popt->name, r + 1))
7091 break;
7092 popt++;
7094 if (popt->flags & HAS_ARG) {
7095 if (optind >= argc) {
7096 fprintf(stderr, "%s: option '%s' requires an argument\n",
7097 argv[0], r);
7098 exit(1);
7100 optarg = argv[optind++];
7101 } else {
7102 optarg = NULL;
7105 switch(popt->index) {
7106 case QEMU_OPTION_M:
7107 machine = find_machine(optarg);
7108 if (!machine) {
7109 QEMUMachine *m;
7110 printf("Supported machines are:\n");
7111 for(m = first_machine; m != NULL; m = m->next) {
7112 printf("%-10s %s%s\n",
7113 m->name, m->desc,
7114 m == first_machine ? " (default)" : "");
7116 exit(1);
7118 break;
7119 case QEMU_OPTION_cpu:
7120 /* hw initialization will check this */
7121 if (optarg[0] == '?') {
7122 #if defined(TARGET_PPC)
7123 ppc_cpu_list(stdout, &fprintf);
7124 #elif defined(TARGET_ARM)
7125 arm_cpu_list();
7126 #elif defined(TARGET_MIPS)
7127 mips_cpu_list(stdout, &fprintf);
7128 #elif defined(TARGET_SPARC)
7129 sparc_cpu_list(stdout, &fprintf);
7130 #endif
7131 exit(1);
7132 } else {
7133 cpu_model = optarg;
7135 break;
7136 case QEMU_OPTION_initrd:
7137 initrd_filename = optarg;
7138 break;
7139 case QEMU_OPTION_hda:
7140 case QEMU_OPTION_hdb:
7141 case QEMU_OPTION_hdc:
7142 case QEMU_OPTION_hdd:
7144 int hd_index;
7145 hd_index = popt->index - QEMU_OPTION_hda;
7146 hd_filename[hd_index] = optarg;
7147 if (hd_index == cdrom_index)
7148 cdrom_index = -1;
7150 break;
7151 case QEMU_OPTION_mtdblock:
7152 mtd_filename = optarg;
7153 break;
7154 case QEMU_OPTION_sd:
7155 sd_filename = optarg;
7156 break;
7157 case QEMU_OPTION_pflash:
7158 if (pflash_index >= MAX_PFLASH) {
7159 fprintf(stderr, "qemu: too many parallel flash images\n");
7160 exit(1);
7162 pflash_filename[pflash_index++] = optarg;
7163 break;
7164 case QEMU_OPTION_snapshot:
7165 snapshot = 1;
7166 break;
7167 case QEMU_OPTION_hdachs:
7169 const char *p;
7170 p = optarg;
7171 cyls = strtol(p, (char **)&p, 0);
7172 if (cyls < 1 || cyls > 16383)
7173 goto chs_fail;
7174 if (*p != ',')
7175 goto chs_fail;
7176 p++;
7177 heads = strtol(p, (char **)&p, 0);
7178 if (heads < 1 || heads > 16)
7179 goto chs_fail;
7180 if (*p != ',')
7181 goto chs_fail;
7182 p++;
7183 secs = strtol(p, (char **)&p, 0);
7184 if (secs < 1 || secs > 63)
7185 goto chs_fail;
7186 if (*p == ',') {
7187 p++;
7188 if (!strcmp(p, "none"))
7189 translation = BIOS_ATA_TRANSLATION_NONE;
7190 else if (!strcmp(p, "lba"))
7191 translation = BIOS_ATA_TRANSLATION_LBA;
7192 else if (!strcmp(p, "auto"))
7193 translation = BIOS_ATA_TRANSLATION_AUTO;
7194 else
7195 goto chs_fail;
7196 } else if (*p != '\0') {
7197 chs_fail:
7198 fprintf(stderr, "qemu: invalid physical CHS format\n");
7199 exit(1);
7202 break;
7203 case QEMU_OPTION_nographic:
7204 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7205 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7206 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7207 nographic = 1;
7208 break;
7209 case QEMU_OPTION_portrait:
7210 graphic_rotate = 1;
7211 break;
7212 case QEMU_OPTION_kernel:
7213 kernel_filename = optarg;
7214 break;
7215 case QEMU_OPTION_append:
7216 kernel_cmdline = optarg;
7217 break;
7218 case QEMU_OPTION_cdrom:
7219 if (cdrom_index >= 0) {
7220 hd_filename[cdrom_index] = optarg;
7222 break;
7223 case QEMU_OPTION_boot:
7224 boot_device = optarg[0];
7225 if (boot_device != 'a' &&
7226 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7227 // Network boot
7228 boot_device != 'n' &&
7229 #endif
7230 boot_device != 'c' && boot_device != 'd') {
7231 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7232 exit(1);
7234 break;
7235 case QEMU_OPTION_fda:
7236 fd_filename[0] = optarg;
7237 break;
7238 case QEMU_OPTION_fdb:
7239 fd_filename[1] = optarg;
7240 break;
7241 #ifdef TARGET_I386
7242 case QEMU_OPTION_no_fd_bootchk:
7243 fd_bootchk = 0;
7244 break;
7245 #endif
7246 case QEMU_OPTION_no_code_copy:
7247 code_copy_enabled = 0;
7248 break;
7249 case QEMU_OPTION_net:
7250 if (nb_net_clients >= MAX_NET_CLIENTS) {
7251 fprintf(stderr, "qemu: too many network clients\n");
7252 exit(1);
7254 pstrcpy(net_clients[nb_net_clients],
7255 sizeof(net_clients[0]),
7256 optarg);
7257 nb_net_clients++;
7258 break;
7259 #ifdef CONFIG_SLIRP
7260 case QEMU_OPTION_tftp:
7261 tftp_prefix = optarg;
7262 break;
7263 case QEMU_OPTION_bootp:
7264 bootp_filename = optarg;
7265 break;
7266 #ifndef _WIN32
7267 case QEMU_OPTION_smb:
7268 net_slirp_smb(optarg);
7269 break;
7270 #endif
7271 case QEMU_OPTION_redir:
7272 net_slirp_redir(optarg);
7273 break;
7274 #endif
7275 #ifdef HAS_AUDIO
7276 case QEMU_OPTION_audio_help:
7277 AUD_help ();
7278 exit (0);
7279 break;
7280 case QEMU_OPTION_soundhw:
7281 select_soundhw (optarg);
7282 break;
7283 #endif
7284 case QEMU_OPTION_h:
7285 help();
7286 break;
7287 case QEMU_OPTION_m:
7288 ram_size = atoi(optarg) * 1024 * 1024;
7289 if (ram_size <= 0)
7290 help();
7291 if (ram_size > PHYS_RAM_MAX_SIZE) {
7292 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7293 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7294 exit(1);
7296 break;
7297 case QEMU_OPTION_d:
7299 int mask;
7300 CPULogItem *item;
7302 mask = cpu_str_to_log_mask(optarg);
7303 if (!mask) {
7304 printf("Log items (comma separated):\n");
7305 for(item = cpu_log_items; item->mask != 0; item++) {
7306 printf("%-10s %s\n", item->name, item->help);
7308 exit(1);
7310 cpu_set_log(mask);
7312 break;
7313 #ifdef CONFIG_GDBSTUB
7314 case QEMU_OPTION_s:
7315 use_gdbstub = 1;
7316 break;
7317 case QEMU_OPTION_p:
7318 gdbstub_port = optarg;
7319 break;
7320 #endif
7321 case QEMU_OPTION_L:
7322 bios_dir = optarg;
7323 break;
7324 case QEMU_OPTION_S:
7325 autostart = 0;
7326 break;
7327 case QEMU_OPTION_k:
7328 keyboard_layout = optarg;
7329 break;
7330 case QEMU_OPTION_localtime:
7331 rtc_utc = 0;
7332 break;
7333 case QEMU_OPTION_cirrusvga:
7334 cirrus_vga_enabled = 1;
7335 vmsvga_enabled = 0;
7336 break;
7337 case QEMU_OPTION_vmsvga:
7338 cirrus_vga_enabled = 0;
7339 vmsvga_enabled = 1;
7340 break;
7341 case QEMU_OPTION_std_vga:
7342 cirrus_vga_enabled = 0;
7343 vmsvga_enabled = 0;
7344 break;
7345 case QEMU_OPTION_g:
7347 const char *p;
7348 int w, h, depth;
7349 p = optarg;
7350 w = strtol(p, (char **)&p, 10);
7351 if (w <= 0) {
7352 graphic_error:
7353 fprintf(stderr, "qemu: invalid resolution or depth\n");
7354 exit(1);
7356 if (*p != 'x')
7357 goto graphic_error;
7358 p++;
7359 h = strtol(p, (char **)&p, 10);
7360 if (h <= 0)
7361 goto graphic_error;
7362 if (*p == 'x') {
7363 p++;
7364 depth = strtol(p, (char **)&p, 10);
7365 if (depth != 8 && depth != 15 && depth != 16 &&
7366 depth != 24 && depth != 32)
7367 goto graphic_error;
7368 } else if (*p == '\0') {
7369 depth = graphic_depth;
7370 } else {
7371 goto graphic_error;
7374 graphic_width = w;
7375 graphic_height = h;
7376 graphic_depth = depth;
7378 break;
7379 case QEMU_OPTION_echr:
7381 char *r;
7382 term_escape_char = strtol(optarg, &r, 0);
7383 if (r == optarg)
7384 printf("Bad argument to echr\n");
7385 break;
7387 case QEMU_OPTION_monitor:
7388 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7389 break;
7390 case QEMU_OPTION_serial:
7391 if (serial_device_index >= MAX_SERIAL_PORTS) {
7392 fprintf(stderr, "qemu: too many serial ports\n");
7393 exit(1);
7395 pstrcpy(serial_devices[serial_device_index],
7396 sizeof(serial_devices[0]), optarg);
7397 serial_device_index++;
7398 break;
7399 case QEMU_OPTION_parallel:
7400 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7401 fprintf(stderr, "qemu: too many parallel ports\n");
7402 exit(1);
7404 pstrcpy(parallel_devices[parallel_device_index],
7405 sizeof(parallel_devices[0]), optarg);
7406 parallel_device_index++;
7407 break;
7408 case QEMU_OPTION_loadvm:
7409 loadvm = optarg;
7410 break;
7411 case QEMU_OPTION_full_screen:
7412 full_screen = 1;
7413 break;
7414 #ifdef CONFIG_SDL
7415 case QEMU_OPTION_no_frame:
7416 no_frame = 1;
7417 break;
7418 case QEMU_OPTION_no_quit:
7419 no_quit = 1;
7420 break;
7421 #endif
7422 case QEMU_OPTION_pidfile:
7423 pid_file = optarg;
7424 break;
7425 #ifdef TARGET_I386
7426 case QEMU_OPTION_win2k_hack:
7427 win2k_install_hack = 1;
7428 break;
7429 #endif
7430 #ifdef USE_KQEMU
7431 case QEMU_OPTION_no_kqemu:
7432 kqemu_allowed = 0;
7433 break;
7434 case QEMU_OPTION_kernel_kqemu:
7435 kqemu_allowed = 2;
7436 break;
7437 #endif
7438 case QEMU_OPTION_usb:
7439 usb_enabled = 1;
7440 break;
7441 case QEMU_OPTION_usbdevice:
7442 usb_enabled = 1;
7443 if (usb_devices_index >= MAX_USB_CMDLINE) {
7444 fprintf(stderr, "Too many USB devices\n");
7445 exit(1);
7447 pstrcpy(usb_devices[usb_devices_index],
7448 sizeof(usb_devices[usb_devices_index]),
7449 optarg);
7450 usb_devices_index++;
7451 break;
7452 case QEMU_OPTION_smp:
7453 smp_cpus = atoi(optarg);
7454 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7455 fprintf(stderr, "Invalid number of CPUs\n");
7456 exit(1);
7458 break;
7459 case QEMU_OPTION_vnc:
7460 vnc_display = optarg;
7461 break;
7462 case QEMU_OPTION_no_acpi:
7463 acpi_enabled = 0;
7464 break;
7465 case QEMU_OPTION_no_reboot:
7466 no_reboot = 1;
7467 break;
7468 case QEMU_OPTION_show_cursor:
7469 cursor_hide = 0;
7470 break;
7471 case QEMU_OPTION_daemonize:
7472 daemonize = 1;
7473 break;
7474 case QEMU_OPTION_option_rom:
7475 if (nb_option_roms >= MAX_OPTION_ROMS) {
7476 fprintf(stderr, "Too many option ROMs\n");
7477 exit(1);
7479 option_rom[nb_option_roms] = optarg;
7480 nb_option_roms++;
7481 break;
7482 case QEMU_OPTION_semihosting:
7483 semihosting_enabled = 1;
7484 break;
7485 case QEMU_OPTION_name:
7486 qemu_name = optarg;
7487 break;
7488 #ifdef TARGET_SPARC
7489 case QEMU_OPTION_prom_env:
7490 if (nb_prom_envs >= MAX_PROM_ENVS) {
7491 fprintf(stderr, "Too many prom variables\n");
7492 exit(1);
7494 prom_envs[nb_prom_envs] = optarg;
7495 nb_prom_envs++;
7496 break;
7497 #endif
7502 #ifndef _WIN32
7503 if (daemonize && !nographic && vnc_display == NULL) {
7504 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7505 daemonize = 0;
7508 if (daemonize) {
7509 pid_t pid;
7511 if (pipe(fds) == -1)
7512 exit(1);
7514 pid = fork();
7515 if (pid > 0) {
7516 uint8_t status;
7517 ssize_t len;
7519 close(fds[1]);
7521 again:
7522 len = read(fds[0], &status, 1);
7523 if (len == -1 && (errno == EINTR))
7524 goto again;
7526 if (len != 1)
7527 exit(1);
7528 else if (status == 1) {
7529 fprintf(stderr, "Could not acquire pidfile\n");
7530 exit(1);
7531 } else
7532 exit(0);
7533 } else if (pid < 0)
7534 exit(1);
7536 setsid();
7538 pid = fork();
7539 if (pid > 0)
7540 exit(0);
7541 else if (pid < 0)
7542 exit(1);
7544 umask(027);
7545 chdir("/");
7547 signal(SIGTSTP, SIG_IGN);
7548 signal(SIGTTOU, SIG_IGN);
7549 signal(SIGTTIN, SIG_IGN);
7551 #endif
7553 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7554 if (daemonize) {
7555 uint8_t status = 1;
7556 write(fds[1], &status, 1);
7557 } else
7558 fprintf(stderr, "Could not acquire pid file\n");
7559 exit(1);
7562 #ifdef USE_KQEMU
7563 if (smp_cpus > 1)
7564 kqemu_allowed = 0;
7565 #endif
7566 linux_boot = (kernel_filename != NULL);
7568 if (!linux_boot &&
7569 boot_device != 'n' &&
7570 hd_filename[0] == '\0' &&
7571 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7572 fd_filename[0] == '\0')
7573 help();
7575 /* boot to floppy or the default cd if no hard disk defined yet */
7576 if (hd_filename[0] == '\0' && boot_device == 'c') {
7577 if (fd_filename[0] != '\0')
7578 boot_device = 'a';
7579 else
7580 boot_device = 'd';
7583 setvbuf(stdout, NULL, _IOLBF, 0);
7585 init_timers();
7586 init_timer_alarm();
7587 qemu_aio_init();
7589 #ifdef _WIN32
7590 socket_init();
7591 #endif
7593 /* init network clients */
7594 if (nb_net_clients == 0) {
7595 /* if no clients, we use a default config */
7596 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7597 "nic");
7598 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7599 "user");
7600 nb_net_clients = 2;
7603 for(i = 0;i < nb_net_clients; i++) {
7604 if (net_client_init(net_clients[i]) < 0)
7605 exit(1);
7608 #ifdef TARGET_I386
7609 if (boot_device == 'n') {
7610 for (i = 0; i < nb_nics; i++) {
7611 const char *model = nd_table[i].model;
7612 char buf[1024];
7613 if (model == NULL)
7614 model = "ne2k_pci";
7615 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7616 if (get_image_size(buf) > 0) {
7617 option_rom[nb_option_roms] = strdup(buf);
7618 nb_option_roms++;
7619 break;
7622 if (i == nb_nics) {
7623 fprintf(stderr, "No valid PXE rom found for network device\n");
7624 exit(1);
7626 boot_device = 'c'; /* to prevent confusion by the BIOS */
7628 #endif
7630 /* init the memory */
7631 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7633 phys_ram_base = qemu_vmalloc(phys_ram_size);
7634 if (!phys_ram_base) {
7635 fprintf(stderr, "Could not allocate physical memory\n");
7636 exit(1);
7639 /* we always create the cdrom drive, even if no disk is there */
7640 bdrv_init();
7641 if (cdrom_index >= 0) {
7642 bs_table[cdrom_index] = bdrv_new("cdrom");
7643 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7646 /* open the virtual block devices */
7647 for(i = 0; i < MAX_DISKS; i++) {
7648 if (hd_filename[i]) {
7649 if (!bs_table[i]) {
7650 char buf[64];
7651 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7652 bs_table[i] = bdrv_new(buf);
7654 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7655 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7656 hd_filename[i]);
7657 exit(1);
7659 if (i == 0 && cyls != 0) {
7660 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7661 bdrv_set_translation_hint(bs_table[i], translation);
7666 /* we always create at least one floppy disk */
7667 fd_table[0] = bdrv_new("fda");
7668 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7670 for(i = 0; i < MAX_FD; i++) {
7671 if (fd_filename[i]) {
7672 if (!fd_table[i]) {
7673 char buf[64];
7674 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7675 fd_table[i] = bdrv_new(buf);
7676 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7678 if (fd_filename[i][0] != '\0') {
7679 if (bdrv_open(fd_table[i], fd_filename[i],
7680 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7681 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7682 fd_filename[i]);
7683 exit(1);
7689 /* Open the virtual parallel flash block devices */
7690 for(i = 0; i < MAX_PFLASH; i++) {
7691 if (pflash_filename[i]) {
7692 if (!pflash_table[i]) {
7693 char buf[64];
7694 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7695 pflash_table[i] = bdrv_new(buf);
7697 if (bdrv_open(pflash_table[i], pflash_filename[i],
7698 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7699 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7700 pflash_filename[i]);
7701 exit(1);
7706 sd_bdrv = bdrv_new ("sd");
7707 /* FIXME: This isn't really a floppy, but it's a reasonable
7708 approximation. */
7709 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7710 if (sd_filename) {
7711 if (bdrv_open(sd_bdrv, sd_filename,
7712 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7713 fprintf(stderr, "qemu: could not open SD card image %s\n",
7714 sd_filename);
7715 } else
7716 qemu_key_check(sd_bdrv, sd_filename);
7719 if (mtd_filename) {
7720 mtd_bdrv = bdrv_new ("mtd");
7721 if (bdrv_open(mtd_bdrv, mtd_filename,
7722 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7723 qemu_key_check(mtd_bdrv, mtd_filename)) {
7724 fprintf(stderr, "qemu: could not open Flash image %s\n",
7725 mtd_filename);
7726 bdrv_delete(mtd_bdrv);
7727 mtd_bdrv = 0;
7731 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7732 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7734 init_ioports();
7736 /* terminal init */
7737 if (nographic) {
7738 dumb_display_init(ds);
7739 } else if (vnc_display != NULL) {
7740 vnc_display_init(ds, vnc_display);
7741 } else {
7742 #if defined(CONFIG_SDL)
7743 sdl_display_init(ds, full_screen, no_frame);
7744 #elif defined(CONFIG_COCOA)
7745 cocoa_display_init(ds, full_screen);
7746 #else
7747 dumb_display_init(ds);
7748 #endif
7751 /* Maintain compatibility with multiple stdio monitors */
7752 if (!strcmp(monitor_device,"stdio")) {
7753 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7754 if (!strcmp(serial_devices[i],"mon:stdio")) {
7755 monitor_device[0] = '\0';
7756 break;
7757 } else if (!strcmp(serial_devices[i],"stdio")) {
7758 monitor_device[0] = '\0';
7759 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7760 break;
7764 if (monitor_device[0] != '\0') {
7765 monitor_hd = qemu_chr_open(monitor_device);
7766 if (!monitor_hd) {
7767 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7768 exit(1);
7770 monitor_init(monitor_hd, !nographic);
7773 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7774 const char *devname = serial_devices[i];
7775 if (devname[0] != '\0' && strcmp(devname, "none")) {
7776 serial_hds[i] = qemu_chr_open(devname);
7777 if (!serial_hds[i]) {
7778 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7779 devname);
7780 exit(1);
7782 if (!strcmp(devname, "vc"))
7783 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7787 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7788 const char *devname = parallel_devices[i];
7789 if (devname[0] != '\0' && strcmp(devname, "none")) {
7790 parallel_hds[i] = qemu_chr_open(devname);
7791 if (!parallel_hds[i]) {
7792 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7793 devname);
7794 exit(1);
7796 if (!strcmp(devname, "vc"))
7797 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7801 machine->init(ram_size, vga_ram_size, boot_device,
7802 ds, fd_filename, snapshot,
7803 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7805 /* init USB devices */
7806 if (usb_enabled) {
7807 for(i = 0; i < usb_devices_index; i++) {
7808 if (usb_device_add(usb_devices[i]) < 0) {
7809 fprintf(stderr, "Warning: could not add USB device %s\n",
7810 usb_devices[i]);
7815 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7816 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7818 #ifdef CONFIG_GDBSTUB
7819 if (use_gdbstub) {
7820 /* XXX: use standard host:port notation and modify options
7821 accordingly. */
7822 if (gdbserver_start(gdbstub_port) < 0) {
7823 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7824 gdbstub_port);
7825 exit(1);
7827 } else
7828 #endif
7829 if (loadvm)
7830 do_loadvm(loadvm);
7833 /* XXX: simplify init */
7834 read_passwords();
7835 if (autostart) {
7836 vm_start();
7840 if (daemonize) {
7841 uint8_t status = 0;
7842 ssize_t len;
7843 int fd;
7845 again1:
7846 len = write(fds[1], &status, 1);
7847 if (len == -1 && (errno == EINTR))
7848 goto again1;
7850 if (len != 1)
7851 exit(1);
7853 fd = open("/dev/null", O_RDWR);
7854 if (fd == -1)
7855 exit(1);
7857 dup2(fd, 0);
7858 dup2(fd, 1);
7859 dup2(fd, 2);
7861 close(fd);
7864 main_loop();
7865 quit_timers();
7866 return 0;