Fix some debugging mistakes/leftovers
[qemu-kvm/fedora.git] / vl.c
blobe8410a8a1b9785e59aa1791e19ccffbd80d7410d
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <signal.h>
45 #include <time.h>
46 #include <errno.h>
47 #include <sys/time.h>
48 #include <zlib.h>
50 #ifndef _WIN32
51 #include <sys/times.h>
52 #include <sys/wait.h>
53 #include <termios.h>
54 #include <sys/poll.h>
55 #include <sys/mman.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <dirent.h>
60 #include <netdb.h>
61 #include <sys/select.h>
62 #include <arpa/inet.h>
63 #ifdef _BSD
64 #include <sys/stat.h>
65 #if !defined(__APPLE__) && !defined(__OpenBSD__)
66 #include <libutil.h>
67 #endif
68 #ifdef __OpenBSD__
69 #include <net/if.h>
70 #endif
71 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72 #include <freebsd/stdlib.h>
73 #else
74 #ifdef __linux__
75 #include <linux/if.h>
76 #include <linux/if_tun.h>
77 #include <pty.h>
78 #include <malloc.h>
79 #include <linux/rtc.h>
81 /* For the benefit of older linux systems which don't supply it,
82 we use a local copy of hpet.h. */
83 /* #include <linux/hpet.h> */
84 #include "hpet.h"
86 #include <linux/ppdev.h>
87 #include <linux/parport.h>
88 #endif
89 #ifdef __sun__
90 #include <sys/stat.h>
91 #include <sys/ethernet.h>
92 #include <sys/sockio.h>
93 #include <netinet/arp.h>
94 #include <netinet/in.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_icmp.h> // must come after ip.h
98 #include <netinet/udp.h>
99 #include <netinet/tcp.h>
100 #include <net/if.h>
101 #include <syslog.h>
102 #include <stropts.h>
103 #endif
104 #endif
105 #endif
107 #include "qemu_socket.h"
109 #if defined(CONFIG_SLIRP)
110 #include "libslirp.h"
111 #endif
113 #if defined(__OpenBSD__)
114 #include <util.h>
115 #endif
117 #if defined(CONFIG_VDE)
118 #include <libvdeplug.h>
119 #endif
121 #ifdef _WIN32
122 #include <malloc.h>
123 #include <sys/timeb.h>
124 #include <mmsystem.h>
125 #define getopt_long_only getopt_long
126 #define memalign(align, size) malloc(size)
127 #endif
129 #ifdef CONFIG_SDL
130 #ifdef __APPLE__
131 #include <SDL/SDL.h>
132 #endif
133 #endif /* CONFIG_SDL */
135 #ifdef CONFIG_COCOA
136 #undef main
137 #define main qemu_main
138 #endif /* CONFIG_COCOA */
140 #include "disas.h"
142 #include "exec-all.h"
144 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
145 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
146 #ifdef __sun__
147 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
148 #else
149 #define SMBD_COMMAND "/usr/sbin/smbd"
150 #endif
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
157 #ifdef TARGET_PPC
158 #define DEFAULT_RAM_SIZE 144
159 #else
160 #define DEFAULT_RAM_SIZE 128
161 #endif
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 static void *ioport_opaque[MAX_IOPORTS];
172 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 /* point to the block driver where the snapshots are managed */
179 static BlockDriverState *bs_snapshots;
180 static int vga_ram_size;
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 static DisplayState display_state;
183 int nographic;
184 static int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 int cirrus_vga_enabled = 1;
194 int vmsvga_enabled = 0;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 static int no_frame = 0;
206 int no_quit = 0;
207 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
208 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
209 #ifdef TARGET_I386
210 int win2k_install_hack = 0;
211 #endif
212 int usb_enabled = 0;
213 static VLANState *first_vlan;
214 int smp_cpus = 1;
215 const char *vnc_display;
216 int acpi_enabled = 1;
217 int fd_bootchk = 1;
218 int no_reboot = 0;
219 int no_shutdown = 0;
220 int cursor_hide = 1;
221 int graphic_rotate = 0;
222 int daemonize = 0;
223 const char *option_rom[MAX_OPTION_ROMS];
224 int nb_option_roms;
225 int semihosting_enabled = 0;
226 #ifdef TARGET_ARM
227 int old_param = 0;
228 #endif
229 const char *qemu_name;
230 int alt_grab = 0;
231 #ifdef TARGET_SPARC
232 unsigned int nb_prom_envs = 0;
233 const char *prom_envs[MAX_PROM_ENVS];
234 #endif
235 static int nb_drives_opt;
236 static struct drive_opt {
237 const char *file;
238 char opt[1024];
239 } drives_opt[MAX_DRIVES];
241 static CPUState *cur_cpu;
242 static CPUState *next_cpu;
243 static int event_pending = 1;
244 /* Conversion factor from emulated instructions to virtual clock ticks. */
245 static int icount_time_shift;
246 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
247 #define MAX_ICOUNT_SHIFT 10
248 /* Compensate for varying guest execution speed. */
249 static int64_t qemu_icount_bias;
250 static QEMUTimer *icount_rt_timer;
251 static QEMUTimer *icount_vm_timer;
253 uint8_t qemu_uuid[16];
255 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
257 /***********************************************************/
258 /* x86 ISA bus support */
260 target_phys_addr_t isa_mem_base = 0;
261 PicState2 *isa_pic;
263 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
264 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
266 static uint32_t ioport_read(int index, uint32_t address)
268 static IOPortReadFunc *default_func[3] = {
269 default_ioport_readb,
270 default_ioport_readw,
271 default_ioport_readl
273 IOPortReadFunc *func = ioport_read_table[index][address];
274 if (!func)
275 func = default_func[index];
276 return func(ioport_opaque[address], address);
279 static void ioport_write(int index, uint32_t address, uint32_t data)
281 static IOPortWriteFunc *default_func[3] = {
282 default_ioport_writeb,
283 default_ioport_writew,
284 default_ioport_writel
286 IOPortWriteFunc *func = ioport_write_table[index][address];
287 if (!func)
288 func = default_func[index];
289 func(ioport_opaque[address], address, data);
292 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr, "unused inb: port=0x%04x\n", address);
296 #endif
297 return 0xff;
300 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
302 #ifdef DEBUG_UNUSED_IOPORT
303 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
304 #endif
307 /* default is to make two byte accesses */
308 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
310 uint32_t data;
311 data = ioport_read(0, address);
312 address = (address + 1) & (MAX_IOPORTS - 1);
313 data |= ioport_read(0, address) << 8;
314 return data;
317 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
319 ioport_write(0, address, data & 0xff);
320 address = (address + 1) & (MAX_IOPORTS - 1);
321 ioport_write(0, address, (data >> 8) & 0xff);
324 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
326 #ifdef DEBUG_UNUSED_IOPORT
327 fprintf(stderr, "unused inl: port=0x%04x\n", address);
328 #endif
329 return 0xffffffff;
332 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
334 #ifdef DEBUG_UNUSED_IOPORT
335 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
336 #endif
339 /* size is the word size in byte */
340 int register_ioport_read(int start, int length, int size,
341 IOPortReadFunc *func, void *opaque)
343 int i, bsize;
345 if (size == 1) {
346 bsize = 0;
347 } else if (size == 2) {
348 bsize = 1;
349 } else if (size == 4) {
350 bsize = 2;
351 } else {
352 hw_error("register_ioport_read: invalid size");
353 return -1;
355 for(i = start; i < start + length; i += size) {
356 ioport_read_table[bsize][i] = func;
357 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
358 hw_error("register_ioport_read: invalid opaque");
359 ioport_opaque[i] = opaque;
361 return 0;
364 /* size is the word size in byte */
365 int register_ioport_write(int start, int length, int size,
366 IOPortWriteFunc *func, void *opaque)
368 int i, bsize;
370 if (size == 1) {
371 bsize = 0;
372 } else if (size == 2) {
373 bsize = 1;
374 } else if (size == 4) {
375 bsize = 2;
376 } else {
377 hw_error("register_ioport_write: invalid size");
378 return -1;
380 for(i = start; i < start + length; i += size) {
381 ioport_write_table[bsize][i] = func;
382 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
383 hw_error("register_ioport_write: invalid opaque");
384 ioport_opaque[i] = opaque;
386 return 0;
389 void isa_unassign_ioport(int start, int length)
391 int i;
393 for(i = start; i < start + length; i++) {
394 ioport_read_table[0][i] = default_ioport_readb;
395 ioport_read_table[1][i] = default_ioport_readw;
396 ioport_read_table[2][i] = default_ioport_readl;
398 ioport_write_table[0][i] = default_ioport_writeb;
399 ioport_write_table[1][i] = default_ioport_writew;
400 ioport_write_table[2][i] = default_ioport_writel;
404 /***********************************************************/
406 void cpu_outb(CPUState *env, int addr, int val)
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "outb: %04x %02x\n", addr, val);
411 #endif
412 ioport_write(0, addr, val);
413 #ifdef USE_KQEMU
414 if (env)
415 env->last_io_time = cpu_get_time_fast();
416 #endif
419 void cpu_outw(CPUState *env, int addr, int val)
421 #ifdef DEBUG_IOPORT
422 if (loglevel & CPU_LOG_IOPORT)
423 fprintf(logfile, "outw: %04x %04x\n", addr, val);
424 #endif
425 ioport_write(1, addr, val);
426 #ifdef USE_KQEMU
427 if (env)
428 env->last_io_time = cpu_get_time_fast();
429 #endif
432 void cpu_outl(CPUState *env, int addr, int val)
434 #ifdef DEBUG_IOPORT
435 if (loglevel & CPU_LOG_IOPORT)
436 fprintf(logfile, "outl: %04x %08x\n", addr, val);
437 #endif
438 ioport_write(2, addr, val);
439 #ifdef USE_KQEMU
440 if (env)
441 env->last_io_time = cpu_get_time_fast();
442 #endif
445 int cpu_inb(CPUState *env, int addr)
447 int val;
448 val = ioport_read(0, addr);
449 #ifdef DEBUG_IOPORT
450 if (loglevel & CPU_LOG_IOPORT)
451 fprintf(logfile, "inb : %04x %02x\n", addr, val);
452 #endif
453 #ifdef USE_KQEMU
454 if (env)
455 env->last_io_time = cpu_get_time_fast();
456 #endif
457 return val;
460 int cpu_inw(CPUState *env, int addr)
462 int val;
463 val = ioport_read(1, addr);
464 #ifdef DEBUG_IOPORT
465 if (loglevel & CPU_LOG_IOPORT)
466 fprintf(logfile, "inw : %04x %04x\n", addr, val);
467 #endif
468 #ifdef USE_KQEMU
469 if (env)
470 env->last_io_time = cpu_get_time_fast();
471 #endif
472 return val;
475 int cpu_inl(CPUState *env, int addr)
477 int val;
478 val = ioport_read(2, addr);
479 #ifdef DEBUG_IOPORT
480 if (loglevel & CPU_LOG_IOPORT)
481 fprintf(logfile, "inl : %04x %08x\n", addr, val);
482 #endif
483 #ifdef USE_KQEMU
484 if (env)
485 env->last_io_time = cpu_get_time_fast();
486 #endif
487 return val;
490 /***********************************************************/
491 void hw_error(const char *fmt, ...)
493 va_list ap;
494 CPUState *env;
496 va_start(ap, fmt);
497 fprintf(stderr, "qemu: hardware error: ");
498 vfprintf(stderr, fmt, ap);
499 fprintf(stderr, "\n");
500 for(env = first_cpu; env != NULL; env = env->next_cpu) {
501 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
502 #ifdef TARGET_I386
503 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
504 #else
505 cpu_dump_state(env, stderr, fprintf, 0);
506 #endif
508 va_end(ap);
509 abort();
512 /***********************************************************/
513 /* keyboard/mouse */
515 static QEMUPutKBDEvent *qemu_put_kbd_event;
516 static void *qemu_put_kbd_event_opaque;
517 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
518 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
520 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
522 qemu_put_kbd_event_opaque = opaque;
523 qemu_put_kbd_event = func;
526 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
527 void *opaque, int absolute,
528 const char *name)
530 QEMUPutMouseEntry *s, *cursor;
532 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
533 if (!s)
534 return NULL;
536 s->qemu_put_mouse_event = func;
537 s->qemu_put_mouse_event_opaque = opaque;
538 s->qemu_put_mouse_event_absolute = absolute;
539 s->qemu_put_mouse_event_name = qemu_strdup(name);
540 s->next = NULL;
542 if (!qemu_put_mouse_event_head) {
543 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
544 return s;
547 cursor = qemu_put_mouse_event_head;
548 while (cursor->next != NULL)
549 cursor = cursor->next;
551 cursor->next = s;
552 qemu_put_mouse_event_current = s;
554 return s;
557 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
559 QEMUPutMouseEntry *prev = NULL, *cursor;
561 if (!qemu_put_mouse_event_head || entry == NULL)
562 return;
564 cursor = qemu_put_mouse_event_head;
565 while (cursor != NULL && cursor != entry) {
566 prev = cursor;
567 cursor = cursor->next;
570 if (cursor == NULL) // does not exist or list empty
571 return;
572 else if (prev == NULL) { // entry is head
573 qemu_put_mouse_event_head = cursor->next;
574 if (qemu_put_mouse_event_current == entry)
575 qemu_put_mouse_event_current = cursor->next;
576 qemu_free(entry->qemu_put_mouse_event_name);
577 qemu_free(entry);
578 return;
581 prev->next = entry->next;
583 if (qemu_put_mouse_event_current == entry)
584 qemu_put_mouse_event_current = prev;
586 qemu_free(entry->qemu_put_mouse_event_name);
587 qemu_free(entry);
590 void kbd_put_keycode(int keycode)
592 if (qemu_put_kbd_event) {
593 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
597 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
599 QEMUPutMouseEvent *mouse_event;
600 void *mouse_event_opaque;
601 int width;
603 if (!qemu_put_mouse_event_current) {
604 return;
607 mouse_event =
608 qemu_put_mouse_event_current->qemu_put_mouse_event;
609 mouse_event_opaque =
610 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
612 if (mouse_event) {
613 if (graphic_rotate) {
614 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
615 width = 0x7fff;
616 else
617 width = graphic_width - 1;
618 mouse_event(mouse_event_opaque,
619 width - dy, dx, dz, buttons_state);
620 } else
621 mouse_event(mouse_event_opaque,
622 dx, dy, dz, buttons_state);
626 int kbd_mouse_is_absolute(void)
628 if (!qemu_put_mouse_event_current)
629 return 0;
631 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
634 void do_info_mice(void)
636 QEMUPutMouseEntry *cursor;
637 int index = 0;
639 if (!qemu_put_mouse_event_head) {
640 term_printf("No mouse devices connected\n");
641 return;
644 term_printf("Mouse devices available:\n");
645 cursor = qemu_put_mouse_event_head;
646 while (cursor != NULL) {
647 term_printf("%c Mouse #%d: %s\n",
648 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
649 index, cursor->qemu_put_mouse_event_name);
650 index++;
651 cursor = cursor->next;
655 void do_mouse_set(int index)
657 QEMUPutMouseEntry *cursor;
658 int i = 0;
660 if (!qemu_put_mouse_event_head) {
661 term_printf("No mouse devices connected\n");
662 return;
665 cursor = qemu_put_mouse_event_head;
666 while (cursor != NULL && index != i) {
667 i++;
668 cursor = cursor->next;
671 if (cursor != NULL)
672 qemu_put_mouse_event_current = cursor;
673 else
674 term_printf("Mouse at given index not found\n");
677 /* compute with 96 bit intermediate result: (a*b)/c */
678 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
680 union {
681 uint64_t ll;
682 struct {
683 #ifdef WORDS_BIGENDIAN
684 uint32_t high, low;
685 #else
686 uint32_t low, high;
687 #endif
688 } l;
689 } u, res;
690 uint64_t rl, rh;
692 u.ll = a;
693 rl = (uint64_t)u.l.low * (uint64_t)b;
694 rh = (uint64_t)u.l.high * (uint64_t)b;
695 rh += (rl >> 32);
696 res.l.high = rh / c;
697 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
698 return res.ll;
701 /***********************************************************/
702 /* real time host monotonic timer */
704 #define QEMU_TIMER_BASE 1000000000LL
706 #ifdef WIN32
708 static int64_t clock_freq;
710 static void init_get_clock(void)
712 LARGE_INTEGER freq;
713 int ret;
714 ret = QueryPerformanceFrequency(&freq);
715 if (ret == 0) {
716 fprintf(stderr, "Could not calibrate ticks\n");
717 exit(1);
719 clock_freq = freq.QuadPart;
722 static int64_t get_clock(void)
724 LARGE_INTEGER ti;
725 QueryPerformanceCounter(&ti);
726 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
729 #else
731 static int use_rt_clock;
733 static void init_get_clock(void)
735 use_rt_clock = 0;
736 #if defined(__linux__)
738 struct timespec ts;
739 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
740 use_rt_clock = 1;
743 #endif
746 static int64_t get_clock(void)
748 #if defined(__linux__)
749 if (use_rt_clock) {
750 struct timespec ts;
751 clock_gettime(CLOCK_MONOTONIC, &ts);
752 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
753 } else
754 #endif
756 /* XXX: using gettimeofday leads to problems if the date
757 changes, so it should be avoided. */
758 struct timeval tv;
759 gettimeofday(&tv, NULL);
760 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
763 #endif
765 /* Return the virtual CPU time, based on the instruction counter. */
766 static int64_t cpu_get_icount(void)
768 int64_t icount;
769 CPUState *env = cpu_single_env;;
770 icount = qemu_icount;
771 if (env) {
772 if (!can_do_io(env))
773 fprintf(stderr, "Bad clock read\n");
774 icount -= (env->icount_decr.u16.low + env->icount_extra);
776 return qemu_icount_bias + (icount << icount_time_shift);
779 /***********************************************************/
780 /* guest cycle counter */
782 static int64_t cpu_ticks_prev;
783 static int64_t cpu_ticks_offset;
784 static int64_t cpu_clock_offset;
785 static int cpu_ticks_enabled;
787 /* return the host CPU cycle counter and handle stop/restart */
788 int64_t cpu_get_ticks(void)
790 if (use_icount) {
791 return cpu_get_icount();
793 if (!cpu_ticks_enabled) {
794 return cpu_ticks_offset;
795 } else {
796 int64_t ticks;
797 ticks = cpu_get_real_ticks();
798 if (cpu_ticks_prev > ticks) {
799 /* Note: non increasing ticks may happen if the host uses
800 software suspend */
801 cpu_ticks_offset += cpu_ticks_prev - ticks;
803 cpu_ticks_prev = ticks;
804 return ticks + cpu_ticks_offset;
808 /* return the host CPU monotonic timer and handle stop/restart */
809 static int64_t cpu_get_clock(void)
811 int64_t ti;
812 if (!cpu_ticks_enabled) {
813 return cpu_clock_offset;
814 } else {
815 ti = get_clock();
816 return ti + cpu_clock_offset;
820 /* enable cpu_get_ticks() */
821 void cpu_enable_ticks(void)
823 if (!cpu_ticks_enabled) {
824 cpu_ticks_offset -= cpu_get_real_ticks();
825 cpu_clock_offset -= get_clock();
826 cpu_ticks_enabled = 1;
830 /* disable cpu_get_ticks() : the clock is stopped. You must not call
831 cpu_get_ticks() after that. */
832 void cpu_disable_ticks(void)
834 if (cpu_ticks_enabled) {
835 cpu_ticks_offset = cpu_get_ticks();
836 cpu_clock_offset = cpu_get_clock();
837 cpu_ticks_enabled = 0;
841 /***********************************************************/
842 /* timers */
844 #define QEMU_TIMER_REALTIME 0
845 #define QEMU_TIMER_VIRTUAL 1
847 struct QEMUClock {
848 int type;
849 /* XXX: add frequency */
852 struct QEMUTimer {
853 QEMUClock *clock;
854 int64_t expire_time;
855 QEMUTimerCB *cb;
856 void *opaque;
857 struct QEMUTimer *next;
860 struct qemu_alarm_timer {
861 char const *name;
862 unsigned int flags;
864 int (*start)(struct qemu_alarm_timer *t);
865 void (*stop)(struct qemu_alarm_timer *t);
866 void (*rearm)(struct qemu_alarm_timer *t);
867 void *priv;
870 #define ALARM_FLAG_DYNTICKS 0x1
871 #define ALARM_FLAG_EXPIRED 0x2
873 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
875 return t->flags & ALARM_FLAG_DYNTICKS;
878 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
880 if (!alarm_has_dynticks(t))
881 return;
883 t->rearm(t);
886 /* TODO: MIN_TIMER_REARM_US should be optimized */
887 #define MIN_TIMER_REARM_US 250
889 static struct qemu_alarm_timer *alarm_timer;
891 #ifdef _WIN32
893 struct qemu_alarm_win32 {
894 MMRESULT timerId;
895 HANDLE host_alarm;
896 unsigned int period;
897 } alarm_win32_data = {0, NULL, -1};
899 static int win32_start_timer(struct qemu_alarm_timer *t);
900 static void win32_stop_timer(struct qemu_alarm_timer *t);
901 static void win32_rearm_timer(struct qemu_alarm_timer *t);
903 #else
905 static int unix_start_timer(struct qemu_alarm_timer *t);
906 static void unix_stop_timer(struct qemu_alarm_timer *t);
908 #ifdef __linux__
910 static int dynticks_start_timer(struct qemu_alarm_timer *t);
911 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
912 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
914 static int hpet_start_timer(struct qemu_alarm_timer *t);
915 static void hpet_stop_timer(struct qemu_alarm_timer *t);
917 static int rtc_start_timer(struct qemu_alarm_timer *t);
918 static void rtc_stop_timer(struct qemu_alarm_timer *t);
920 #endif /* __linux__ */
922 #endif /* _WIN32 */
924 /* Correlation between real and virtual time is always going to be
925 fairly approximate, so ignore small variation.
926 When the guest is idle real and virtual time will be aligned in
927 the IO wait loop. */
928 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
930 static void icount_adjust(void)
932 int64_t cur_time;
933 int64_t cur_icount;
934 int64_t delta;
935 static int64_t last_delta;
936 /* If the VM is not running, then do nothing. */
937 if (!vm_running)
938 return;
940 cur_time = cpu_get_clock();
941 cur_icount = qemu_get_clock(vm_clock);
942 delta = cur_icount - cur_time;
943 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
944 if (delta > 0
945 && last_delta + ICOUNT_WOBBLE < delta * 2
946 && icount_time_shift > 0) {
947 /* The guest is getting too far ahead. Slow time down. */
948 icount_time_shift--;
950 if (delta < 0
951 && last_delta - ICOUNT_WOBBLE > delta * 2
952 && icount_time_shift < MAX_ICOUNT_SHIFT) {
953 /* The guest is getting too far behind. Speed time up. */
954 icount_time_shift++;
956 last_delta = delta;
957 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
960 static void icount_adjust_rt(void * opaque)
962 qemu_mod_timer(icount_rt_timer,
963 qemu_get_clock(rt_clock) + 1000);
964 icount_adjust();
967 static void icount_adjust_vm(void * opaque)
969 qemu_mod_timer(icount_vm_timer,
970 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
971 icount_adjust();
974 static void init_icount_adjust(void)
976 /* Have both realtime and virtual time triggers for speed adjustment.
977 The realtime trigger catches emulated time passing too slowly,
978 the virtual time trigger catches emulated time passing too fast.
979 Realtime triggers occur even when idle, so use them less frequently
980 than VM triggers. */
981 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
982 qemu_mod_timer(icount_rt_timer,
983 qemu_get_clock(rt_clock) + 1000);
984 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
985 qemu_mod_timer(icount_vm_timer,
986 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
989 static struct qemu_alarm_timer alarm_timers[] = {
990 #ifndef _WIN32
991 #ifdef __linux__
992 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
993 dynticks_stop_timer, dynticks_rearm_timer, NULL},
994 /* HPET - if available - is preferred */
995 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
996 /* ...otherwise try RTC */
997 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
998 #endif
999 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1000 #else
1001 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1002 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1003 {"win32", 0, win32_start_timer,
1004 win32_stop_timer, NULL, &alarm_win32_data},
1005 #endif
1006 {NULL, }
1009 static void show_available_alarms(void)
1011 int i;
1013 printf("Available alarm timers, in order of precedence:\n");
1014 for (i = 0; alarm_timers[i].name; i++)
1015 printf("%s\n", alarm_timers[i].name);
1018 static void configure_alarms(char const *opt)
1020 int i;
1021 int cur = 0;
1022 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1023 char *arg;
1024 char *name;
1025 struct qemu_alarm_timer tmp;
1027 if (!strcmp(opt, "?")) {
1028 show_available_alarms();
1029 exit(0);
1032 arg = strdup(opt);
1034 /* Reorder the array */
1035 name = strtok(arg, ",");
1036 while (name) {
1037 for (i = 0; i < count && alarm_timers[i].name; i++) {
1038 if (!strcmp(alarm_timers[i].name, name))
1039 break;
1042 if (i == count) {
1043 fprintf(stderr, "Unknown clock %s\n", name);
1044 goto next;
1047 if (i < cur)
1048 /* Ignore */
1049 goto next;
1051 /* Swap */
1052 tmp = alarm_timers[i];
1053 alarm_timers[i] = alarm_timers[cur];
1054 alarm_timers[cur] = tmp;
1056 cur++;
1057 next:
1058 name = strtok(NULL, ",");
1061 free(arg);
1063 if (cur) {
1064 /* Disable remaining timers */
1065 for (i = cur; i < count; i++)
1066 alarm_timers[i].name = NULL;
1067 } else {
1068 show_available_alarms();
1069 exit(1);
1073 QEMUClock *rt_clock;
1074 QEMUClock *vm_clock;
1076 static QEMUTimer *active_timers[2];
1078 static QEMUClock *qemu_new_clock(int type)
1080 QEMUClock *clock;
1081 clock = qemu_mallocz(sizeof(QEMUClock));
1082 if (!clock)
1083 return NULL;
1084 clock->type = type;
1085 return clock;
1088 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1090 QEMUTimer *ts;
1092 ts = qemu_mallocz(sizeof(QEMUTimer));
1093 ts->clock = clock;
1094 ts->cb = cb;
1095 ts->opaque = opaque;
1096 return ts;
1099 void qemu_free_timer(QEMUTimer *ts)
1101 qemu_free(ts);
1104 /* stop a timer, but do not dealloc it */
1105 void qemu_del_timer(QEMUTimer *ts)
1107 QEMUTimer **pt, *t;
1109 /* NOTE: this code must be signal safe because
1110 qemu_timer_expired() can be called from a signal. */
1111 pt = &active_timers[ts->clock->type];
1112 for(;;) {
1113 t = *pt;
1114 if (!t)
1115 break;
1116 if (t == ts) {
1117 *pt = t->next;
1118 break;
1120 pt = &t->next;
1124 /* modify the current timer so that it will be fired when current_time
1125 >= expire_time. The corresponding callback will be called. */
1126 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1128 QEMUTimer **pt, *t;
1130 qemu_del_timer(ts);
1132 /* add the timer in the sorted list */
1133 /* NOTE: this code must be signal safe because
1134 qemu_timer_expired() can be called from a signal. */
1135 pt = &active_timers[ts->clock->type];
1136 for(;;) {
1137 t = *pt;
1138 if (!t)
1139 break;
1140 if (t->expire_time > expire_time)
1141 break;
1142 pt = &t->next;
1144 ts->expire_time = expire_time;
1145 ts->next = *pt;
1146 *pt = ts;
1148 /* Rearm if necessary */
1149 if (pt == &active_timers[ts->clock->type]) {
1150 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1151 qemu_rearm_alarm_timer(alarm_timer);
1153 /* Interrupt execution to force deadline recalculation. */
1154 if (use_icount && cpu_single_env) {
1155 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1160 int qemu_timer_pending(QEMUTimer *ts)
1162 QEMUTimer *t;
1163 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1164 if (t == ts)
1165 return 1;
1167 return 0;
1170 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1172 if (!timer_head)
1173 return 0;
1174 return (timer_head->expire_time <= current_time);
1177 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1179 QEMUTimer *ts;
1181 for(;;) {
1182 ts = *ptimer_head;
1183 if (!ts || ts->expire_time > current_time)
1184 break;
1185 /* remove timer from the list before calling the callback */
1186 *ptimer_head = ts->next;
1187 ts->next = NULL;
1189 /* run the callback (the timer list can be modified) */
1190 ts->cb(ts->opaque);
1194 int64_t qemu_get_clock(QEMUClock *clock)
1196 switch(clock->type) {
1197 case QEMU_TIMER_REALTIME:
1198 return get_clock() / 1000000;
1199 default:
1200 case QEMU_TIMER_VIRTUAL:
1201 if (use_icount) {
1202 return cpu_get_icount();
1203 } else {
1204 return cpu_get_clock();
1209 static void init_timers(void)
1211 init_get_clock();
1212 ticks_per_sec = QEMU_TIMER_BASE;
1213 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1214 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1217 /* save a timer */
1218 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1220 uint64_t expire_time;
1222 if (qemu_timer_pending(ts)) {
1223 expire_time = ts->expire_time;
1224 } else {
1225 expire_time = -1;
1227 qemu_put_be64(f, expire_time);
1230 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1232 uint64_t expire_time;
1234 expire_time = qemu_get_be64(f);
1235 if (expire_time != -1) {
1236 qemu_mod_timer(ts, expire_time);
1237 } else {
1238 qemu_del_timer(ts);
1242 static void timer_save(QEMUFile *f, void *opaque)
1244 if (cpu_ticks_enabled) {
1245 hw_error("cannot save state if virtual timers are running");
1247 qemu_put_be64(f, cpu_ticks_offset);
1248 qemu_put_be64(f, ticks_per_sec);
1249 qemu_put_be64(f, cpu_clock_offset);
1252 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1254 if (version_id != 1 && version_id != 2)
1255 return -EINVAL;
1256 if (cpu_ticks_enabled) {
1257 return -EINVAL;
1259 cpu_ticks_offset=qemu_get_be64(f);
1260 ticks_per_sec=qemu_get_be64(f);
1261 if (version_id == 2) {
1262 cpu_clock_offset=qemu_get_be64(f);
1264 return 0;
1267 #ifdef _WIN32
1268 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1269 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1270 #else
1271 static void host_alarm_handler(int host_signum)
1272 #endif
1274 #if 0
1275 #define DISP_FREQ 1000
1277 static int64_t delta_min = INT64_MAX;
1278 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1279 static int count;
1280 ti = qemu_get_clock(vm_clock);
1281 if (last_clock != 0) {
1282 delta = ti - last_clock;
1283 if (delta < delta_min)
1284 delta_min = delta;
1285 if (delta > delta_max)
1286 delta_max = delta;
1287 delta_cum += delta;
1288 if (++count == DISP_FREQ) {
1289 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1290 muldiv64(delta_min, 1000000, ticks_per_sec),
1291 muldiv64(delta_max, 1000000, ticks_per_sec),
1292 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1293 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1294 count = 0;
1295 delta_min = INT64_MAX;
1296 delta_max = 0;
1297 delta_cum = 0;
1300 last_clock = ti;
1302 #endif
1303 if (alarm_has_dynticks(alarm_timer) ||
1304 (!use_icount &&
1305 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1306 qemu_get_clock(vm_clock))) ||
1307 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1308 qemu_get_clock(rt_clock))) {
1309 #ifdef _WIN32
1310 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1311 SetEvent(data->host_alarm);
1312 #endif
1313 CPUState *env = next_cpu;
1315 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1317 if (env) {
1318 /* stop the currently executing cpu because a timer occured */
1319 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1320 #ifdef USE_KQEMU
1321 if (env->kqemu_enabled) {
1322 kqemu_cpu_interrupt(env);
1324 #endif
1326 event_pending = 1;
1330 static int64_t qemu_next_deadline(void)
1332 int64_t delta;
1334 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1335 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1336 qemu_get_clock(vm_clock);
1337 } else {
1338 /* To avoid problems with overflow limit this to 2^32. */
1339 delta = INT32_MAX;
1342 if (delta < 0)
1343 delta = 0;
1345 return delta;
1348 #if defined(__linux__) || defined(_WIN32)
1349 static uint64_t qemu_next_deadline_dyntick(void)
1351 int64_t delta;
1352 int64_t rtdelta;
1354 if (use_icount)
1355 delta = INT32_MAX;
1356 else
1357 delta = (qemu_next_deadline() + 999) / 1000;
1359 if (active_timers[QEMU_TIMER_REALTIME]) {
1360 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1361 qemu_get_clock(rt_clock))*1000;
1362 if (rtdelta < delta)
1363 delta = rtdelta;
1366 if (delta < MIN_TIMER_REARM_US)
1367 delta = MIN_TIMER_REARM_US;
1369 return delta;
1371 #endif
1373 #ifndef _WIN32
1375 #if defined(__linux__)
1377 #define RTC_FREQ 1024
1379 static void enable_sigio_timer(int fd)
1381 struct sigaction act;
1383 /* timer signal */
1384 sigfillset(&act.sa_mask);
1385 act.sa_flags = 0;
1386 act.sa_handler = host_alarm_handler;
1388 sigaction(SIGIO, &act, NULL);
1389 fcntl(fd, F_SETFL, O_ASYNC);
1390 fcntl(fd, F_SETOWN, getpid());
1393 static int hpet_start_timer(struct qemu_alarm_timer *t)
1395 struct hpet_info info;
1396 int r, fd;
1398 fd = open("/dev/hpet", O_RDONLY);
1399 if (fd < 0)
1400 return -1;
1402 /* Set frequency */
1403 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1404 if (r < 0) {
1405 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1406 "error, but for better emulation accuracy type:\n"
1407 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1408 goto fail;
1411 /* Check capabilities */
1412 r = ioctl(fd, HPET_INFO, &info);
1413 if (r < 0)
1414 goto fail;
1416 /* Enable periodic mode */
1417 r = ioctl(fd, HPET_EPI, 0);
1418 if (info.hi_flags && (r < 0))
1419 goto fail;
1421 /* Enable interrupt */
1422 r = ioctl(fd, HPET_IE_ON, 0);
1423 if (r < 0)
1424 goto fail;
1426 enable_sigio_timer(fd);
1427 t->priv = (void *)(long)fd;
1429 return 0;
1430 fail:
1431 close(fd);
1432 return -1;
1435 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1437 int fd = (long)t->priv;
1439 close(fd);
1442 static int rtc_start_timer(struct qemu_alarm_timer *t)
1444 int rtc_fd;
1445 unsigned long current_rtc_freq = 0;
1447 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1448 if (rtc_fd < 0)
1449 return -1;
1450 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1451 if (current_rtc_freq != RTC_FREQ &&
1452 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1453 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1454 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1455 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1456 goto fail;
1458 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1459 fail:
1460 close(rtc_fd);
1461 return -1;
1464 enable_sigio_timer(rtc_fd);
1466 t->priv = (void *)(long)rtc_fd;
1468 return 0;
1471 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1473 int rtc_fd = (long)t->priv;
1475 close(rtc_fd);
1478 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1480 struct sigevent ev;
1481 timer_t host_timer;
1482 struct sigaction act;
1484 sigfillset(&act.sa_mask);
1485 act.sa_flags = 0;
1486 act.sa_handler = host_alarm_handler;
1488 sigaction(SIGALRM, &act, NULL);
1490 ev.sigev_value.sival_int = 0;
1491 ev.sigev_notify = SIGEV_SIGNAL;
1492 ev.sigev_signo = SIGALRM;
1494 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1495 perror("timer_create");
1497 /* disable dynticks */
1498 fprintf(stderr, "Dynamic Ticks disabled\n");
1500 return -1;
1503 t->priv = (void *)host_timer;
1505 return 0;
1508 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1510 timer_t host_timer = (timer_t)t->priv;
1512 timer_delete(host_timer);
1515 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1517 timer_t host_timer = (timer_t)t->priv;
1518 struct itimerspec timeout;
1519 int64_t nearest_delta_us = INT64_MAX;
1520 int64_t current_us;
1522 if (!active_timers[QEMU_TIMER_REALTIME] &&
1523 !active_timers[QEMU_TIMER_VIRTUAL])
1524 return;
1526 nearest_delta_us = qemu_next_deadline_dyntick();
1528 /* check whether a timer is already running */
1529 if (timer_gettime(host_timer, &timeout)) {
1530 perror("gettime");
1531 fprintf(stderr, "Internal timer error: aborting\n");
1532 exit(1);
1534 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1535 if (current_us && current_us <= nearest_delta_us)
1536 return;
1538 timeout.it_interval.tv_sec = 0;
1539 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1540 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1541 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1542 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1543 perror("settime");
1544 fprintf(stderr, "Internal timer error: aborting\n");
1545 exit(1);
1549 #endif /* defined(__linux__) */
1551 static int unix_start_timer(struct qemu_alarm_timer *t)
1553 struct sigaction act;
1554 struct itimerval itv;
1555 int err;
1557 /* timer signal */
1558 sigfillset(&act.sa_mask);
1559 act.sa_flags = 0;
1560 act.sa_handler = host_alarm_handler;
1562 sigaction(SIGALRM, &act, NULL);
1564 itv.it_interval.tv_sec = 0;
1565 /* for i386 kernel 2.6 to get 1 ms */
1566 itv.it_interval.tv_usec = 999;
1567 itv.it_value.tv_sec = 0;
1568 itv.it_value.tv_usec = 10 * 1000;
1570 err = setitimer(ITIMER_REAL, &itv, NULL);
1571 if (err)
1572 return -1;
1574 return 0;
1577 static void unix_stop_timer(struct qemu_alarm_timer *t)
1579 struct itimerval itv;
1581 memset(&itv, 0, sizeof(itv));
1582 setitimer(ITIMER_REAL, &itv, NULL);
1585 #endif /* !defined(_WIN32) */
1587 #ifdef _WIN32
1589 static int win32_start_timer(struct qemu_alarm_timer *t)
1591 TIMECAPS tc;
1592 struct qemu_alarm_win32 *data = t->priv;
1593 UINT flags;
1595 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1596 if (!data->host_alarm) {
1597 perror("Failed CreateEvent");
1598 return -1;
1601 memset(&tc, 0, sizeof(tc));
1602 timeGetDevCaps(&tc, sizeof(tc));
1604 if (data->period < tc.wPeriodMin)
1605 data->period = tc.wPeriodMin;
1607 timeBeginPeriod(data->period);
1609 flags = TIME_CALLBACK_FUNCTION;
1610 if (alarm_has_dynticks(t))
1611 flags |= TIME_ONESHOT;
1612 else
1613 flags |= TIME_PERIODIC;
1615 data->timerId = timeSetEvent(1, // interval (ms)
1616 data->period, // resolution
1617 host_alarm_handler, // function
1618 (DWORD)t, // parameter
1619 flags);
1621 if (!data->timerId) {
1622 perror("Failed to initialize win32 alarm timer");
1624 timeEndPeriod(data->period);
1625 CloseHandle(data->host_alarm);
1626 return -1;
1629 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1631 return 0;
1634 static void win32_stop_timer(struct qemu_alarm_timer *t)
1636 struct qemu_alarm_win32 *data = t->priv;
1638 timeKillEvent(data->timerId);
1639 timeEndPeriod(data->period);
1641 CloseHandle(data->host_alarm);
1644 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1646 struct qemu_alarm_win32 *data = t->priv;
1647 uint64_t nearest_delta_us;
1649 if (!active_timers[QEMU_TIMER_REALTIME] &&
1650 !active_timers[QEMU_TIMER_VIRTUAL])
1651 return;
1653 nearest_delta_us = qemu_next_deadline_dyntick();
1654 nearest_delta_us /= 1000;
1656 timeKillEvent(data->timerId);
1658 data->timerId = timeSetEvent(1,
1659 data->period,
1660 host_alarm_handler,
1661 (DWORD)t,
1662 TIME_ONESHOT | TIME_PERIODIC);
1664 if (!data->timerId) {
1665 perror("Failed to re-arm win32 alarm timer");
1667 timeEndPeriod(data->period);
1668 CloseHandle(data->host_alarm);
1669 exit(1);
1673 #endif /* _WIN32 */
1675 static void init_timer_alarm(void)
1677 struct qemu_alarm_timer *t = NULL;
1678 int i, err = -1;
1680 for (i = 0; alarm_timers[i].name; i++) {
1681 t = &alarm_timers[i];
1683 err = t->start(t);
1684 if (!err)
1685 break;
1688 if (err) {
1689 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1690 fprintf(stderr, "Terminating\n");
1691 exit(1);
1694 alarm_timer = t;
1697 static void quit_timers(void)
1699 alarm_timer->stop(alarm_timer);
1700 alarm_timer = NULL;
1703 /***********************************************************/
1704 /* host time/date access */
1705 void qemu_get_timedate(struct tm *tm, int offset)
1707 time_t ti;
1708 struct tm *ret;
1710 time(&ti);
1711 ti += offset;
1712 if (rtc_date_offset == -1) {
1713 if (rtc_utc)
1714 ret = gmtime(&ti);
1715 else
1716 ret = localtime(&ti);
1717 } else {
1718 ti -= rtc_date_offset;
1719 ret = gmtime(&ti);
1722 memcpy(tm, ret, sizeof(struct tm));
1725 int qemu_timedate_diff(struct tm *tm)
1727 time_t seconds;
1729 if (rtc_date_offset == -1)
1730 if (rtc_utc)
1731 seconds = mktimegm(tm);
1732 else
1733 seconds = mktime(tm);
1734 else
1735 seconds = mktimegm(tm) + rtc_date_offset;
1737 return seconds - time(NULL);
1740 /***********************************************************/
1741 /* character device */
1743 static void qemu_chr_event(CharDriverState *s, int event)
1745 if (!s->chr_event)
1746 return;
1747 s->chr_event(s->handler_opaque, event);
1750 static void qemu_chr_reset_bh(void *opaque)
1752 CharDriverState *s = opaque;
1753 qemu_chr_event(s, CHR_EVENT_RESET);
1754 qemu_bh_delete(s->bh);
1755 s->bh = NULL;
1758 void qemu_chr_reset(CharDriverState *s)
1760 if (s->bh == NULL) {
1761 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1762 qemu_bh_schedule(s->bh);
1766 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1768 return s->chr_write(s, buf, len);
1771 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1773 if (!s->chr_ioctl)
1774 return -ENOTSUP;
1775 return s->chr_ioctl(s, cmd, arg);
1778 int qemu_chr_can_read(CharDriverState *s)
1780 if (!s->chr_can_read)
1781 return 0;
1782 return s->chr_can_read(s->handler_opaque);
1785 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1787 s->chr_read(s->handler_opaque, buf, len);
1790 void qemu_chr_accept_input(CharDriverState *s)
1792 if (s->chr_accept_input)
1793 s->chr_accept_input(s);
1796 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1798 char buf[4096];
1799 va_list ap;
1800 va_start(ap, fmt);
1801 vsnprintf(buf, sizeof(buf), fmt, ap);
1802 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1803 va_end(ap);
1806 void qemu_chr_send_event(CharDriverState *s, int event)
1808 if (s->chr_send_event)
1809 s->chr_send_event(s, event);
1812 void qemu_chr_add_handlers(CharDriverState *s,
1813 IOCanRWHandler *fd_can_read,
1814 IOReadHandler *fd_read,
1815 IOEventHandler *fd_event,
1816 void *opaque)
1818 s->chr_can_read = fd_can_read;
1819 s->chr_read = fd_read;
1820 s->chr_event = fd_event;
1821 s->handler_opaque = opaque;
1822 if (s->chr_update_read_handler)
1823 s->chr_update_read_handler(s);
1826 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1828 return len;
1831 static CharDriverState *qemu_chr_open_null(void)
1833 CharDriverState *chr;
1835 chr = qemu_mallocz(sizeof(CharDriverState));
1836 if (!chr)
1837 return NULL;
1838 chr->chr_write = null_chr_write;
1839 return chr;
1842 /* MUX driver for serial I/O splitting */
1843 static int term_timestamps;
1844 static int64_t term_timestamps_start;
1845 #define MAX_MUX 4
1846 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1847 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1848 typedef struct {
1849 IOCanRWHandler *chr_can_read[MAX_MUX];
1850 IOReadHandler *chr_read[MAX_MUX];
1851 IOEventHandler *chr_event[MAX_MUX];
1852 void *ext_opaque[MAX_MUX];
1853 CharDriverState *drv;
1854 unsigned char buffer[MUX_BUFFER_SIZE];
1855 int prod;
1856 int cons;
1857 int mux_cnt;
1858 int term_got_escape;
1859 int max_size;
1860 } MuxDriver;
1863 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1865 MuxDriver *d = chr->opaque;
1866 int ret;
1867 if (!term_timestamps) {
1868 ret = d->drv->chr_write(d->drv, buf, len);
1869 } else {
1870 int i;
1872 ret = 0;
1873 for(i = 0; i < len; i++) {
1874 ret += d->drv->chr_write(d->drv, buf+i, 1);
1875 if (buf[i] == '\n') {
1876 char buf1[64];
1877 int64_t ti;
1878 int secs;
1880 ti = get_clock();
1881 if (term_timestamps_start == -1)
1882 term_timestamps_start = ti;
1883 ti -= term_timestamps_start;
1884 secs = ti / 1000000000;
1885 snprintf(buf1, sizeof(buf1),
1886 "[%02d:%02d:%02d.%03d] ",
1887 secs / 3600,
1888 (secs / 60) % 60,
1889 secs % 60,
1890 (int)((ti / 1000000) % 1000));
1891 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1895 return ret;
1898 static const char * const mux_help[] = {
1899 "% h print this help\n\r",
1900 "% x exit emulator\n\r",
1901 "% s save disk data back to file (if -snapshot)\n\r",
1902 "% t toggle console timestamps\n\r"
1903 "% b send break (magic sysrq)\n\r",
1904 "% c switch between console and monitor\n\r",
1905 "% % sends %\n\r",
1906 NULL
1909 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1910 static void mux_print_help(CharDriverState *chr)
1912 int i, j;
1913 char ebuf[15] = "Escape-Char";
1914 char cbuf[50] = "\n\r";
1916 if (term_escape_char > 0 && term_escape_char < 26) {
1917 snprintf(cbuf, sizeof(cbuf), "\n\r");
1918 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1919 } else {
1920 snprintf(cbuf, sizeof(cbuf),
1921 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1922 term_escape_char);
1924 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1925 for (i = 0; mux_help[i] != NULL; i++) {
1926 for (j=0; mux_help[i][j] != '\0'; j++) {
1927 if (mux_help[i][j] == '%')
1928 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1929 else
1930 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1935 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1937 if (d->term_got_escape) {
1938 d->term_got_escape = 0;
1939 if (ch == term_escape_char)
1940 goto send_char;
1941 switch(ch) {
1942 case '?':
1943 case 'h':
1944 mux_print_help(chr);
1945 break;
1946 case 'x':
1948 const char *term = "QEMU: Terminated\n\r";
1949 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1950 exit(0);
1951 break;
1953 case 's':
1955 int i;
1956 for (i = 0; i < nb_drives; i++) {
1957 bdrv_commit(drives_table[i].bdrv);
1960 break;
1961 case 'b':
1962 qemu_chr_event(chr, CHR_EVENT_BREAK);
1963 break;
1964 case 'c':
1965 /* Switch to the next registered device */
1966 chr->focus++;
1967 if (chr->focus >= d->mux_cnt)
1968 chr->focus = 0;
1969 break;
1970 case 't':
1971 term_timestamps = !term_timestamps;
1972 term_timestamps_start = -1;
1973 break;
1975 } else if (ch == term_escape_char) {
1976 d->term_got_escape = 1;
1977 } else {
1978 send_char:
1979 return 1;
1981 return 0;
1984 static void mux_chr_accept_input(CharDriverState *chr)
1986 int m = chr->focus;
1987 MuxDriver *d = chr->opaque;
1989 while (d->prod != d->cons &&
1990 d->chr_can_read[m] &&
1991 d->chr_can_read[m](d->ext_opaque[m])) {
1992 d->chr_read[m](d->ext_opaque[m],
1993 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1997 static int mux_chr_can_read(void *opaque)
1999 CharDriverState *chr = opaque;
2000 MuxDriver *d = chr->opaque;
2002 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2003 return 1;
2004 if (d->chr_can_read[chr->focus])
2005 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2006 return 0;
2009 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2011 CharDriverState *chr = opaque;
2012 MuxDriver *d = chr->opaque;
2013 int m = chr->focus;
2014 int i;
2016 mux_chr_accept_input (opaque);
2018 for(i = 0; i < size; i++)
2019 if (mux_proc_byte(chr, d, buf[i])) {
2020 if (d->prod == d->cons &&
2021 d->chr_can_read[m] &&
2022 d->chr_can_read[m](d->ext_opaque[m]))
2023 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2024 else
2025 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2029 static void mux_chr_event(void *opaque, int event)
2031 CharDriverState *chr = opaque;
2032 MuxDriver *d = chr->opaque;
2033 int i;
2035 /* Send the event to all registered listeners */
2036 for (i = 0; i < d->mux_cnt; i++)
2037 if (d->chr_event[i])
2038 d->chr_event[i](d->ext_opaque[i], event);
2041 static void mux_chr_update_read_handler(CharDriverState *chr)
2043 MuxDriver *d = chr->opaque;
2045 if (d->mux_cnt >= MAX_MUX) {
2046 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2047 return;
2049 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2050 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2051 d->chr_read[d->mux_cnt] = chr->chr_read;
2052 d->chr_event[d->mux_cnt] = chr->chr_event;
2053 /* Fix up the real driver with mux routines */
2054 if (d->mux_cnt == 0) {
2055 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2056 mux_chr_event, chr);
2058 chr->focus = d->mux_cnt;
2059 d->mux_cnt++;
2062 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2064 CharDriverState *chr;
2065 MuxDriver *d;
2067 chr = qemu_mallocz(sizeof(CharDriverState));
2068 if (!chr)
2069 return NULL;
2070 d = qemu_mallocz(sizeof(MuxDriver));
2071 if (!d) {
2072 free(chr);
2073 return NULL;
2076 chr->opaque = d;
2077 d->drv = drv;
2078 chr->focus = -1;
2079 chr->chr_write = mux_chr_write;
2080 chr->chr_update_read_handler = mux_chr_update_read_handler;
2081 chr->chr_accept_input = mux_chr_accept_input;
2082 return chr;
2086 #ifdef _WIN32
2088 static void socket_cleanup(void)
2090 WSACleanup();
2093 static int socket_init(void)
2095 WSADATA Data;
2096 int ret, err;
2098 ret = WSAStartup(MAKEWORD(2,2), &Data);
2099 if (ret != 0) {
2100 err = WSAGetLastError();
2101 fprintf(stderr, "WSAStartup: %d\n", err);
2102 return -1;
2104 atexit(socket_cleanup);
2105 return 0;
2108 static int send_all(int fd, const uint8_t *buf, int len1)
2110 int ret, len;
2112 len = len1;
2113 while (len > 0) {
2114 ret = send(fd, buf, len, 0);
2115 if (ret < 0) {
2116 int errno;
2117 errno = WSAGetLastError();
2118 if (errno != WSAEWOULDBLOCK) {
2119 return -1;
2121 } else if (ret == 0) {
2122 break;
2123 } else {
2124 buf += ret;
2125 len -= ret;
2128 return len1 - len;
2131 #else
2133 static int unix_write(int fd, const uint8_t *buf, int len1)
2135 int ret, len;
2137 len = len1;
2138 while (len > 0) {
2139 ret = write(fd, buf, len);
2140 if (ret < 0) {
2141 if (errno != EINTR && errno != EAGAIN)
2142 return -1;
2143 } else if (ret == 0) {
2144 break;
2145 } else {
2146 buf += ret;
2147 len -= ret;
2150 return len1 - len;
2153 static inline int send_all(int fd, const uint8_t *buf, int len1)
2155 return unix_write(fd, buf, len1);
2157 #endif /* !_WIN32 */
2159 #ifndef _WIN32
2161 typedef struct {
2162 int fd_in, fd_out;
2163 int max_size;
2164 } FDCharDriver;
2166 #define STDIO_MAX_CLIENTS 1
2167 static int stdio_nb_clients = 0;
2169 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2171 FDCharDriver *s = chr->opaque;
2172 return unix_write(s->fd_out, buf, len);
2175 static int fd_chr_read_poll(void *opaque)
2177 CharDriverState *chr = opaque;
2178 FDCharDriver *s = chr->opaque;
2180 s->max_size = qemu_chr_can_read(chr);
2181 return s->max_size;
2184 static void fd_chr_read(void *opaque)
2186 CharDriverState *chr = opaque;
2187 FDCharDriver *s = chr->opaque;
2188 int size, len;
2189 uint8_t buf[1024];
2191 len = sizeof(buf);
2192 if (len > s->max_size)
2193 len = s->max_size;
2194 if (len == 0)
2195 return;
2196 size = read(s->fd_in, buf, len);
2197 if (size == 0) {
2198 /* FD has been closed. Remove it from the active list. */
2199 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2200 return;
2202 if (size > 0) {
2203 qemu_chr_read(chr, buf, size);
2207 static void fd_chr_update_read_handler(CharDriverState *chr)
2209 FDCharDriver *s = chr->opaque;
2211 if (s->fd_in >= 0) {
2212 if (nographic && s->fd_in == 0) {
2213 } else {
2214 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2215 fd_chr_read, NULL, chr);
2220 static void fd_chr_close(struct CharDriverState *chr)
2222 FDCharDriver *s = chr->opaque;
2224 if (s->fd_in >= 0) {
2225 if (nographic && s->fd_in == 0) {
2226 } else {
2227 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2231 qemu_free(s);
2234 /* open a character device to a unix fd */
2235 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2237 CharDriverState *chr;
2238 FDCharDriver *s;
2240 chr = qemu_mallocz(sizeof(CharDriverState));
2241 if (!chr)
2242 return NULL;
2243 s = qemu_mallocz(sizeof(FDCharDriver));
2244 if (!s) {
2245 free(chr);
2246 return NULL;
2248 s->fd_in = fd_in;
2249 s->fd_out = fd_out;
2250 chr->opaque = s;
2251 chr->chr_write = fd_chr_write;
2252 chr->chr_update_read_handler = fd_chr_update_read_handler;
2253 chr->chr_close = fd_chr_close;
2255 qemu_chr_reset(chr);
2257 return chr;
2260 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2262 int fd_out;
2264 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2265 if (fd_out < 0)
2266 return NULL;
2267 return qemu_chr_open_fd(-1, fd_out);
2270 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2272 int fd_in, fd_out;
2273 char filename_in[256], filename_out[256];
2275 snprintf(filename_in, 256, "%s.in", filename);
2276 snprintf(filename_out, 256, "%s.out", filename);
2277 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2278 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2279 if (fd_in < 0 || fd_out < 0) {
2280 if (fd_in >= 0)
2281 close(fd_in);
2282 if (fd_out >= 0)
2283 close(fd_out);
2284 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2285 if (fd_in < 0)
2286 return NULL;
2288 return qemu_chr_open_fd(fd_in, fd_out);
2292 /* for STDIO, we handle the case where several clients use it
2293 (nographic mode) */
2295 #define TERM_FIFO_MAX_SIZE 1
2297 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2298 static int term_fifo_size;
2300 static int stdio_read_poll(void *opaque)
2302 CharDriverState *chr = opaque;
2304 /* try to flush the queue if needed */
2305 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2306 qemu_chr_read(chr, term_fifo, 1);
2307 term_fifo_size = 0;
2309 /* see if we can absorb more chars */
2310 if (term_fifo_size == 0)
2311 return 1;
2312 else
2313 return 0;
2316 static void stdio_read(void *opaque)
2318 int size;
2319 uint8_t buf[1];
2320 CharDriverState *chr = opaque;
2322 size = read(0, buf, 1);
2323 if (size == 0) {
2324 /* stdin has been closed. Remove it from the active list. */
2325 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2326 return;
2328 if (size > 0) {
2329 if (qemu_chr_can_read(chr) > 0) {
2330 qemu_chr_read(chr, buf, 1);
2331 } else if (term_fifo_size == 0) {
2332 term_fifo[term_fifo_size++] = buf[0];
2337 /* init terminal so that we can grab keys */
2338 static struct termios oldtty;
2339 static int old_fd0_flags;
2340 static int term_atexit_done;
2342 static void term_exit(void)
2344 tcsetattr (0, TCSANOW, &oldtty);
2345 fcntl(0, F_SETFL, old_fd0_flags);
2348 static void term_init(void)
2350 struct termios tty;
2352 tcgetattr (0, &tty);
2353 oldtty = tty;
2354 old_fd0_flags = fcntl(0, F_GETFL);
2356 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2357 |INLCR|IGNCR|ICRNL|IXON);
2358 tty.c_oflag |= OPOST;
2359 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2360 /* if graphical mode, we allow Ctrl-C handling */
2361 if (nographic)
2362 tty.c_lflag &= ~ISIG;
2363 tty.c_cflag &= ~(CSIZE|PARENB);
2364 tty.c_cflag |= CS8;
2365 tty.c_cc[VMIN] = 1;
2366 tty.c_cc[VTIME] = 0;
2368 tcsetattr (0, TCSANOW, &tty);
2370 if (!term_atexit_done++)
2371 atexit(term_exit);
2373 fcntl(0, F_SETFL, O_NONBLOCK);
2376 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2378 term_exit();
2379 stdio_nb_clients--;
2380 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2381 fd_chr_close(chr);
2384 static CharDriverState *qemu_chr_open_stdio(void)
2386 CharDriverState *chr;
2388 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2389 return NULL;
2390 chr = qemu_chr_open_fd(0, 1);
2391 chr->chr_close = qemu_chr_close_stdio;
2392 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2393 stdio_nb_clients++;
2394 term_init();
2396 return chr;
2399 #ifdef __sun__
2400 /* Once Solaris has openpty(), this is going to be removed. */
2401 int openpty(int *amaster, int *aslave, char *name,
2402 struct termios *termp, struct winsize *winp)
2404 const char *slave;
2405 int mfd = -1, sfd = -1;
2407 *amaster = *aslave = -1;
2409 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2410 if (mfd < 0)
2411 goto err;
2413 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2414 goto err;
2416 if ((slave = ptsname(mfd)) == NULL)
2417 goto err;
2419 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2420 goto err;
2422 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2423 (termp != NULL && tcgetattr(sfd, termp) < 0))
2424 goto err;
2426 if (amaster)
2427 *amaster = mfd;
2428 if (aslave)
2429 *aslave = sfd;
2430 if (winp)
2431 ioctl(sfd, TIOCSWINSZ, winp);
2433 return 0;
2435 err:
2436 if (sfd != -1)
2437 close(sfd);
2438 close(mfd);
2439 return -1;
2442 void cfmakeraw (struct termios *termios_p)
2444 termios_p->c_iflag &=
2445 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2446 termios_p->c_oflag &= ~OPOST;
2447 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2448 termios_p->c_cflag &= ~(CSIZE|PARENB);
2449 termios_p->c_cflag |= CS8;
2451 termios_p->c_cc[VMIN] = 0;
2452 termios_p->c_cc[VTIME] = 0;
2454 #endif
2456 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2457 || defined(__NetBSD__) || defined(__OpenBSD__)
2459 typedef struct {
2460 int fd;
2461 int connected;
2462 int polling;
2463 int read_bytes;
2464 QEMUTimer *timer;
2465 } PtyCharDriver;
2467 static void pty_chr_update_read_handler(CharDriverState *chr);
2468 static void pty_chr_state(CharDriverState *chr, int connected);
2470 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2472 PtyCharDriver *s = chr->opaque;
2474 if (!s->connected) {
2475 /* guest sends data, check for (re-)connect */
2476 pty_chr_update_read_handler(chr);
2477 return 0;
2479 return unix_write(s->fd, buf, len);
2482 static int pty_chr_read_poll(void *opaque)
2484 CharDriverState *chr = opaque;
2485 PtyCharDriver *s = chr->opaque;
2487 s->read_bytes = qemu_chr_can_read(chr);
2488 return s->read_bytes;
2491 static void pty_chr_read(void *opaque)
2493 CharDriverState *chr = opaque;
2494 PtyCharDriver *s = chr->opaque;
2495 int size, len;
2496 uint8_t buf[1024];
2498 len = sizeof(buf);
2499 if (len > s->read_bytes)
2500 len = s->read_bytes;
2501 if (len == 0)
2502 return;
2503 size = read(s->fd, buf, len);
2504 if ((size == -1 && errno == EIO) ||
2505 (size == 0)) {
2506 pty_chr_state(chr, 0);
2507 return;
2509 if (size > 0) {
2510 pty_chr_state(chr, 1);
2511 qemu_chr_read(chr, buf, size);
2515 static void pty_chr_update_read_handler(CharDriverState *chr)
2517 PtyCharDriver *s = chr->opaque;
2519 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2520 pty_chr_read, NULL, chr);
2521 s->polling = 1;
2523 * Short timeout here: just need wait long enougth that qemu makes
2524 * it through the poll loop once. When reconnected we want a
2525 * short timeout so we notice it almost instantly. Otherwise
2526 * read() gives us -EIO instantly, making pty_chr_state() reset the
2527 * timeout to the normal (much longer) poll interval before the
2528 * timer triggers.
2530 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2533 static void pty_chr_state(CharDriverState *chr, int connected)
2535 PtyCharDriver *s = chr->opaque;
2537 if (!connected) {
2538 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2539 s->connected = 0;
2540 s->polling = 0;
2541 /* (re-)connect poll interval for idle guests: once per second.
2542 * We check more frequently in case the guests sends data to
2543 * the virtual device linked to our pty. */
2544 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2545 } else {
2546 if (!s->connected)
2547 qemu_chr_reset(chr);
2548 s->connected = 1;
2552 static void pty_chr_timer(void *opaque)
2554 struct CharDriverState *chr = opaque;
2555 PtyCharDriver *s = chr->opaque;
2557 if (s->connected)
2558 return;
2559 if (s->polling) {
2560 /* If we arrive here without polling being cleared due
2561 * read returning -EIO, then we are (re-)connected */
2562 pty_chr_state(chr, 1);
2563 return;
2566 /* Next poll ... */
2567 pty_chr_update_read_handler(chr);
2570 static void pty_chr_close(struct CharDriverState *chr)
2572 PtyCharDriver *s = chr->opaque;
2574 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2575 close(s->fd);
2576 qemu_free(s);
2579 static CharDriverState *qemu_chr_open_pty(void)
2581 CharDriverState *chr;
2582 PtyCharDriver *s;
2583 struct termios tty;
2584 int slave_fd;
2585 #if defined(__OpenBSD__)
2586 char pty_name[PATH_MAX];
2587 #define q_ptsname(x) pty_name
2588 #else
2589 char *pty_name = NULL;
2590 #define q_ptsname(x) ptsname(x)
2591 #endif
2593 chr = qemu_mallocz(sizeof(CharDriverState));
2594 if (!chr)
2595 return NULL;
2596 s = qemu_mallocz(sizeof(PtyCharDriver));
2597 if (!s) {
2598 qemu_free(chr);
2599 return NULL;
2602 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2603 return NULL;
2606 /* Set raw attributes on the pty. */
2607 cfmakeraw(&tty);
2608 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2609 close(slave_fd);
2611 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2613 chr->opaque = s;
2614 chr->chr_write = pty_chr_write;
2615 chr->chr_update_read_handler = pty_chr_update_read_handler;
2616 chr->chr_close = pty_chr_close;
2618 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2620 return chr;
2623 static void tty_serial_init(int fd, int speed,
2624 int parity, int data_bits, int stop_bits)
2626 struct termios tty;
2627 speed_t spd;
2629 #if 0
2630 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2631 speed, parity, data_bits, stop_bits);
2632 #endif
2633 tcgetattr (fd, &tty);
2635 #define MARGIN 1.1
2636 if (speed <= 50 * MARGIN)
2637 spd = B50;
2638 else if (speed <= 75 * MARGIN)
2639 spd = B75;
2640 else if (speed <= 300 * MARGIN)
2641 spd = B300;
2642 else if (speed <= 600 * MARGIN)
2643 spd = B600;
2644 else if (speed <= 1200 * MARGIN)
2645 spd = B1200;
2646 else if (speed <= 2400 * MARGIN)
2647 spd = B2400;
2648 else if (speed <= 4800 * MARGIN)
2649 spd = B4800;
2650 else if (speed <= 9600 * MARGIN)
2651 spd = B9600;
2652 else if (speed <= 19200 * MARGIN)
2653 spd = B19200;
2654 else if (speed <= 38400 * MARGIN)
2655 spd = B38400;
2656 else if (speed <= 57600 * MARGIN)
2657 spd = B57600;
2658 else if (speed <= 115200 * MARGIN)
2659 spd = B115200;
2660 else
2661 spd = B115200;
2663 cfsetispeed(&tty, spd);
2664 cfsetospeed(&tty, spd);
2666 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2667 |INLCR|IGNCR|ICRNL|IXON);
2668 tty.c_oflag |= OPOST;
2669 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2670 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2671 switch(data_bits) {
2672 default:
2673 case 8:
2674 tty.c_cflag |= CS8;
2675 break;
2676 case 7:
2677 tty.c_cflag |= CS7;
2678 break;
2679 case 6:
2680 tty.c_cflag |= CS6;
2681 break;
2682 case 5:
2683 tty.c_cflag |= CS5;
2684 break;
2686 switch(parity) {
2687 default:
2688 case 'N':
2689 break;
2690 case 'E':
2691 tty.c_cflag |= PARENB;
2692 break;
2693 case 'O':
2694 tty.c_cflag |= PARENB | PARODD;
2695 break;
2697 if (stop_bits == 2)
2698 tty.c_cflag |= CSTOPB;
2700 tcsetattr (fd, TCSANOW, &tty);
2703 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2705 FDCharDriver *s = chr->opaque;
2707 switch(cmd) {
2708 case CHR_IOCTL_SERIAL_SET_PARAMS:
2710 QEMUSerialSetParams *ssp = arg;
2711 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2712 ssp->data_bits, ssp->stop_bits);
2714 break;
2715 case CHR_IOCTL_SERIAL_SET_BREAK:
2717 int enable = *(int *)arg;
2718 if (enable)
2719 tcsendbreak(s->fd_in, 1);
2721 break;
2722 case CHR_IOCTL_SERIAL_GET_TIOCM:
2724 int sarg = 0;
2725 int *targ = (int *)arg;
2726 ioctl(s->fd_in, TIOCMGET, &sarg);
2727 *targ = 0;
2728 if (sarg | TIOCM_CTS)
2729 *targ |= CHR_TIOCM_CTS;
2730 if (sarg | TIOCM_CAR)
2731 *targ |= CHR_TIOCM_CAR;
2732 if (sarg | TIOCM_DSR)
2733 *targ |= CHR_TIOCM_DSR;
2734 if (sarg | TIOCM_RI)
2735 *targ |= CHR_TIOCM_RI;
2736 if (sarg | TIOCM_DTR)
2737 *targ |= CHR_TIOCM_DTR;
2738 if (sarg | TIOCM_RTS)
2739 *targ |= CHR_TIOCM_RTS;
2741 break;
2742 case CHR_IOCTL_SERIAL_SET_TIOCM:
2744 int sarg = *(int *)arg;
2745 int targ = 0;
2746 if (sarg | CHR_TIOCM_DTR)
2747 targ |= TIOCM_DTR;
2748 if (sarg | CHR_TIOCM_RTS)
2749 targ |= TIOCM_RTS;
2750 ioctl(s->fd_in, TIOCMSET, &targ);
2752 break;
2753 default:
2754 return -ENOTSUP;
2756 return 0;
2759 static CharDriverState *qemu_chr_open_tty(const char *filename)
2761 CharDriverState *chr;
2762 int fd;
2764 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2765 tty_serial_init(fd, 115200, 'N', 8, 1);
2766 chr = qemu_chr_open_fd(fd, fd);
2767 if (!chr) {
2768 close(fd);
2769 return NULL;
2771 chr->chr_ioctl = tty_serial_ioctl;
2772 qemu_chr_reset(chr);
2773 return chr;
2775 #else /* ! __linux__ && ! __sun__ */
2776 static CharDriverState *qemu_chr_open_pty(void)
2778 return NULL;
2780 #endif /* __linux__ || __sun__ */
2782 #if defined(__linux__)
2783 typedef struct {
2784 int fd;
2785 int mode;
2786 } ParallelCharDriver;
2788 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2790 if (s->mode != mode) {
2791 int m = mode;
2792 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2793 return 0;
2794 s->mode = mode;
2796 return 1;
2799 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2801 ParallelCharDriver *drv = chr->opaque;
2802 int fd = drv->fd;
2803 uint8_t b;
2805 switch(cmd) {
2806 case CHR_IOCTL_PP_READ_DATA:
2807 if (ioctl(fd, PPRDATA, &b) < 0)
2808 return -ENOTSUP;
2809 *(uint8_t *)arg = b;
2810 break;
2811 case CHR_IOCTL_PP_WRITE_DATA:
2812 b = *(uint8_t *)arg;
2813 if (ioctl(fd, PPWDATA, &b) < 0)
2814 return -ENOTSUP;
2815 break;
2816 case CHR_IOCTL_PP_READ_CONTROL:
2817 if (ioctl(fd, PPRCONTROL, &b) < 0)
2818 return -ENOTSUP;
2819 /* Linux gives only the lowest bits, and no way to know data
2820 direction! For better compatibility set the fixed upper
2821 bits. */
2822 *(uint8_t *)arg = b | 0xc0;
2823 break;
2824 case CHR_IOCTL_PP_WRITE_CONTROL:
2825 b = *(uint8_t *)arg;
2826 if (ioctl(fd, PPWCONTROL, &b) < 0)
2827 return -ENOTSUP;
2828 break;
2829 case CHR_IOCTL_PP_READ_STATUS:
2830 if (ioctl(fd, PPRSTATUS, &b) < 0)
2831 return -ENOTSUP;
2832 *(uint8_t *)arg = b;
2833 break;
2834 case CHR_IOCTL_PP_DATA_DIR:
2835 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2836 return -ENOTSUP;
2837 break;
2838 case CHR_IOCTL_PP_EPP_READ_ADDR:
2839 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2840 struct ParallelIOArg *parg = arg;
2841 int n = read(fd, parg->buffer, parg->count);
2842 if (n != parg->count) {
2843 return -EIO;
2846 break;
2847 case CHR_IOCTL_PP_EPP_READ:
2848 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2849 struct ParallelIOArg *parg = arg;
2850 int n = read(fd, parg->buffer, parg->count);
2851 if (n != parg->count) {
2852 return -EIO;
2855 break;
2856 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2857 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2858 struct ParallelIOArg *parg = arg;
2859 int n = write(fd, parg->buffer, parg->count);
2860 if (n != parg->count) {
2861 return -EIO;
2864 break;
2865 case CHR_IOCTL_PP_EPP_WRITE:
2866 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2867 struct ParallelIOArg *parg = arg;
2868 int n = write(fd, parg->buffer, parg->count);
2869 if (n != parg->count) {
2870 return -EIO;
2873 break;
2874 default:
2875 return -ENOTSUP;
2877 return 0;
2880 static void pp_close(CharDriverState *chr)
2882 ParallelCharDriver *drv = chr->opaque;
2883 int fd = drv->fd;
2885 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2886 ioctl(fd, PPRELEASE);
2887 close(fd);
2888 qemu_free(drv);
2891 static CharDriverState *qemu_chr_open_pp(const char *filename)
2893 CharDriverState *chr;
2894 ParallelCharDriver *drv;
2895 int fd;
2897 TFR(fd = open(filename, O_RDWR));
2898 if (fd < 0)
2899 return NULL;
2901 if (ioctl(fd, PPCLAIM) < 0) {
2902 close(fd);
2903 return NULL;
2906 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2907 if (!drv) {
2908 close(fd);
2909 return NULL;
2911 drv->fd = fd;
2912 drv->mode = IEEE1284_MODE_COMPAT;
2914 chr = qemu_mallocz(sizeof(CharDriverState));
2915 if (!chr) {
2916 qemu_free(drv);
2917 close(fd);
2918 return NULL;
2920 chr->chr_write = null_chr_write;
2921 chr->chr_ioctl = pp_ioctl;
2922 chr->chr_close = pp_close;
2923 chr->opaque = drv;
2925 qemu_chr_reset(chr);
2927 return chr;
2929 #endif /* __linux__ */
2931 #else /* _WIN32 */
2933 typedef struct {
2934 int max_size;
2935 HANDLE hcom, hrecv, hsend;
2936 OVERLAPPED orecv, osend;
2937 BOOL fpipe;
2938 DWORD len;
2939 } WinCharState;
2941 #define NSENDBUF 2048
2942 #define NRECVBUF 2048
2943 #define MAXCONNECT 1
2944 #define NTIMEOUT 5000
2946 static int win_chr_poll(void *opaque);
2947 static int win_chr_pipe_poll(void *opaque);
2949 static void win_chr_close(CharDriverState *chr)
2951 WinCharState *s = chr->opaque;
2953 if (s->hsend) {
2954 CloseHandle(s->hsend);
2955 s->hsend = NULL;
2957 if (s->hrecv) {
2958 CloseHandle(s->hrecv);
2959 s->hrecv = NULL;
2961 if (s->hcom) {
2962 CloseHandle(s->hcom);
2963 s->hcom = NULL;
2965 if (s->fpipe)
2966 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2967 else
2968 qemu_del_polling_cb(win_chr_poll, chr);
2971 static int win_chr_init(CharDriverState *chr, const char *filename)
2973 WinCharState *s = chr->opaque;
2974 COMMCONFIG comcfg;
2975 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2976 COMSTAT comstat;
2977 DWORD size;
2978 DWORD err;
2980 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2981 if (!s->hsend) {
2982 fprintf(stderr, "Failed CreateEvent\n");
2983 goto fail;
2985 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2986 if (!s->hrecv) {
2987 fprintf(stderr, "Failed CreateEvent\n");
2988 goto fail;
2991 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2992 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2993 if (s->hcom == INVALID_HANDLE_VALUE) {
2994 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2995 s->hcom = NULL;
2996 goto fail;
2999 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3000 fprintf(stderr, "Failed SetupComm\n");
3001 goto fail;
3004 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3005 size = sizeof(COMMCONFIG);
3006 GetDefaultCommConfig(filename, &comcfg, &size);
3007 comcfg.dcb.DCBlength = sizeof(DCB);
3008 CommConfigDialog(filename, NULL, &comcfg);
3010 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3011 fprintf(stderr, "Failed SetCommState\n");
3012 goto fail;
3015 if (!SetCommMask(s->hcom, EV_ERR)) {
3016 fprintf(stderr, "Failed SetCommMask\n");
3017 goto fail;
3020 cto.ReadIntervalTimeout = MAXDWORD;
3021 if (!SetCommTimeouts(s->hcom, &cto)) {
3022 fprintf(stderr, "Failed SetCommTimeouts\n");
3023 goto fail;
3026 if (!ClearCommError(s->hcom, &err, &comstat)) {
3027 fprintf(stderr, "Failed ClearCommError\n");
3028 goto fail;
3030 qemu_add_polling_cb(win_chr_poll, chr);
3031 return 0;
3033 fail:
3034 win_chr_close(chr);
3035 return -1;
3038 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3040 WinCharState *s = chr->opaque;
3041 DWORD len, ret, size, err;
3043 len = len1;
3044 ZeroMemory(&s->osend, sizeof(s->osend));
3045 s->osend.hEvent = s->hsend;
3046 while (len > 0) {
3047 if (s->hsend)
3048 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3049 else
3050 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3051 if (!ret) {
3052 err = GetLastError();
3053 if (err == ERROR_IO_PENDING) {
3054 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3055 if (ret) {
3056 buf += size;
3057 len -= size;
3058 } else {
3059 break;
3061 } else {
3062 break;
3064 } else {
3065 buf += size;
3066 len -= size;
3069 return len1 - len;
3072 static int win_chr_read_poll(CharDriverState *chr)
3074 WinCharState *s = chr->opaque;
3076 s->max_size = qemu_chr_can_read(chr);
3077 return s->max_size;
3080 static void win_chr_readfile(CharDriverState *chr)
3082 WinCharState *s = chr->opaque;
3083 int ret, err;
3084 uint8_t buf[1024];
3085 DWORD size;
3087 ZeroMemory(&s->orecv, sizeof(s->orecv));
3088 s->orecv.hEvent = s->hrecv;
3089 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3090 if (!ret) {
3091 err = GetLastError();
3092 if (err == ERROR_IO_PENDING) {
3093 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3097 if (size > 0) {
3098 qemu_chr_read(chr, buf, size);
3102 static void win_chr_read(CharDriverState *chr)
3104 WinCharState *s = chr->opaque;
3106 if (s->len > s->max_size)
3107 s->len = s->max_size;
3108 if (s->len == 0)
3109 return;
3111 win_chr_readfile(chr);
3114 static int win_chr_poll(void *opaque)
3116 CharDriverState *chr = opaque;
3117 WinCharState *s = chr->opaque;
3118 COMSTAT status;
3119 DWORD comerr;
3121 ClearCommError(s->hcom, &comerr, &status);
3122 if (status.cbInQue > 0) {
3123 s->len = status.cbInQue;
3124 win_chr_read_poll(chr);
3125 win_chr_read(chr);
3126 return 1;
3128 return 0;
3131 static CharDriverState *qemu_chr_open_win(const char *filename)
3133 CharDriverState *chr;
3134 WinCharState *s;
3136 chr = qemu_mallocz(sizeof(CharDriverState));
3137 if (!chr)
3138 return NULL;
3139 s = qemu_mallocz(sizeof(WinCharState));
3140 if (!s) {
3141 free(chr);
3142 return NULL;
3144 chr->opaque = s;
3145 chr->chr_write = win_chr_write;
3146 chr->chr_close = win_chr_close;
3148 if (win_chr_init(chr, filename) < 0) {
3149 free(s);
3150 free(chr);
3151 return NULL;
3153 qemu_chr_reset(chr);
3154 return chr;
3157 static int win_chr_pipe_poll(void *opaque)
3159 CharDriverState *chr = opaque;
3160 WinCharState *s = chr->opaque;
3161 DWORD size;
3163 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3164 if (size > 0) {
3165 s->len = size;
3166 win_chr_read_poll(chr);
3167 win_chr_read(chr);
3168 return 1;
3170 return 0;
3173 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3175 WinCharState *s = chr->opaque;
3176 OVERLAPPED ov;
3177 int ret;
3178 DWORD size;
3179 char openname[256];
3181 s->fpipe = TRUE;
3183 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3184 if (!s->hsend) {
3185 fprintf(stderr, "Failed CreateEvent\n");
3186 goto fail;
3188 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3189 if (!s->hrecv) {
3190 fprintf(stderr, "Failed CreateEvent\n");
3191 goto fail;
3194 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3195 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3196 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3197 PIPE_WAIT,
3198 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3199 if (s->hcom == INVALID_HANDLE_VALUE) {
3200 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3201 s->hcom = NULL;
3202 goto fail;
3205 ZeroMemory(&ov, sizeof(ov));
3206 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3207 ret = ConnectNamedPipe(s->hcom, &ov);
3208 if (ret) {
3209 fprintf(stderr, "Failed ConnectNamedPipe\n");
3210 goto fail;
3213 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3214 if (!ret) {
3215 fprintf(stderr, "Failed GetOverlappedResult\n");
3216 if (ov.hEvent) {
3217 CloseHandle(ov.hEvent);
3218 ov.hEvent = NULL;
3220 goto fail;
3223 if (ov.hEvent) {
3224 CloseHandle(ov.hEvent);
3225 ov.hEvent = NULL;
3227 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3228 return 0;
3230 fail:
3231 win_chr_close(chr);
3232 return -1;
3236 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3238 CharDriverState *chr;
3239 WinCharState *s;
3241 chr = qemu_mallocz(sizeof(CharDriverState));
3242 if (!chr)
3243 return NULL;
3244 s = qemu_mallocz(sizeof(WinCharState));
3245 if (!s) {
3246 free(chr);
3247 return NULL;
3249 chr->opaque = s;
3250 chr->chr_write = win_chr_write;
3251 chr->chr_close = win_chr_close;
3253 if (win_chr_pipe_init(chr, filename) < 0) {
3254 free(s);
3255 free(chr);
3256 return NULL;
3258 qemu_chr_reset(chr);
3259 return chr;
3262 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3264 CharDriverState *chr;
3265 WinCharState *s;
3267 chr = qemu_mallocz(sizeof(CharDriverState));
3268 if (!chr)
3269 return NULL;
3270 s = qemu_mallocz(sizeof(WinCharState));
3271 if (!s) {
3272 free(chr);
3273 return NULL;
3275 s->hcom = fd_out;
3276 chr->opaque = s;
3277 chr->chr_write = win_chr_write;
3278 qemu_chr_reset(chr);
3279 return chr;
3282 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3284 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3287 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3289 HANDLE fd_out;
3291 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3292 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3293 if (fd_out == INVALID_HANDLE_VALUE)
3294 return NULL;
3296 return qemu_chr_open_win_file(fd_out);
3298 #endif /* !_WIN32 */
3300 /***********************************************************/
3301 /* UDP Net console */
3303 typedef struct {
3304 int fd;
3305 struct sockaddr_in daddr;
3306 uint8_t buf[1024];
3307 int bufcnt;
3308 int bufptr;
3309 int max_size;
3310 } NetCharDriver;
3312 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3314 NetCharDriver *s = chr->opaque;
3316 return sendto(s->fd, buf, len, 0,
3317 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3320 static int udp_chr_read_poll(void *opaque)
3322 CharDriverState *chr = opaque;
3323 NetCharDriver *s = chr->opaque;
3325 s->max_size = qemu_chr_can_read(chr);
3327 /* If there were any stray characters in the queue process them
3328 * first
3330 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3331 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3332 s->bufptr++;
3333 s->max_size = qemu_chr_can_read(chr);
3335 return s->max_size;
3338 static void udp_chr_read(void *opaque)
3340 CharDriverState *chr = opaque;
3341 NetCharDriver *s = chr->opaque;
3343 if (s->max_size == 0)
3344 return;
3345 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3346 s->bufptr = s->bufcnt;
3347 if (s->bufcnt <= 0)
3348 return;
3350 s->bufptr = 0;
3351 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3352 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3353 s->bufptr++;
3354 s->max_size = qemu_chr_can_read(chr);
3358 static void udp_chr_update_read_handler(CharDriverState *chr)
3360 NetCharDriver *s = chr->opaque;
3362 if (s->fd >= 0) {
3363 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3364 udp_chr_read, NULL, chr);
3368 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3369 #ifndef _WIN32
3370 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3371 #endif
3372 int parse_host_src_port(struct sockaddr_in *haddr,
3373 struct sockaddr_in *saddr,
3374 const char *str);
3376 static CharDriverState *qemu_chr_open_udp(const char *def)
3378 CharDriverState *chr = NULL;
3379 NetCharDriver *s = NULL;
3380 int fd = -1;
3381 struct sockaddr_in saddr;
3383 chr = qemu_mallocz(sizeof(CharDriverState));
3384 if (!chr)
3385 goto return_err;
3386 s = qemu_mallocz(sizeof(NetCharDriver));
3387 if (!s)
3388 goto return_err;
3390 fd = socket(PF_INET, SOCK_DGRAM, 0);
3391 if (fd < 0) {
3392 perror("socket(PF_INET, SOCK_DGRAM)");
3393 goto return_err;
3396 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3397 printf("Could not parse: %s\n", def);
3398 goto return_err;
3401 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3403 perror("bind");
3404 goto return_err;
3407 s->fd = fd;
3408 s->bufcnt = 0;
3409 s->bufptr = 0;
3410 chr->opaque = s;
3411 chr->chr_write = udp_chr_write;
3412 chr->chr_update_read_handler = udp_chr_update_read_handler;
3413 return chr;
3415 return_err:
3416 if (chr)
3417 free(chr);
3418 if (s)
3419 free(s);
3420 if (fd >= 0)
3421 closesocket(fd);
3422 return NULL;
3425 /***********************************************************/
3426 /* TCP Net console */
3428 typedef struct {
3429 int fd, listen_fd;
3430 int connected;
3431 int max_size;
3432 int do_telnetopt;
3433 int do_nodelay;
3434 int is_unix;
3435 } TCPCharDriver;
3437 static void tcp_chr_accept(void *opaque);
3439 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3441 TCPCharDriver *s = chr->opaque;
3442 if (s->connected) {
3443 return send_all(s->fd, buf, len);
3444 } else {
3445 /* XXX: indicate an error ? */
3446 return len;
3450 static int tcp_chr_read_poll(void *opaque)
3452 CharDriverState *chr = opaque;
3453 TCPCharDriver *s = chr->opaque;
3454 if (!s->connected)
3455 return 0;
3456 s->max_size = qemu_chr_can_read(chr);
3457 return s->max_size;
3460 #define IAC 255
3461 #define IAC_BREAK 243
3462 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3463 TCPCharDriver *s,
3464 uint8_t *buf, int *size)
3466 /* Handle any telnet client's basic IAC options to satisfy char by
3467 * char mode with no echo. All IAC options will be removed from
3468 * the buf and the do_telnetopt variable will be used to track the
3469 * state of the width of the IAC information.
3471 * IAC commands come in sets of 3 bytes with the exception of the
3472 * "IAC BREAK" command and the double IAC.
3475 int i;
3476 int j = 0;
3478 for (i = 0; i < *size; i++) {
3479 if (s->do_telnetopt > 1) {
3480 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3481 /* Double IAC means send an IAC */
3482 if (j != i)
3483 buf[j] = buf[i];
3484 j++;
3485 s->do_telnetopt = 1;
3486 } else {
3487 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3488 /* Handle IAC break commands by sending a serial break */
3489 qemu_chr_event(chr, CHR_EVENT_BREAK);
3490 s->do_telnetopt++;
3492 s->do_telnetopt++;
3494 if (s->do_telnetopt >= 4) {
3495 s->do_telnetopt = 1;
3497 } else {
3498 if ((unsigned char)buf[i] == IAC) {
3499 s->do_telnetopt = 2;
3500 } else {
3501 if (j != i)
3502 buf[j] = buf[i];
3503 j++;
3507 *size = j;
3510 static void tcp_chr_read(void *opaque)
3512 CharDriverState *chr = opaque;
3513 TCPCharDriver *s = chr->opaque;
3514 uint8_t buf[1024];
3515 int len, size;
3517 if (!s->connected || s->max_size <= 0)
3518 return;
3519 len = sizeof(buf);
3520 if (len > s->max_size)
3521 len = s->max_size;
3522 size = recv(s->fd, buf, len, 0);
3523 if (size == 0) {
3524 /* connection closed */
3525 s->connected = 0;
3526 if (s->listen_fd >= 0) {
3527 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3529 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3530 closesocket(s->fd);
3531 s->fd = -1;
3532 } else if (size > 0) {
3533 if (s->do_telnetopt)
3534 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3535 if (size > 0)
3536 qemu_chr_read(chr, buf, size);
3540 static void tcp_chr_connect(void *opaque)
3542 CharDriverState *chr = opaque;
3543 TCPCharDriver *s = chr->opaque;
3545 s->connected = 1;
3546 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3547 tcp_chr_read, NULL, chr);
3548 qemu_chr_reset(chr);
3551 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3552 static void tcp_chr_telnet_init(int fd)
3554 char buf[3];
3555 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3556 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3557 send(fd, (char *)buf, 3, 0);
3558 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3559 send(fd, (char *)buf, 3, 0);
3560 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3561 send(fd, (char *)buf, 3, 0);
3562 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3563 send(fd, (char *)buf, 3, 0);
3566 static void socket_set_nodelay(int fd)
3568 int val = 1;
3569 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3572 static void tcp_chr_accept(void *opaque)
3574 CharDriverState *chr = opaque;
3575 TCPCharDriver *s = chr->opaque;
3576 struct sockaddr_in saddr;
3577 #ifndef _WIN32
3578 struct sockaddr_un uaddr;
3579 #endif
3580 struct sockaddr *addr;
3581 socklen_t len;
3582 int fd;
3584 for(;;) {
3585 #ifndef _WIN32
3586 if (s->is_unix) {
3587 len = sizeof(uaddr);
3588 addr = (struct sockaddr *)&uaddr;
3589 } else
3590 #endif
3592 len = sizeof(saddr);
3593 addr = (struct sockaddr *)&saddr;
3595 fd = accept(s->listen_fd, addr, &len);
3596 if (fd < 0 && errno != EINTR) {
3597 return;
3598 } else if (fd >= 0) {
3599 if (s->do_telnetopt)
3600 tcp_chr_telnet_init(fd);
3601 break;
3604 socket_set_nonblock(fd);
3605 if (s->do_nodelay)
3606 socket_set_nodelay(fd);
3607 s->fd = fd;
3608 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3609 tcp_chr_connect(chr);
3612 static void tcp_chr_close(CharDriverState *chr)
3614 TCPCharDriver *s = chr->opaque;
3615 if (s->fd >= 0)
3616 closesocket(s->fd);
3617 if (s->listen_fd >= 0)
3618 closesocket(s->listen_fd);
3619 qemu_free(s);
3622 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3623 int is_telnet,
3624 int is_unix)
3626 CharDriverState *chr = NULL;
3627 TCPCharDriver *s = NULL;
3628 int fd = -1, ret, err, val;
3629 int is_listen = 0;
3630 int is_waitconnect = 1;
3631 int do_nodelay = 0;
3632 const char *ptr;
3633 struct sockaddr_in saddr;
3634 #ifndef _WIN32
3635 struct sockaddr_un uaddr;
3636 #endif
3637 struct sockaddr *addr;
3638 socklen_t addrlen;
3640 #ifndef _WIN32
3641 if (is_unix) {
3642 addr = (struct sockaddr *)&uaddr;
3643 addrlen = sizeof(uaddr);
3644 if (parse_unix_path(&uaddr, host_str) < 0)
3645 goto fail;
3646 } else
3647 #endif
3649 addr = (struct sockaddr *)&saddr;
3650 addrlen = sizeof(saddr);
3651 if (parse_host_port(&saddr, host_str) < 0)
3652 goto fail;
3655 ptr = host_str;
3656 while((ptr = strchr(ptr,','))) {
3657 ptr++;
3658 if (!strncmp(ptr,"server",6)) {
3659 is_listen = 1;
3660 } else if (!strncmp(ptr,"nowait",6)) {
3661 is_waitconnect = 0;
3662 } else if (!strncmp(ptr,"nodelay",6)) {
3663 do_nodelay = 1;
3664 } else {
3665 printf("Unknown option: %s\n", ptr);
3666 goto fail;
3669 if (!is_listen)
3670 is_waitconnect = 0;
3672 chr = qemu_mallocz(sizeof(CharDriverState));
3673 if (!chr)
3674 goto fail;
3675 s = qemu_mallocz(sizeof(TCPCharDriver));
3676 if (!s)
3677 goto fail;
3679 #ifndef _WIN32
3680 if (is_unix)
3681 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3682 else
3683 #endif
3684 fd = socket(PF_INET, SOCK_STREAM, 0);
3686 if (fd < 0)
3687 goto fail;
3689 if (!is_waitconnect)
3690 socket_set_nonblock(fd);
3692 s->connected = 0;
3693 s->fd = -1;
3694 s->listen_fd = -1;
3695 s->is_unix = is_unix;
3696 s->do_nodelay = do_nodelay && !is_unix;
3698 chr->opaque = s;
3699 chr->chr_write = tcp_chr_write;
3700 chr->chr_close = tcp_chr_close;
3702 if (is_listen) {
3703 /* allow fast reuse */
3704 #ifndef _WIN32
3705 if (is_unix) {
3706 char path[109];
3707 pstrcpy(path, sizeof(path), uaddr.sun_path);
3708 unlink(path);
3709 } else
3710 #endif
3712 val = 1;
3713 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3716 ret = bind(fd, addr, addrlen);
3717 if (ret < 0)
3718 goto fail;
3720 ret = listen(fd, 0);
3721 if (ret < 0)
3722 goto fail;
3724 s->listen_fd = fd;
3725 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3726 if (is_telnet)
3727 s->do_telnetopt = 1;
3728 } else {
3729 for(;;) {
3730 ret = connect(fd, addr, addrlen);
3731 if (ret < 0) {
3732 err = socket_error();
3733 if (err == EINTR || err == EWOULDBLOCK) {
3734 } else if (err == EINPROGRESS) {
3735 break;
3736 #ifdef _WIN32
3737 } else if (err == WSAEALREADY) {
3738 break;
3739 #endif
3740 } else {
3741 goto fail;
3743 } else {
3744 s->connected = 1;
3745 break;
3748 s->fd = fd;
3749 socket_set_nodelay(fd);
3750 if (s->connected)
3751 tcp_chr_connect(chr);
3752 else
3753 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3756 if (is_listen && is_waitconnect) {
3757 printf("QEMU waiting for connection on: %s\n", host_str);
3758 tcp_chr_accept(chr);
3759 socket_set_nonblock(s->listen_fd);
3762 return chr;
3763 fail:
3764 if (fd >= 0)
3765 closesocket(fd);
3766 qemu_free(s);
3767 qemu_free(chr);
3768 return NULL;
3771 CharDriverState *qemu_chr_open(const char *filename)
3773 const char *p;
3775 if (!strcmp(filename, "vc")) {
3776 return text_console_init(&display_state, 0);
3777 } else if (strstart(filename, "vc:", &p)) {
3778 return text_console_init(&display_state, p);
3779 } else if (!strcmp(filename, "null")) {
3780 return qemu_chr_open_null();
3781 } else
3782 if (strstart(filename, "tcp:", &p)) {
3783 return qemu_chr_open_tcp(p, 0, 0);
3784 } else
3785 if (strstart(filename, "telnet:", &p)) {
3786 return qemu_chr_open_tcp(p, 1, 0);
3787 } else
3788 if (strstart(filename, "udp:", &p)) {
3789 return qemu_chr_open_udp(p);
3790 } else
3791 if (strstart(filename, "mon:", &p)) {
3792 CharDriverState *drv = qemu_chr_open(p);
3793 if (drv) {
3794 drv = qemu_chr_open_mux(drv);
3795 monitor_init(drv, !nographic);
3796 return drv;
3798 printf("Unable to open driver: %s\n", p);
3799 return 0;
3800 } else
3801 #ifndef _WIN32
3802 if (strstart(filename, "unix:", &p)) {
3803 return qemu_chr_open_tcp(p, 0, 1);
3804 } else if (strstart(filename, "file:", &p)) {
3805 return qemu_chr_open_file_out(p);
3806 } else if (strstart(filename, "pipe:", &p)) {
3807 return qemu_chr_open_pipe(p);
3808 } else if (!strcmp(filename, "pty")) {
3809 return qemu_chr_open_pty();
3810 } else if (!strcmp(filename, "stdio")) {
3811 return qemu_chr_open_stdio();
3812 } else
3813 #if defined(__linux__)
3814 if (strstart(filename, "/dev/parport", NULL)) {
3815 return qemu_chr_open_pp(filename);
3816 } else
3817 #endif
3818 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3819 || defined(__NetBSD__) || defined(__OpenBSD__)
3820 if (strstart(filename, "/dev/", NULL)) {
3821 return qemu_chr_open_tty(filename);
3822 } else
3823 #endif
3824 #else /* !_WIN32 */
3825 if (strstart(filename, "COM", NULL)) {
3826 return qemu_chr_open_win(filename);
3827 } else
3828 if (strstart(filename, "pipe:", &p)) {
3829 return qemu_chr_open_win_pipe(p);
3830 } else
3831 if (strstart(filename, "con:", NULL)) {
3832 return qemu_chr_open_win_con(filename);
3833 } else
3834 if (strstart(filename, "file:", &p)) {
3835 return qemu_chr_open_win_file_out(p);
3836 } else
3837 #endif
3838 #ifdef CONFIG_BRLAPI
3839 if (!strcmp(filename, "braille")) {
3840 return chr_baum_init();
3841 } else
3842 #endif
3844 return NULL;
3848 void qemu_chr_close(CharDriverState *chr)
3850 if (chr->chr_close)
3851 chr->chr_close(chr);
3852 qemu_free(chr);
3855 /***********************************************************/
3856 /* network device redirectors */
3858 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
3859 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3861 int len, i, j, c;
3863 for(i=0;i<size;i+=16) {
3864 len = size - i;
3865 if (len > 16)
3866 len = 16;
3867 fprintf(f, "%08x ", i);
3868 for(j=0;j<16;j++) {
3869 if (j < len)
3870 fprintf(f, " %02x", buf[i+j]);
3871 else
3872 fprintf(f, " ");
3874 fprintf(f, " ");
3875 for(j=0;j<len;j++) {
3876 c = buf[i+j];
3877 if (c < ' ' || c > '~')
3878 c = '.';
3879 fprintf(f, "%c", c);
3881 fprintf(f, "\n");
3884 #endif
3886 static int parse_macaddr(uint8_t *macaddr, const char *p)
3888 int i;
3889 char *last_char;
3890 long int offset;
3892 errno = 0;
3893 offset = strtol(p, &last_char, 0);
3894 if (0 == errno && '\0' == *last_char &&
3895 offset >= 0 && offset <= 0xFFFFFF) {
3896 macaddr[3] = (offset & 0xFF0000) >> 16;
3897 macaddr[4] = (offset & 0xFF00) >> 8;
3898 macaddr[5] = offset & 0xFF;
3899 return 0;
3900 } else {
3901 for(i = 0; i < 6; i++) {
3902 macaddr[i] = strtol(p, (char **)&p, 16);
3903 if (i == 5) {
3904 if (*p != '\0')
3905 return -1;
3906 } else {
3907 if (*p != ':' && *p != '-')
3908 return -1;
3909 p++;
3912 return 0;
3915 return -1;
3918 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3920 const char *p, *p1;
3921 int len;
3922 p = *pp;
3923 p1 = strchr(p, sep);
3924 if (!p1)
3925 return -1;
3926 len = p1 - p;
3927 p1++;
3928 if (buf_size > 0) {
3929 if (len > buf_size - 1)
3930 len = buf_size - 1;
3931 memcpy(buf, p, len);
3932 buf[len] = '\0';
3934 *pp = p1;
3935 return 0;
3938 int parse_host_src_port(struct sockaddr_in *haddr,
3939 struct sockaddr_in *saddr,
3940 const char *input_str)
3942 char *str = strdup(input_str);
3943 char *host_str = str;
3944 char *src_str;
3945 const char *src_str2;
3946 char *ptr;
3949 * Chop off any extra arguments at the end of the string which
3950 * would start with a comma, then fill in the src port information
3951 * if it was provided else use the "any address" and "any port".
3953 if ((ptr = strchr(str,',')))
3954 *ptr = '\0';
3956 if ((src_str = strchr(input_str,'@'))) {
3957 *src_str = '\0';
3958 src_str++;
3961 if (parse_host_port(haddr, host_str) < 0)
3962 goto fail;
3964 src_str2 = src_str;
3965 if (!src_str || *src_str == '\0')
3966 src_str2 = ":0";
3968 if (parse_host_port(saddr, src_str2) < 0)
3969 goto fail;
3971 free(str);
3972 return(0);
3974 fail:
3975 free(str);
3976 return -1;
3979 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3981 char buf[512];
3982 struct hostent *he;
3983 const char *p, *r;
3984 int port;
3986 p = str;
3987 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3988 return -1;
3989 saddr->sin_family = AF_INET;
3990 if (buf[0] == '\0') {
3991 saddr->sin_addr.s_addr = 0;
3992 } else {
3993 if (isdigit(buf[0])) {
3994 if (!inet_aton(buf, &saddr->sin_addr))
3995 return -1;
3996 } else {
3997 if ((he = gethostbyname(buf)) == NULL)
3998 return - 1;
3999 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4002 port = strtol(p, (char **)&r, 0);
4003 if (r == p)
4004 return -1;
4005 saddr->sin_port = htons(port);
4006 return 0;
4009 #ifndef _WIN32
4010 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4012 const char *p;
4013 int len;
4015 len = MIN(108, strlen(str));
4016 p = strchr(str, ',');
4017 if (p)
4018 len = MIN(len, p - str);
4020 memset(uaddr, 0, sizeof(*uaddr));
4022 uaddr->sun_family = AF_UNIX;
4023 memcpy(uaddr->sun_path, str, len);
4025 return 0;
4027 #endif
4029 /* find or alloc a new VLAN */
4030 VLANState *qemu_find_vlan(int id)
4032 VLANState **pvlan, *vlan;
4033 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4034 if (vlan->id == id)
4035 return vlan;
4037 vlan = qemu_mallocz(sizeof(VLANState));
4038 if (!vlan)
4039 return NULL;
4040 vlan->id = id;
4041 vlan->next = NULL;
4042 pvlan = &first_vlan;
4043 while (*pvlan != NULL)
4044 pvlan = &(*pvlan)->next;
4045 *pvlan = vlan;
4046 return vlan;
4049 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4050 IOReadHandler *fd_read,
4051 IOCanRWHandler *fd_can_read,
4052 void *opaque)
4054 VLANClientState *vc, **pvc;
4055 vc = qemu_mallocz(sizeof(VLANClientState));
4056 if (!vc)
4057 return NULL;
4058 vc->fd_read = fd_read;
4059 vc->fd_can_read = fd_can_read;
4060 vc->opaque = opaque;
4061 vc->vlan = vlan;
4063 vc->next = NULL;
4064 pvc = &vlan->first_client;
4065 while (*pvc != NULL)
4066 pvc = &(*pvc)->next;
4067 *pvc = vc;
4068 return vc;
4071 void qemu_del_vlan_client(VLANClientState *vc)
4073 VLANClientState **pvc = &vc->vlan->first_client;
4075 while (*pvc != NULL)
4076 if (*pvc == vc) {
4077 *pvc = vc->next;
4078 free(vc);
4079 break;
4080 } else
4081 pvc = &(*pvc)->next;
4084 int qemu_can_send_packet(VLANClientState *vc1)
4086 VLANState *vlan = vc1->vlan;
4087 VLANClientState *vc;
4089 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4090 if (vc != vc1) {
4091 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4092 return 1;
4095 return 0;
4098 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4100 VLANState *vlan = vc1->vlan;
4101 VLANClientState *vc;
4103 #ifdef DEBUG_NET
4104 printf("vlan %d send:\n", vlan->id);
4105 hex_dump(stdout, buf, size);
4106 #endif
4107 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4108 if (vc != vc1) {
4109 vc->fd_read(vc->opaque, buf, size);
4114 #if defined(CONFIG_SLIRP)
4116 /* slirp network adapter */
4118 static int slirp_inited;
4119 static VLANClientState *slirp_vc;
4121 int slirp_can_output(void)
4123 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4126 void slirp_output(const uint8_t *pkt, int pkt_len)
4128 #ifdef DEBUG_SLIRP
4129 printf("slirp output:\n");
4130 hex_dump(stdout, pkt, pkt_len);
4131 #endif
4132 if (!slirp_vc)
4133 return;
4134 qemu_send_packet(slirp_vc, pkt, pkt_len);
4137 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4139 #ifdef DEBUG_SLIRP
4140 printf("slirp input:\n");
4141 hex_dump(stdout, buf, size);
4142 #endif
4143 slirp_input(buf, size);
4146 static int net_slirp_init(VLANState *vlan)
4148 if (!slirp_inited) {
4149 slirp_inited = 1;
4150 slirp_init();
4152 slirp_vc = qemu_new_vlan_client(vlan,
4153 slirp_receive, NULL, NULL);
4154 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4155 return 0;
4158 static void net_slirp_redir(const char *redir_str)
4160 int is_udp;
4161 char buf[256], *r;
4162 const char *p;
4163 struct in_addr guest_addr;
4164 int host_port, guest_port;
4166 if (!slirp_inited) {
4167 slirp_inited = 1;
4168 slirp_init();
4171 p = redir_str;
4172 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4173 goto fail;
4174 if (!strcmp(buf, "tcp")) {
4175 is_udp = 0;
4176 } else if (!strcmp(buf, "udp")) {
4177 is_udp = 1;
4178 } else {
4179 goto fail;
4182 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4183 goto fail;
4184 host_port = strtol(buf, &r, 0);
4185 if (r == buf)
4186 goto fail;
4188 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4189 goto fail;
4190 if (buf[0] == '\0') {
4191 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4193 if (!inet_aton(buf, &guest_addr))
4194 goto fail;
4196 guest_port = strtol(p, &r, 0);
4197 if (r == p)
4198 goto fail;
4200 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4201 fprintf(stderr, "qemu: could not set up redirection\n");
4202 exit(1);
4204 return;
4205 fail:
4206 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4207 exit(1);
4210 #ifndef _WIN32
4212 static char smb_dir[1024];
4214 static void erase_dir(char *dir_name)
4216 DIR *d;
4217 struct dirent *de;
4218 char filename[1024];
4220 /* erase all the files in the directory */
4221 if ((d = opendir(dir_name)) != 0) {
4222 for(;;) {
4223 de = readdir(d);
4224 if (!de)
4225 break;
4226 if (strcmp(de->d_name, ".") != 0 &&
4227 strcmp(de->d_name, "..") != 0) {
4228 snprintf(filename, sizeof(filename), "%s/%s",
4229 smb_dir, de->d_name);
4230 if (unlink(filename) != 0) /* is it a directory? */
4231 erase_dir(filename);
4234 closedir(d);
4235 rmdir(dir_name);
4239 /* automatic user mode samba server configuration */
4240 static void smb_exit(void)
4242 erase_dir(smb_dir);
4245 /* automatic user mode samba server configuration */
4246 static void net_slirp_smb(const char *exported_dir)
4248 char smb_conf[1024];
4249 char smb_cmdline[1024];
4250 FILE *f;
4252 if (!slirp_inited) {
4253 slirp_inited = 1;
4254 slirp_init();
4257 /* XXX: better tmp dir construction */
4258 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4259 if (mkdir(smb_dir, 0700) < 0) {
4260 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4261 exit(1);
4263 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4265 f = fopen(smb_conf, "w");
4266 if (!f) {
4267 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4268 exit(1);
4270 fprintf(f,
4271 "[global]\n"
4272 "private dir=%s\n"
4273 "smb ports=0\n"
4274 "socket address=127.0.0.1\n"
4275 "pid directory=%s\n"
4276 "lock directory=%s\n"
4277 "log file=%s/log.smbd\n"
4278 "smb passwd file=%s/smbpasswd\n"
4279 "security = share\n"
4280 "[qemu]\n"
4281 "path=%s\n"
4282 "read only=no\n"
4283 "guest ok=yes\n",
4284 smb_dir,
4285 smb_dir,
4286 smb_dir,
4287 smb_dir,
4288 smb_dir,
4289 exported_dir
4291 fclose(f);
4292 atexit(smb_exit);
4294 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4295 SMBD_COMMAND, smb_conf);
4297 slirp_add_exec(0, smb_cmdline, 4, 139);
4300 #endif /* !defined(_WIN32) */
4301 void do_info_slirp(void)
4303 slirp_stats();
4306 #endif /* CONFIG_SLIRP */
4308 #if !defined(_WIN32)
4310 typedef struct TAPState {
4311 VLANClientState *vc;
4312 int fd;
4313 char down_script[1024];
4314 } TAPState;
4316 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4318 TAPState *s = opaque;
4319 int ret;
4320 for(;;) {
4321 ret = write(s->fd, buf, size);
4322 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4323 } else {
4324 break;
4329 static void tap_send(void *opaque)
4331 TAPState *s = opaque;
4332 uint8_t buf[4096];
4333 int size;
4335 #ifdef __sun__
4336 struct strbuf sbuf;
4337 int f = 0;
4338 sbuf.maxlen = sizeof(buf);
4339 sbuf.buf = buf;
4340 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4341 #else
4342 size = read(s->fd, buf, sizeof(buf));
4343 #endif
4344 if (size > 0) {
4345 qemu_send_packet(s->vc, buf, size);
4349 /* fd support */
4351 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4353 TAPState *s;
4355 s = qemu_mallocz(sizeof(TAPState));
4356 if (!s)
4357 return NULL;
4358 s->fd = fd;
4359 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4360 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4361 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4362 return s;
4365 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4366 static int tap_open(char *ifname, int ifname_size)
4368 int fd;
4369 char *dev;
4370 struct stat s;
4372 TFR(fd = open("/dev/tap", O_RDWR));
4373 if (fd < 0) {
4374 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4375 return -1;
4378 fstat(fd, &s);
4379 dev = devname(s.st_rdev, S_IFCHR);
4380 pstrcpy(ifname, ifname_size, dev);
4382 fcntl(fd, F_SETFL, O_NONBLOCK);
4383 return fd;
4385 #elif defined(__sun__)
4386 #define TUNNEWPPA (('T'<<16) | 0x0001)
4388 * Allocate TAP device, returns opened fd.
4389 * Stores dev name in the first arg(must be large enough).
4391 int tap_alloc(char *dev, size_t dev_size)
4393 int tap_fd, if_fd, ppa = -1;
4394 static int ip_fd = 0;
4395 char *ptr;
4397 static int arp_fd = 0;
4398 int ip_muxid, arp_muxid;
4399 struct strioctl strioc_if, strioc_ppa;
4400 int link_type = I_PLINK;;
4401 struct lifreq ifr;
4402 char actual_name[32] = "";
4404 memset(&ifr, 0x0, sizeof(ifr));
4406 if( *dev ){
4407 ptr = dev;
4408 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4409 ppa = atoi(ptr);
4412 /* Check if IP device was opened */
4413 if( ip_fd )
4414 close(ip_fd);
4416 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4417 if (ip_fd < 0) {
4418 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4419 return -1;
4422 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4423 if (tap_fd < 0) {
4424 syslog(LOG_ERR, "Can't open /dev/tap");
4425 return -1;
4428 /* Assign a new PPA and get its unit number. */
4429 strioc_ppa.ic_cmd = TUNNEWPPA;
4430 strioc_ppa.ic_timout = 0;
4431 strioc_ppa.ic_len = sizeof(ppa);
4432 strioc_ppa.ic_dp = (char *)&ppa;
4433 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4434 syslog (LOG_ERR, "Can't assign new interface");
4436 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4437 if (if_fd < 0) {
4438 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4439 return -1;
4441 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4442 syslog(LOG_ERR, "Can't push IP module");
4443 return -1;
4446 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4447 syslog(LOG_ERR, "Can't get flags\n");
4449 snprintf (actual_name, 32, "tap%d", ppa);
4450 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4452 ifr.lifr_ppa = ppa;
4453 /* Assign ppa according to the unit number returned by tun device */
4455 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4456 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4457 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4458 syslog (LOG_ERR, "Can't get flags\n");
4459 /* Push arp module to if_fd */
4460 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4461 syslog (LOG_ERR, "Can't push ARP module (2)");
4463 /* Push arp module to ip_fd */
4464 if (ioctl (ip_fd, I_POP, NULL) < 0)
4465 syslog (LOG_ERR, "I_POP failed\n");
4466 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4467 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4468 /* Open arp_fd */
4469 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4470 if (arp_fd < 0)
4471 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4473 /* Set ifname to arp */
4474 strioc_if.ic_cmd = SIOCSLIFNAME;
4475 strioc_if.ic_timout = 0;
4476 strioc_if.ic_len = sizeof(ifr);
4477 strioc_if.ic_dp = (char *)&ifr;
4478 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4479 syslog (LOG_ERR, "Can't set ifname to arp\n");
4482 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4483 syslog(LOG_ERR, "Can't link TAP device to IP");
4484 return -1;
4487 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4488 syslog (LOG_ERR, "Can't link TAP device to ARP");
4490 close (if_fd);
4492 memset(&ifr, 0x0, sizeof(ifr));
4493 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4494 ifr.lifr_ip_muxid = ip_muxid;
4495 ifr.lifr_arp_muxid = arp_muxid;
4497 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4499 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4500 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4501 syslog (LOG_ERR, "Can't set multiplexor id");
4504 snprintf(dev, dev_size, "tap%d", ppa);
4505 return tap_fd;
4508 static int tap_open(char *ifname, int ifname_size)
4510 char dev[10]="";
4511 int fd;
4512 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4513 fprintf(stderr, "Cannot allocate TAP device\n");
4514 return -1;
4516 pstrcpy(ifname, ifname_size, dev);
4517 fcntl(fd, F_SETFL, O_NONBLOCK);
4518 return fd;
4520 #else
4521 static int tap_open(char *ifname, int ifname_size)
4523 struct ifreq ifr;
4524 int fd, ret;
4526 TFR(fd = open("/dev/net/tun", O_RDWR));
4527 if (fd < 0) {
4528 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4529 return -1;
4531 memset(&ifr, 0, sizeof(ifr));
4532 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4533 if (ifname[0] != '\0')
4534 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4535 else
4536 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4537 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4538 if (ret != 0) {
4539 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4540 close(fd);
4541 return -1;
4543 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4544 fcntl(fd, F_SETFL, O_NONBLOCK);
4545 return fd;
4547 #endif
4549 static int launch_script(const char *setup_script, const char *ifname, int fd)
4551 int pid, status;
4552 char *args[3];
4553 char **parg;
4555 /* try to launch network script */
4556 pid = fork();
4557 if (pid >= 0) {
4558 if (pid == 0) {
4559 int open_max = sysconf (_SC_OPEN_MAX), i;
4560 for (i = 0; i < open_max; i++)
4561 if (i != STDIN_FILENO &&
4562 i != STDOUT_FILENO &&
4563 i != STDERR_FILENO &&
4564 i != fd)
4565 close(i);
4567 parg = args;
4568 *parg++ = (char *)setup_script;
4569 *parg++ = (char *)ifname;
4570 *parg++ = NULL;
4571 execv(setup_script, args);
4572 _exit(1);
4574 while (waitpid(pid, &status, 0) != pid);
4575 if (!WIFEXITED(status) ||
4576 WEXITSTATUS(status) != 0) {
4577 fprintf(stderr, "%s: could not launch network script\n",
4578 setup_script);
4579 return -1;
4582 return 0;
4585 static int net_tap_init(VLANState *vlan, const char *ifname1,
4586 const char *setup_script, const char *down_script)
4588 TAPState *s;
4589 int fd;
4590 char ifname[128];
4592 if (ifname1 != NULL)
4593 pstrcpy(ifname, sizeof(ifname), ifname1);
4594 else
4595 ifname[0] = '\0';
4596 TFR(fd = tap_open(ifname, sizeof(ifname)));
4597 if (fd < 0)
4598 return -1;
4600 if (!setup_script || !strcmp(setup_script, "no"))
4601 setup_script = "";
4602 if (setup_script[0] != '\0') {
4603 if (launch_script(setup_script, ifname, fd))
4604 return -1;
4606 s = net_tap_fd_init(vlan, fd);
4607 if (!s)
4608 return -1;
4609 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4610 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4611 if (down_script && strcmp(down_script, "no"))
4612 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4613 return 0;
4616 #endif /* !_WIN32 */
4618 #if defined(CONFIG_VDE)
4619 typedef struct VDEState {
4620 VLANClientState *vc;
4621 VDECONN *vde;
4622 } VDEState;
4624 static void vde_to_qemu(void *opaque)
4626 VDEState *s = opaque;
4627 uint8_t buf[4096];
4628 int size;
4630 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4631 if (size > 0) {
4632 qemu_send_packet(s->vc, buf, size);
4636 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4638 VDEState *s = opaque;
4639 int ret;
4640 for(;;) {
4641 ret = vde_send(s->vde, buf, size, 0);
4642 if (ret < 0 && errno == EINTR) {
4643 } else {
4644 break;
4649 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4650 const char *group, int mode)
4652 VDEState *s;
4653 char *init_group = strlen(group) ? (char *)group : NULL;
4654 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4656 struct vde_open_args args = {
4657 .port = port,
4658 .group = init_group,
4659 .mode = mode,
4662 s = qemu_mallocz(sizeof(VDEState));
4663 if (!s)
4664 return -1;
4665 s->vde = vde_open(init_sock, "QEMU", &args);
4666 if (!s->vde){
4667 free(s);
4668 return -1;
4670 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4671 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4672 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4673 sock, vde_datafd(s->vde));
4674 return 0;
4676 #endif
4678 /* network connection */
4679 typedef struct NetSocketState {
4680 VLANClientState *vc;
4681 int fd;
4682 int state; /* 0 = getting length, 1 = getting data */
4683 int index;
4684 int packet_len;
4685 uint8_t buf[4096];
4686 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4687 } NetSocketState;
4689 typedef struct NetSocketListenState {
4690 VLANState *vlan;
4691 int fd;
4692 } NetSocketListenState;
4694 /* XXX: we consider we can send the whole packet without blocking */
4695 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4697 NetSocketState *s = opaque;
4698 uint32_t len;
4699 len = htonl(size);
4701 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4702 send_all(s->fd, buf, size);
4705 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4707 NetSocketState *s = opaque;
4708 sendto(s->fd, buf, size, 0,
4709 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4712 static void net_socket_send(void *opaque)
4714 NetSocketState *s = opaque;
4715 int l, size, err;
4716 uint8_t buf1[4096];
4717 const uint8_t *buf;
4719 size = recv(s->fd, buf1, sizeof(buf1), 0);
4720 if (size < 0) {
4721 err = socket_error();
4722 if (err != EWOULDBLOCK)
4723 goto eoc;
4724 } else if (size == 0) {
4725 /* end of connection */
4726 eoc:
4727 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4728 closesocket(s->fd);
4729 return;
4731 buf = buf1;
4732 while (size > 0) {
4733 /* reassemble a packet from the network */
4734 switch(s->state) {
4735 case 0:
4736 l = 4 - s->index;
4737 if (l > size)
4738 l = size;
4739 memcpy(s->buf + s->index, buf, l);
4740 buf += l;
4741 size -= l;
4742 s->index += l;
4743 if (s->index == 4) {
4744 /* got length */
4745 s->packet_len = ntohl(*(uint32_t *)s->buf);
4746 s->index = 0;
4747 s->state = 1;
4749 break;
4750 case 1:
4751 l = s->packet_len - s->index;
4752 if (l > size)
4753 l = size;
4754 memcpy(s->buf + s->index, buf, l);
4755 s->index += l;
4756 buf += l;
4757 size -= l;
4758 if (s->index >= s->packet_len) {
4759 qemu_send_packet(s->vc, s->buf, s->packet_len);
4760 s->index = 0;
4761 s->state = 0;
4763 break;
4768 static void net_socket_send_dgram(void *opaque)
4770 NetSocketState *s = opaque;
4771 int size;
4773 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4774 if (size < 0)
4775 return;
4776 if (size == 0) {
4777 /* end of connection */
4778 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4779 return;
4781 qemu_send_packet(s->vc, s->buf, size);
4784 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4786 struct ip_mreq imr;
4787 int fd;
4788 int val, ret;
4789 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4790 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4791 inet_ntoa(mcastaddr->sin_addr),
4792 (int)ntohl(mcastaddr->sin_addr.s_addr));
4793 return -1;
4796 fd = socket(PF_INET, SOCK_DGRAM, 0);
4797 if (fd < 0) {
4798 perror("socket(PF_INET, SOCK_DGRAM)");
4799 return -1;
4802 val = 1;
4803 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4804 (const char *)&val, sizeof(val));
4805 if (ret < 0) {
4806 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4807 goto fail;
4810 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4811 if (ret < 0) {
4812 perror("bind");
4813 goto fail;
4816 /* Add host to multicast group */
4817 imr.imr_multiaddr = mcastaddr->sin_addr;
4818 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4820 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4821 (const char *)&imr, sizeof(struct ip_mreq));
4822 if (ret < 0) {
4823 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4824 goto fail;
4827 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4828 val = 1;
4829 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4830 (const char *)&val, sizeof(val));
4831 if (ret < 0) {
4832 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4833 goto fail;
4836 socket_set_nonblock(fd);
4837 return fd;
4838 fail:
4839 if (fd >= 0)
4840 closesocket(fd);
4841 return -1;
4844 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4845 int is_connected)
4847 struct sockaddr_in saddr;
4848 int newfd;
4849 socklen_t saddr_len;
4850 NetSocketState *s;
4852 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4853 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4854 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4857 if (is_connected) {
4858 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4859 /* must be bound */
4860 if (saddr.sin_addr.s_addr==0) {
4861 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4862 fd);
4863 return NULL;
4865 /* clone dgram socket */
4866 newfd = net_socket_mcast_create(&saddr);
4867 if (newfd < 0) {
4868 /* error already reported by net_socket_mcast_create() */
4869 close(fd);
4870 return NULL;
4872 /* clone newfd to fd, close newfd */
4873 dup2(newfd, fd);
4874 close(newfd);
4876 } else {
4877 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4878 fd, strerror(errno));
4879 return NULL;
4883 s = qemu_mallocz(sizeof(NetSocketState));
4884 if (!s)
4885 return NULL;
4886 s->fd = fd;
4888 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4889 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4891 /* mcast: save bound address as dst */
4892 if (is_connected) s->dgram_dst=saddr;
4894 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4895 "socket: fd=%d (%s mcast=%s:%d)",
4896 fd, is_connected? "cloned" : "",
4897 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4898 return s;
4901 static void net_socket_connect(void *opaque)
4903 NetSocketState *s = opaque;
4904 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4907 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4908 int is_connected)
4910 NetSocketState *s;
4911 s = qemu_mallocz(sizeof(NetSocketState));
4912 if (!s)
4913 return NULL;
4914 s->fd = fd;
4915 s->vc = qemu_new_vlan_client(vlan,
4916 net_socket_receive, NULL, s);
4917 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4918 "socket: fd=%d", fd);
4919 if (is_connected) {
4920 net_socket_connect(s);
4921 } else {
4922 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4924 return s;
4927 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4928 int is_connected)
4930 int so_type=-1, optlen=sizeof(so_type);
4932 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4933 (socklen_t *)&optlen)< 0) {
4934 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4935 return NULL;
4937 switch(so_type) {
4938 case SOCK_DGRAM:
4939 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4940 case SOCK_STREAM:
4941 return net_socket_fd_init_stream(vlan, fd, is_connected);
4942 default:
4943 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4944 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4945 return net_socket_fd_init_stream(vlan, fd, is_connected);
4947 return NULL;
4950 static void net_socket_accept(void *opaque)
4952 NetSocketListenState *s = opaque;
4953 NetSocketState *s1;
4954 struct sockaddr_in saddr;
4955 socklen_t len;
4956 int fd;
4958 for(;;) {
4959 len = sizeof(saddr);
4960 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4961 if (fd < 0 && errno != EINTR) {
4962 return;
4963 } else if (fd >= 0) {
4964 break;
4967 s1 = net_socket_fd_init(s->vlan, fd, 1);
4968 if (!s1) {
4969 closesocket(fd);
4970 } else {
4971 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4972 "socket: connection from %s:%d",
4973 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4977 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4979 NetSocketListenState *s;
4980 int fd, val, ret;
4981 struct sockaddr_in saddr;
4983 if (parse_host_port(&saddr, host_str) < 0)
4984 return -1;
4986 s = qemu_mallocz(sizeof(NetSocketListenState));
4987 if (!s)
4988 return -1;
4990 fd = socket(PF_INET, SOCK_STREAM, 0);
4991 if (fd < 0) {
4992 perror("socket");
4993 return -1;
4995 socket_set_nonblock(fd);
4997 /* allow fast reuse */
4998 val = 1;
4999 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5001 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5002 if (ret < 0) {
5003 perror("bind");
5004 return -1;
5006 ret = listen(fd, 0);
5007 if (ret < 0) {
5008 perror("listen");
5009 return -1;
5011 s->vlan = vlan;
5012 s->fd = fd;
5013 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5014 return 0;
5017 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5019 NetSocketState *s;
5020 int fd, connected, ret, err;
5021 struct sockaddr_in saddr;
5023 if (parse_host_port(&saddr, host_str) < 0)
5024 return -1;
5026 fd = socket(PF_INET, SOCK_STREAM, 0);
5027 if (fd < 0) {
5028 perror("socket");
5029 return -1;
5031 socket_set_nonblock(fd);
5033 connected = 0;
5034 for(;;) {
5035 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5036 if (ret < 0) {
5037 err = socket_error();
5038 if (err == EINTR || err == EWOULDBLOCK) {
5039 } else if (err == EINPROGRESS) {
5040 break;
5041 #ifdef _WIN32
5042 } else if (err == WSAEALREADY) {
5043 break;
5044 #endif
5045 } else {
5046 perror("connect");
5047 closesocket(fd);
5048 return -1;
5050 } else {
5051 connected = 1;
5052 break;
5055 s = net_socket_fd_init(vlan, fd, connected);
5056 if (!s)
5057 return -1;
5058 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5059 "socket: connect to %s:%d",
5060 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5061 return 0;
5064 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5066 NetSocketState *s;
5067 int fd;
5068 struct sockaddr_in saddr;
5070 if (parse_host_port(&saddr, host_str) < 0)
5071 return -1;
5074 fd = net_socket_mcast_create(&saddr);
5075 if (fd < 0)
5076 return -1;
5078 s = net_socket_fd_init(vlan, fd, 0);
5079 if (!s)
5080 return -1;
5082 s->dgram_dst = saddr;
5084 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5085 "socket: mcast=%s:%d",
5086 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5087 return 0;
5091 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5093 char *q;
5095 q = buf;
5096 while (*p != '\0' && *p != '=') {
5097 if (q && (q - buf) < buf_size - 1)
5098 *q++ = *p;
5099 p++;
5101 if (q)
5102 *q = '\0';
5104 return p;
5107 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5109 char *q;
5111 q = buf;
5112 while (*p != '\0') {
5113 if (*p == ',') {
5114 if (*(p + 1) != ',')
5115 break;
5116 p++;
5118 if (q && (q - buf) < buf_size - 1)
5119 *q++ = *p;
5120 p++;
5122 if (q)
5123 *q = '\0';
5125 return p;
5128 static int get_param_value(char *buf, int buf_size,
5129 const char *tag, const char *str)
5131 const char *p;
5132 char option[128];
5134 p = str;
5135 for(;;) {
5136 p = get_opt_name(option, sizeof(option), p);
5137 if (*p != '=')
5138 break;
5139 p++;
5140 if (!strcmp(tag, option)) {
5141 (void)get_opt_value(buf, buf_size, p);
5142 return strlen(buf);
5143 } else {
5144 p = get_opt_value(NULL, 0, p);
5146 if (*p != ',')
5147 break;
5148 p++;
5150 return 0;
5153 static int check_params(char *buf, int buf_size,
5154 const char * const *params, const char *str)
5156 const char *p;
5157 int i;
5159 p = str;
5160 for(;;) {
5161 p = get_opt_name(buf, buf_size, p);
5162 if (*p != '=')
5163 return -1;
5164 p++;
5165 for(i = 0; params[i] != NULL; i++)
5166 if (!strcmp(params[i], buf))
5167 break;
5168 if (params[i] == NULL)
5169 return -1;
5170 p = get_opt_value(NULL, 0, p);
5171 if (*p != ',')
5172 break;
5173 p++;
5175 return 0;
5178 static int net_client_init(const char *device, const char *p)
5180 char buf[1024];
5181 int vlan_id, ret;
5182 VLANState *vlan;
5184 vlan_id = 0;
5185 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5186 vlan_id = strtol(buf, NULL, 0);
5188 vlan = qemu_find_vlan(vlan_id);
5189 if (!vlan) {
5190 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5191 return -1;
5193 if (!strcmp(device, "nic")) {
5194 NICInfo *nd;
5195 uint8_t *macaddr;
5197 if (nb_nics >= MAX_NICS) {
5198 fprintf(stderr, "Too Many NICs\n");
5199 return -1;
5201 nd = &nd_table[nb_nics];
5202 macaddr = nd->macaddr;
5203 macaddr[0] = 0x52;
5204 macaddr[1] = 0x54;
5205 macaddr[2] = 0x00;
5206 macaddr[3] = 0x12;
5207 macaddr[4] = 0x34;
5208 macaddr[5] = 0x56 + nb_nics;
5210 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5211 if (parse_macaddr(macaddr, buf) < 0) {
5212 fprintf(stderr, "invalid syntax for ethernet address\n");
5213 return -1;
5216 if (get_param_value(buf, sizeof(buf), "model", p)) {
5217 nd->model = strdup(buf);
5219 nd->vlan = vlan;
5220 nb_nics++;
5221 vlan->nb_guest_devs++;
5222 ret = 0;
5223 } else
5224 if (!strcmp(device, "none")) {
5225 /* does nothing. It is needed to signal that no network cards
5226 are wanted */
5227 ret = 0;
5228 } else
5229 #ifdef CONFIG_SLIRP
5230 if (!strcmp(device, "user")) {
5231 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5232 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5234 vlan->nb_host_devs++;
5235 ret = net_slirp_init(vlan);
5236 } else
5237 #endif
5238 #ifdef _WIN32
5239 if (!strcmp(device, "tap")) {
5240 char ifname[64];
5241 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5242 fprintf(stderr, "tap: no interface name\n");
5243 return -1;
5245 vlan->nb_host_devs++;
5246 ret = tap_win32_init(vlan, ifname);
5247 } else
5248 #else
5249 if (!strcmp(device, "tap")) {
5250 char ifname[64];
5251 char setup_script[1024], down_script[1024];
5252 int fd;
5253 vlan->nb_host_devs++;
5254 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5255 fd = strtol(buf, NULL, 0);
5256 fcntl(fd, F_SETFL, O_NONBLOCK);
5257 ret = -1;
5258 if (net_tap_fd_init(vlan, fd))
5259 ret = 0;
5260 } else {
5261 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5262 ifname[0] = '\0';
5264 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5265 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5267 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5268 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5270 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5272 } else
5273 #endif
5274 if (!strcmp(device, "socket")) {
5275 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5276 int fd;
5277 fd = strtol(buf, NULL, 0);
5278 ret = -1;
5279 if (net_socket_fd_init(vlan, fd, 1))
5280 ret = 0;
5281 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5282 ret = net_socket_listen_init(vlan, buf);
5283 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5284 ret = net_socket_connect_init(vlan, buf);
5285 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5286 ret = net_socket_mcast_init(vlan, buf);
5287 } else {
5288 fprintf(stderr, "Unknown socket options: %s\n", p);
5289 return -1;
5291 vlan->nb_host_devs++;
5292 } else
5293 #ifdef CONFIG_VDE
5294 if (!strcmp(device, "vde")) {
5295 char vde_sock[1024], vde_group[512];
5296 int vde_port, vde_mode;
5297 vlan->nb_host_devs++;
5298 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5299 vde_sock[0] = '\0';
5301 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5302 vde_port = strtol(buf, NULL, 10);
5303 } else {
5304 vde_port = 0;
5306 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5307 vde_group[0] = '\0';
5309 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5310 vde_mode = strtol(buf, NULL, 8);
5311 } else {
5312 vde_mode = 0700;
5314 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5315 } else
5316 #endif
5318 fprintf(stderr, "Unknown network device: %s\n", device);
5319 return -1;
5321 if (ret < 0) {
5322 fprintf(stderr, "Could not initialize device '%s'\n", device);
5325 return ret;
5328 static int net_client_parse(const char *str)
5330 const char *p;
5331 char *q;
5332 char device[64];
5334 p = str;
5335 q = device;
5336 while (*p != '\0' && *p != ',') {
5337 if ((q - device) < sizeof(device) - 1)
5338 *q++ = *p;
5339 p++;
5341 *q = '\0';
5342 if (*p == ',')
5343 p++;
5345 return net_client_init(device, p);
5348 void do_info_network(void)
5350 VLANState *vlan;
5351 VLANClientState *vc;
5353 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5354 term_printf("VLAN %d devices:\n", vlan->id);
5355 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5356 term_printf(" %s\n", vc->info_str);
5360 /***********************************************************/
5361 /* Bluetooth support */
5362 static int nb_hcis;
5363 static int cur_hci;
5364 static struct HCIInfo *hci_table[MAX_NICS];
5365 static struct bt_vlan_s {
5366 struct bt_scatternet_s net;
5367 int id;
5368 struct bt_vlan_s *next;
5369 } *first_bt_vlan;
5371 /* find or alloc a new bluetooth "VLAN" */
5372 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
5374 struct bt_vlan_s **pvlan, *vlan;
5375 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
5376 if (vlan->id == id)
5377 return &vlan->net;
5379 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
5380 vlan->id = id;
5381 pvlan = &first_bt_vlan;
5382 while (*pvlan != NULL)
5383 pvlan = &(*pvlan)->next;
5384 *pvlan = vlan;
5385 return &vlan->net;
5388 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
5392 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
5394 return -ENOTSUP;
5397 static struct HCIInfo null_hci = {
5398 .cmd_send = null_hci_send,
5399 .sco_send = null_hci_send,
5400 .acl_send = null_hci_send,
5401 .bdaddr_set = null_hci_addr_set,
5404 struct HCIInfo *qemu_next_hci(void)
5406 if (cur_hci == nb_hcis)
5407 return &null_hci;
5409 return hci_table[cur_hci++];
5412 /***********************************************************/
5413 /* QEMU Block devices */
5415 #define HD_ALIAS "index=%d,media=disk"
5416 #ifdef TARGET_PPC
5417 #define CDROM_ALIAS "index=1,media=cdrom"
5418 #else
5419 #define CDROM_ALIAS "index=2,media=cdrom"
5420 #endif
5421 #define FD_ALIAS "index=%d,if=floppy"
5422 #define PFLASH_ALIAS "if=pflash"
5423 #define MTD_ALIAS "if=mtd"
5424 #define SD_ALIAS "index=0,if=sd"
5426 static int drive_add(const char *file, const char *fmt, ...)
5428 va_list ap;
5430 if (nb_drives_opt >= MAX_DRIVES) {
5431 fprintf(stderr, "qemu: too many drives\n");
5432 exit(1);
5435 drives_opt[nb_drives_opt].file = file;
5436 va_start(ap, fmt);
5437 vsnprintf(drives_opt[nb_drives_opt].opt,
5438 sizeof(drives_opt[0].opt), fmt, ap);
5439 va_end(ap);
5441 return nb_drives_opt++;
5444 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5446 int index;
5448 /* seek interface, bus and unit */
5450 for (index = 0; index < nb_drives; index++)
5451 if (drives_table[index].type == type &&
5452 drives_table[index].bus == bus &&
5453 drives_table[index].unit == unit)
5454 return index;
5456 return -1;
5459 int drive_get_max_bus(BlockInterfaceType type)
5461 int max_bus;
5462 int index;
5464 max_bus = -1;
5465 for (index = 0; index < nb_drives; index++) {
5466 if(drives_table[index].type == type &&
5467 drives_table[index].bus > max_bus)
5468 max_bus = drives_table[index].bus;
5470 return max_bus;
5473 static void bdrv_format_print(void *opaque, const char *name)
5475 fprintf(stderr, " %s", name);
5478 static int drive_init(struct drive_opt *arg, int snapshot,
5479 QEMUMachine *machine)
5481 char buf[128];
5482 char file[1024];
5483 char devname[128];
5484 const char *mediastr = "";
5485 BlockInterfaceType type;
5486 enum { MEDIA_DISK, MEDIA_CDROM } media;
5487 int bus_id, unit_id;
5488 int cyls, heads, secs, translation;
5489 BlockDriverState *bdrv;
5490 BlockDriver *drv = NULL;
5491 int max_devs;
5492 int index;
5493 int cache;
5494 int bdrv_flags;
5495 char *str = arg->opt;
5496 static const char * const params[] = { "bus", "unit", "if", "index",
5497 "cyls", "heads", "secs", "trans",
5498 "media", "snapshot", "file",
5499 "cache", "format", NULL };
5501 if (check_params(buf, sizeof(buf), params, str) < 0) {
5502 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5503 buf, str);
5504 return -1;
5507 file[0] = 0;
5508 cyls = heads = secs = 0;
5509 bus_id = 0;
5510 unit_id = -1;
5511 translation = BIOS_ATA_TRANSLATION_AUTO;
5512 index = -1;
5513 cache = 1;
5515 if (machine->use_scsi) {
5516 type = IF_SCSI;
5517 max_devs = MAX_SCSI_DEVS;
5518 pstrcpy(devname, sizeof(devname), "scsi");
5519 } else {
5520 type = IF_IDE;
5521 max_devs = MAX_IDE_DEVS;
5522 pstrcpy(devname, sizeof(devname), "ide");
5524 media = MEDIA_DISK;
5526 /* extract parameters */
5528 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5529 bus_id = strtol(buf, NULL, 0);
5530 if (bus_id < 0) {
5531 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5532 return -1;
5536 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5537 unit_id = strtol(buf, NULL, 0);
5538 if (unit_id < 0) {
5539 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5540 return -1;
5544 if (get_param_value(buf, sizeof(buf), "if", str)) {
5545 pstrcpy(devname, sizeof(devname), buf);
5546 if (!strcmp(buf, "ide")) {
5547 type = IF_IDE;
5548 max_devs = MAX_IDE_DEVS;
5549 } else if (!strcmp(buf, "scsi")) {
5550 type = IF_SCSI;
5551 max_devs = MAX_SCSI_DEVS;
5552 } else if (!strcmp(buf, "floppy")) {
5553 type = IF_FLOPPY;
5554 max_devs = 0;
5555 } else if (!strcmp(buf, "pflash")) {
5556 type = IF_PFLASH;
5557 max_devs = 0;
5558 } else if (!strcmp(buf, "mtd")) {
5559 type = IF_MTD;
5560 max_devs = 0;
5561 } else if (!strcmp(buf, "sd")) {
5562 type = IF_SD;
5563 max_devs = 0;
5564 } else {
5565 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5566 return -1;
5570 if (get_param_value(buf, sizeof(buf), "index", str)) {
5571 index = strtol(buf, NULL, 0);
5572 if (index < 0) {
5573 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5574 return -1;
5578 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5579 cyls = strtol(buf, NULL, 0);
5582 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5583 heads = strtol(buf, NULL, 0);
5586 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5587 secs = strtol(buf, NULL, 0);
5590 if (cyls || heads || secs) {
5591 if (cyls < 1 || cyls > 16383) {
5592 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5593 return -1;
5595 if (heads < 1 || heads > 16) {
5596 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5597 return -1;
5599 if (secs < 1 || secs > 63) {
5600 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5601 return -1;
5605 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5606 if (!cyls) {
5607 fprintf(stderr,
5608 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5609 str);
5610 return -1;
5612 if (!strcmp(buf, "none"))
5613 translation = BIOS_ATA_TRANSLATION_NONE;
5614 else if (!strcmp(buf, "lba"))
5615 translation = BIOS_ATA_TRANSLATION_LBA;
5616 else if (!strcmp(buf, "auto"))
5617 translation = BIOS_ATA_TRANSLATION_AUTO;
5618 else {
5619 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5620 return -1;
5624 if (get_param_value(buf, sizeof(buf), "media", str)) {
5625 if (!strcmp(buf, "disk")) {
5626 media = MEDIA_DISK;
5627 } else if (!strcmp(buf, "cdrom")) {
5628 if (cyls || secs || heads) {
5629 fprintf(stderr,
5630 "qemu: '%s' invalid physical CHS format\n", str);
5631 return -1;
5633 media = MEDIA_CDROM;
5634 } else {
5635 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5636 return -1;
5640 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5641 if (!strcmp(buf, "on"))
5642 snapshot = 1;
5643 else if (!strcmp(buf, "off"))
5644 snapshot = 0;
5645 else {
5646 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5647 return -1;
5651 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5652 if (!strcmp(buf, "off"))
5653 cache = 0;
5654 else if (!strcmp(buf, "on"))
5655 cache = 1;
5656 else {
5657 fprintf(stderr, "qemu: invalid cache option\n");
5658 return -1;
5662 if (get_param_value(buf, sizeof(buf), "format", str)) {
5663 if (strcmp(buf, "?") == 0) {
5664 fprintf(stderr, "qemu: Supported formats:");
5665 bdrv_iterate_format(bdrv_format_print, NULL);
5666 fprintf(stderr, "\n");
5667 return -1;
5669 drv = bdrv_find_format(buf);
5670 if (!drv) {
5671 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5672 return -1;
5676 if (arg->file == NULL)
5677 get_param_value(file, sizeof(file), "file", str);
5678 else
5679 pstrcpy(file, sizeof(file), arg->file);
5681 /* compute bus and unit according index */
5683 if (index != -1) {
5684 if (bus_id != 0 || unit_id != -1) {
5685 fprintf(stderr,
5686 "qemu: '%s' index cannot be used with bus and unit\n", str);
5687 return -1;
5689 if (max_devs == 0)
5691 unit_id = index;
5692 bus_id = 0;
5693 } else {
5694 unit_id = index % max_devs;
5695 bus_id = index / max_devs;
5699 /* if user doesn't specify a unit_id,
5700 * try to find the first free
5703 if (unit_id == -1) {
5704 unit_id = 0;
5705 while (drive_get_index(type, bus_id, unit_id) != -1) {
5706 unit_id++;
5707 if (max_devs && unit_id >= max_devs) {
5708 unit_id -= max_devs;
5709 bus_id++;
5714 /* check unit id */
5716 if (max_devs && unit_id >= max_devs) {
5717 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5718 str, unit_id, max_devs - 1);
5719 return -1;
5723 * ignore multiple definitions
5726 if (drive_get_index(type, bus_id, unit_id) != -1)
5727 return 0;
5729 /* init */
5731 if (type == IF_IDE || type == IF_SCSI)
5732 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5733 if (max_devs)
5734 snprintf(buf, sizeof(buf), "%s%i%s%i",
5735 devname, bus_id, mediastr, unit_id);
5736 else
5737 snprintf(buf, sizeof(buf), "%s%s%i",
5738 devname, mediastr, unit_id);
5739 bdrv = bdrv_new(buf);
5740 drives_table[nb_drives].bdrv = bdrv;
5741 drives_table[nb_drives].type = type;
5742 drives_table[nb_drives].bus = bus_id;
5743 drives_table[nb_drives].unit = unit_id;
5744 nb_drives++;
5746 switch(type) {
5747 case IF_IDE:
5748 case IF_SCSI:
5749 switch(media) {
5750 case MEDIA_DISK:
5751 if (cyls != 0) {
5752 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5753 bdrv_set_translation_hint(bdrv, translation);
5755 break;
5756 case MEDIA_CDROM:
5757 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5758 break;
5760 break;
5761 case IF_SD:
5762 /* FIXME: This isn't really a floppy, but it's a reasonable
5763 approximation. */
5764 case IF_FLOPPY:
5765 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5766 break;
5767 case IF_PFLASH:
5768 case IF_MTD:
5769 break;
5771 if (!file[0])
5772 return 0;
5773 bdrv_flags = 0;
5774 if (snapshot)
5775 bdrv_flags |= BDRV_O_SNAPSHOT;
5776 if (!cache)
5777 bdrv_flags |= BDRV_O_DIRECT;
5778 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5779 fprintf(stderr, "qemu: could not open disk image %s\n",
5780 file);
5781 return -1;
5783 return 0;
5786 /***********************************************************/
5787 /* USB devices */
5789 static USBPort *used_usb_ports;
5790 static USBPort *free_usb_ports;
5792 /* ??? Maybe change this to register a hub to keep track of the topology. */
5793 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5794 usb_attachfn attach)
5796 port->opaque = opaque;
5797 port->index = index;
5798 port->attach = attach;
5799 port->next = free_usb_ports;
5800 free_usb_ports = port;
5803 int usb_device_add_dev(USBDevice *dev)
5805 USBPort *port;
5807 /* Find a USB port to add the device to. */
5808 port = free_usb_ports;
5809 if (!port->next) {
5810 USBDevice *hub;
5812 /* Create a new hub and chain it on. */
5813 free_usb_ports = NULL;
5814 port->next = used_usb_ports;
5815 used_usb_ports = port;
5817 hub = usb_hub_init(VM_USB_HUB_SIZE);
5818 usb_attach(port, hub);
5819 port = free_usb_ports;
5822 free_usb_ports = port->next;
5823 port->next = used_usb_ports;
5824 used_usb_ports = port;
5825 usb_attach(port, dev);
5826 return 0;
5829 static int usb_device_add(const char *devname)
5831 const char *p;
5832 USBDevice *dev;
5834 if (!free_usb_ports)
5835 return -1;
5837 if (strstart(devname, "host:", &p)) {
5838 dev = usb_host_device_open(p);
5839 } else if (!strcmp(devname, "mouse")) {
5840 dev = usb_mouse_init();
5841 } else if (!strcmp(devname, "tablet")) {
5842 dev = usb_tablet_init();
5843 } else if (!strcmp(devname, "keyboard")) {
5844 dev = usb_keyboard_init();
5845 } else if (strstart(devname, "disk:", &p)) {
5846 dev = usb_msd_init(p);
5847 } else if (!strcmp(devname, "wacom-tablet")) {
5848 dev = usb_wacom_init();
5849 } else if (strstart(devname, "serial:", &p)) {
5850 dev = usb_serial_init(p);
5851 #ifdef CONFIG_BRLAPI
5852 } else if (!strcmp(devname, "braille")) {
5853 dev = usb_baum_init();
5854 #endif
5855 } else if (strstart(devname, "net:", &p)) {
5856 int nic = nb_nics;
5858 if (net_client_init("nic", p) < 0)
5859 return -1;
5860 nd_table[nic].model = "usb";
5861 dev = usb_net_init(&nd_table[nic]);
5862 } else {
5863 return -1;
5865 if (!dev)
5866 return -1;
5868 return usb_device_add_dev(dev);
5871 int usb_device_del_addr(int bus_num, int addr)
5873 USBPort *port;
5874 USBPort **lastp;
5875 USBDevice *dev;
5877 if (!used_usb_ports)
5878 return -1;
5880 if (bus_num != 0)
5881 return -1;
5883 lastp = &used_usb_ports;
5884 port = used_usb_ports;
5885 while (port && port->dev->addr != addr) {
5886 lastp = &port->next;
5887 port = port->next;
5890 if (!port)
5891 return -1;
5893 dev = port->dev;
5894 *lastp = port->next;
5895 usb_attach(port, NULL);
5896 dev->handle_destroy(dev);
5897 port->next = free_usb_ports;
5898 free_usb_ports = port;
5899 return 0;
5902 static int usb_device_del(const char *devname)
5904 int bus_num, addr;
5905 const char *p;
5907 if (strstart(devname, "host:", &p))
5908 return usb_host_device_close(p);
5910 if (!used_usb_ports)
5911 return -1;
5913 p = strchr(devname, '.');
5914 if (!p)
5915 return -1;
5916 bus_num = strtoul(devname, NULL, 0);
5917 addr = strtoul(p + 1, NULL, 0);
5919 return usb_device_del_addr(bus_num, addr);
5922 void do_usb_add(const char *devname)
5924 usb_device_add(devname);
5927 void do_usb_del(const char *devname)
5929 usb_device_del(devname);
5932 void usb_info(void)
5934 USBDevice *dev;
5935 USBPort *port;
5936 const char *speed_str;
5938 if (!usb_enabled) {
5939 term_printf("USB support not enabled\n");
5940 return;
5943 for (port = used_usb_ports; port; port = port->next) {
5944 dev = port->dev;
5945 if (!dev)
5946 continue;
5947 switch(dev->speed) {
5948 case USB_SPEED_LOW:
5949 speed_str = "1.5";
5950 break;
5951 case USB_SPEED_FULL:
5952 speed_str = "12";
5953 break;
5954 case USB_SPEED_HIGH:
5955 speed_str = "480";
5956 break;
5957 default:
5958 speed_str = "?";
5959 break;
5961 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5962 0, dev->addr, speed_str, dev->devname);
5966 /***********************************************************/
5967 /* PCMCIA/Cardbus */
5969 static struct pcmcia_socket_entry_s {
5970 struct pcmcia_socket_s *socket;
5971 struct pcmcia_socket_entry_s *next;
5972 } *pcmcia_sockets = 0;
5974 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5976 struct pcmcia_socket_entry_s *entry;
5978 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5979 entry->socket = socket;
5980 entry->next = pcmcia_sockets;
5981 pcmcia_sockets = entry;
5984 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5986 struct pcmcia_socket_entry_s *entry, **ptr;
5988 ptr = &pcmcia_sockets;
5989 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5990 if (entry->socket == socket) {
5991 *ptr = entry->next;
5992 qemu_free(entry);
5996 void pcmcia_info(void)
5998 struct pcmcia_socket_entry_s *iter;
5999 if (!pcmcia_sockets)
6000 term_printf("No PCMCIA sockets\n");
6002 for (iter = pcmcia_sockets; iter; iter = iter->next)
6003 term_printf("%s: %s\n", iter->socket->slot_string,
6004 iter->socket->attached ? iter->socket->card_string :
6005 "Empty");
6008 /***********************************************************/
6009 /* dumb display */
6011 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6015 static void dumb_resize(DisplayState *ds, int w, int h)
6019 static void dumb_refresh(DisplayState *ds)
6021 #if defined(CONFIG_SDL)
6022 vga_hw_update();
6023 #endif
6026 static void dumb_display_init(DisplayState *ds)
6028 ds->data = NULL;
6029 ds->linesize = 0;
6030 ds->depth = 0;
6031 ds->dpy_update = dumb_update;
6032 ds->dpy_resize = dumb_resize;
6033 ds->dpy_refresh = dumb_refresh;
6034 ds->gui_timer_interval = 500;
6035 ds->idle = 1;
6038 /***********************************************************/
6039 /* I/O handling */
6041 #define MAX_IO_HANDLERS 64
6043 typedef struct IOHandlerRecord {
6044 int fd;
6045 IOCanRWHandler *fd_read_poll;
6046 IOHandler *fd_read;
6047 IOHandler *fd_write;
6048 int deleted;
6049 void *opaque;
6050 /* temporary data */
6051 struct pollfd *ufd;
6052 struct IOHandlerRecord *next;
6053 } IOHandlerRecord;
6055 static IOHandlerRecord *first_io_handler;
6057 /* XXX: fd_read_poll should be suppressed, but an API change is
6058 necessary in the character devices to suppress fd_can_read(). */
6059 int qemu_set_fd_handler2(int fd,
6060 IOCanRWHandler *fd_read_poll,
6061 IOHandler *fd_read,
6062 IOHandler *fd_write,
6063 void *opaque)
6065 IOHandlerRecord **pioh, *ioh;
6067 if (!fd_read && !fd_write) {
6068 pioh = &first_io_handler;
6069 for(;;) {
6070 ioh = *pioh;
6071 if (ioh == NULL)
6072 break;
6073 if (ioh->fd == fd) {
6074 ioh->deleted = 1;
6075 break;
6077 pioh = &ioh->next;
6079 } else {
6080 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6081 if (ioh->fd == fd)
6082 goto found;
6084 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6085 if (!ioh)
6086 return -1;
6087 ioh->next = first_io_handler;
6088 first_io_handler = ioh;
6089 found:
6090 ioh->fd = fd;
6091 ioh->fd_read_poll = fd_read_poll;
6092 ioh->fd_read = fd_read;
6093 ioh->fd_write = fd_write;
6094 ioh->opaque = opaque;
6095 ioh->deleted = 0;
6097 return 0;
6100 int qemu_set_fd_handler(int fd,
6101 IOHandler *fd_read,
6102 IOHandler *fd_write,
6103 void *opaque)
6105 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6108 /***********************************************************/
6109 /* Polling handling */
6111 typedef struct PollingEntry {
6112 PollingFunc *func;
6113 void *opaque;
6114 struct PollingEntry *next;
6115 } PollingEntry;
6117 static PollingEntry *first_polling_entry;
6119 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6121 PollingEntry **ppe, *pe;
6122 pe = qemu_mallocz(sizeof(PollingEntry));
6123 if (!pe)
6124 return -1;
6125 pe->func = func;
6126 pe->opaque = opaque;
6127 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6128 *ppe = pe;
6129 return 0;
6132 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6134 PollingEntry **ppe, *pe;
6135 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6136 pe = *ppe;
6137 if (pe->func == func && pe->opaque == opaque) {
6138 *ppe = pe->next;
6139 qemu_free(pe);
6140 break;
6145 #ifdef _WIN32
6146 /***********************************************************/
6147 /* Wait objects support */
6148 typedef struct WaitObjects {
6149 int num;
6150 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6151 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6152 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6153 } WaitObjects;
6155 static WaitObjects wait_objects = {0};
6157 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6159 WaitObjects *w = &wait_objects;
6161 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6162 return -1;
6163 w->events[w->num] = handle;
6164 w->func[w->num] = func;
6165 w->opaque[w->num] = opaque;
6166 w->num++;
6167 return 0;
6170 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6172 int i, found;
6173 WaitObjects *w = &wait_objects;
6175 found = 0;
6176 for (i = 0; i < w->num; i++) {
6177 if (w->events[i] == handle)
6178 found = 1;
6179 if (found) {
6180 w->events[i] = w->events[i + 1];
6181 w->func[i] = w->func[i + 1];
6182 w->opaque[i] = w->opaque[i + 1];
6185 if (found)
6186 w->num--;
6188 #endif
6190 /***********************************************************/
6191 /* savevm/loadvm support */
6193 #define IO_BUF_SIZE 32768
6195 struct QEMUFile {
6196 QEMUFilePutBufferFunc *put_buffer;
6197 QEMUFileGetBufferFunc *get_buffer;
6198 QEMUFileCloseFunc *close;
6199 QEMUFileRateLimit *rate_limit;
6200 void *opaque;
6202 int64_t buf_offset; /* start of buffer when writing, end of buffer
6203 when reading */
6204 int buf_index;
6205 int buf_size; /* 0 when writing */
6206 uint8_t buf[IO_BUF_SIZE];
6209 typedef struct QEMUFileFD
6211 int fd;
6212 QEMUFile *file;
6213 } QEMUFileFD;
6215 static void fd_put_notify(void *opaque)
6217 QEMUFileFD *s = opaque;
6219 /* Remove writable callback and do a put notify */
6220 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
6221 qemu_file_put_notify(s->file);
6224 static void fd_put_buffer(void *opaque, const uint8_t *buf,
6225 int64_t pos, int size)
6227 QEMUFileFD *s = opaque;
6228 ssize_t len;
6230 do {
6231 len = write(s->fd, buf, size);
6232 } while (len == -1 && errno == EINTR);
6234 if (len == -1)
6235 len = -errno;
6237 /* When the fd becomes writable again, register a callback to do
6238 * a put notify */
6239 if (len == -EAGAIN)
6240 qemu_set_fd_handler2(s->fd, NULL, NULL, fd_put_notify, s);
6243 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6245 QEMUFileFD *s = opaque;
6246 ssize_t len;
6248 do {
6249 len = read(s->fd, buf, size);
6250 } while (len == -1 && errno == EINTR);
6252 if (len == -1)
6253 len = -errno;
6255 return len;
6258 static int fd_close(void *opaque)
6260 QEMUFileFD *s = opaque;
6261 qemu_free(s);
6262 return 0;
6265 QEMUFile *qemu_fopen_fd(int fd)
6267 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6269 if (s == NULL)
6270 return NULL;
6272 s->fd = fd;
6273 s->file = qemu_fopen_ops(s, fd_put_buffer, fd_get_buffer, fd_close, NULL);
6274 return s->file;
6277 typedef struct QEMUFileStdio
6279 FILE *outfile;
6280 } QEMUFileStdio;
6282 static void file_put_buffer(void *opaque, const uint8_t *buf,
6283 int64_t pos, int size)
6285 QEMUFileStdio *s = opaque;
6286 fseek(s->outfile, pos, SEEK_SET);
6287 fwrite(buf, 1, size, s->outfile);
6290 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6292 QEMUFileStdio *s = opaque;
6293 fseek(s->outfile, pos, SEEK_SET);
6294 return fread(buf, 1, size, s->outfile);
6297 static int file_close(void *opaque)
6299 QEMUFileStdio *s = opaque;
6300 fclose(s->outfile);
6301 qemu_free(s);
6302 return 0;
6305 QEMUFile *qemu_fopen(const char *filename, const char *mode)
6307 QEMUFileStdio *s;
6309 s = qemu_mallocz(sizeof(QEMUFileStdio));
6310 if (!s)
6311 return NULL;
6313 s->outfile = fopen(filename, mode);
6314 if (!s->outfile)
6315 goto fail;
6317 if (!strcmp(mode, "wb"))
6318 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
6319 else if (!strcmp(mode, "rb"))
6320 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
6322 fail:
6323 if (s->outfile)
6324 fclose(s->outfile);
6325 qemu_free(s);
6326 return NULL;
6329 typedef struct QEMUFileBdrv
6331 BlockDriverState *bs;
6332 int64_t base_offset;
6333 } QEMUFileBdrv;
6335 static void bdrv_put_buffer(void *opaque, const uint8_t *buf,
6336 int64_t pos, int size)
6338 QEMUFileBdrv *s = opaque;
6339 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6342 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6344 QEMUFileBdrv *s = opaque;
6345 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6348 static int bdrv_fclose(void *opaque)
6350 QEMUFileBdrv *s = opaque;
6351 qemu_free(s);
6352 return 0;
6355 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6357 QEMUFileBdrv *s;
6359 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6360 if (!s)
6361 return NULL;
6363 s->bs = bs;
6364 s->base_offset = offset;
6366 if (is_writable)
6367 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
6369 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
6372 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6373 QEMUFileGetBufferFunc *get_buffer,
6374 QEMUFileCloseFunc *close,
6375 QEMUFileRateLimit *rate_limit)
6377 QEMUFile *f;
6379 f = qemu_mallocz(sizeof(QEMUFile));
6380 if (!f)
6381 return NULL;
6383 f->opaque = opaque;
6384 f->put_buffer = put_buffer;
6385 f->get_buffer = get_buffer;
6386 f->close = close;
6387 f->rate_limit = rate_limit;
6389 return f;
6392 void qemu_fflush(QEMUFile *f)
6394 if (!f->put_buffer)
6395 return;
6397 if (f->buf_index > 0) {
6398 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6399 f->buf_offset += f->buf_index;
6400 f->buf_index = 0;
6404 static void qemu_fill_buffer(QEMUFile *f)
6406 int len;
6408 if (!f->get_buffer)
6409 return;
6411 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6412 if (len < 0)
6413 len = 0;
6415 f->buf_index = 0;
6416 f->buf_size = len;
6417 f->buf_offset += len;
6420 int qemu_fclose(QEMUFile *f)
6422 int ret = 0;
6423 qemu_fflush(f);
6424 if (f->close)
6425 ret = f->close(f->opaque);
6426 qemu_free(f);
6427 return ret;
6430 void qemu_file_put_notify(QEMUFile *f)
6432 f->put_buffer(f->opaque, NULL, 0, 0);
6435 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6437 int l;
6438 while (size > 0) {
6439 l = IO_BUF_SIZE - f->buf_index;
6440 if (l > size)
6441 l = size;
6442 memcpy(f->buf + f->buf_index, buf, l);
6443 f->buf_index += l;
6444 buf += l;
6445 size -= l;
6446 if (f->buf_index >= IO_BUF_SIZE)
6447 qemu_fflush(f);
6451 void qemu_put_byte(QEMUFile *f, int v)
6453 f->buf[f->buf_index++] = v;
6454 if (f->buf_index >= IO_BUF_SIZE)
6455 qemu_fflush(f);
6458 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6460 int size, l;
6462 size = size1;
6463 while (size > 0) {
6464 l = f->buf_size - f->buf_index;
6465 if (l == 0) {
6466 qemu_fill_buffer(f);
6467 l = f->buf_size - f->buf_index;
6468 if (l == 0)
6469 break;
6471 if (l > size)
6472 l = size;
6473 memcpy(buf, f->buf + f->buf_index, l);
6474 f->buf_index += l;
6475 buf += l;
6476 size -= l;
6478 return size1 - size;
6481 int qemu_get_byte(QEMUFile *f)
6483 if (f->buf_index >= f->buf_size) {
6484 qemu_fill_buffer(f);
6485 if (f->buf_index >= f->buf_size)
6486 return 0;
6488 return f->buf[f->buf_index++];
6491 int64_t qemu_ftell(QEMUFile *f)
6493 return f->buf_offset - f->buf_size + f->buf_index;
6496 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6498 if (whence == SEEK_SET) {
6499 /* nothing to do */
6500 } else if (whence == SEEK_CUR) {
6501 pos += qemu_ftell(f);
6502 } else {
6503 /* SEEK_END not supported */
6504 return -1;
6506 if (f->put_buffer) {
6507 qemu_fflush(f);
6508 f->buf_offset = pos;
6509 } else {
6510 f->buf_offset = pos;
6511 f->buf_index = 0;
6512 f->buf_size = 0;
6514 return pos;
6517 int qemu_file_rate_limit(QEMUFile *f)
6519 if (f->rate_limit)
6520 return f->rate_limit(f->opaque);
6522 return 0;
6525 void qemu_put_be16(QEMUFile *f, unsigned int v)
6527 qemu_put_byte(f, v >> 8);
6528 qemu_put_byte(f, v);
6531 void qemu_put_be32(QEMUFile *f, unsigned int v)
6533 qemu_put_byte(f, v >> 24);
6534 qemu_put_byte(f, v >> 16);
6535 qemu_put_byte(f, v >> 8);
6536 qemu_put_byte(f, v);
6539 void qemu_put_be64(QEMUFile *f, uint64_t v)
6541 qemu_put_be32(f, v >> 32);
6542 qemu_put_be32(f, v);
6545 unsigned int qemu_get_be16(QEMUFile *f)
6547 unsigned int v;
6548 v = qemu_get_byte(f) << 8;
6549 v |= qemu_get_byte(f);
6550 return v;
6553 unsigned int qemu_get_be32(QEMUFile *f)
6555 unsigned int v;
6556 v = qemu_get_byte(f) << 24;
6557 v |= qemu_get_byte(f) << 16;
6558 v |= qemu_get_byte(f) << 8;
6559 v |= qemu_get_byte(f);
6560 return v;
6563 uint64_t qemu_get_be64(QEMUFile *f)
6565 uint64_t v;
6566 v = (uint64_t)qemu_get_be32(f) << 32;
6567 v |= qemu_get_be32(f);
6568 return v;
6571 typedef struct SaveStateEntry {
6572 char idstr[256];
6573 int instance_id;
6574 int version_id;
6575 int section_id;
6576 SaveLiveStateHandler *save_live_state;
6577 SaveStateHandler *save_state;
6578 LoadStateHandler *load_state;
6579 void *opaque;
6580 struct SaveStateEntry *next;
6581 } SaveStateEntry;
6583 static SaveStateEntry *first_se;
6585 /* TODO: Individual devices generally have very little idea about the rest
6586 of the system, so instance_id should be removed/replaced.
6587 Meanwhile pass -1 as instance_id if you do not already have a clearly
6588 distinguishing id for all instances of your device class. */
6589 int register_savevm_live(const char *idstr,
6590 int instance_id,
6591 int version_id,
6592 SaveLiveStateHandler *save_live_state,
6593 SaveStateHandler *save_state,
6594 LoadStateHandler *load_state,
6595 void *opaque)
6597 SaveStateEntry *se, **pse;
6598 static int global_section_id;
6600 se = qemu_malloc(sizeof(SaveStateEntry));
6601 if (!se)
6602 return -1;
6603 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6604 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6605 se->version_id = version_id;
6606 se->section_id = global_section_id++;
6607 se->save_live_state = save_live_state;
6608 se->save_state = save_state;
6609 se->load_state = load_state;
6610 se->opaque = opaque;
6611 se->next = NULL;
6613 /* add at the end of list */
6614 pse = &first_se;
6615 while (*pse != NULL) {
6616 if (instance_id == -1
6617 && strcmp(se->idstr, (*pse)->idstr) == 0
6618 && se->instance_id <= (*pse)->instance_id)
6619 se->instance_id = (*pse)->instance_id + 1;
6620 pse = &(*pse)->next;
6622 *pse = se;
6623 return 0;
6626 int register_savevm(const char *idstr,
6627 int instance_id,
6628 int version_id,
6629 SaveStateHandler *save_state,
6630 LoadStateHandler *load_state,
6631 void *opaque)
6633 return register_savevm_live(idstr, instance_id, version_id,
6634 NULL, save_state, load_state, opaque);
6637 #define QEMU_VM_FILE_MAGIC 0x5145564d
6638 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
6639 #define QEMU_VM_FILE_VERSION 0x00000003
6641 #define QEMU_VM_EOF 0x00
6642 #define QEMU_VM_SECTION_START 0x01
6643 #define QEMU_VM_SECTION_PART 0x02
6644 #define QEMU_VM_SECTION_END 0x03
6645 #define QEMU_VM_SECTION_FULL 0x04
6647 int qemu_savevm_state_begin(QEMUFile *f)
6649 SaveStateEntry *se;
6651 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6652 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6654 for (se = first_se; se != NULL; se = se->next) {
6655 int len;
6657 if (se->save_live_state == NULL)
6658 continue;
6660 /* Section type */
6661 qemu_put_byte(f, QEMU_VM_SECTION_START);
6662 qemu_put_be32(f, se->section_id);
6664 /* ID string */
6665 len = strlen(se->idstr);
6666 qemu_put_byte(f, len);
6667 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6669 qemu_put_be32(f, se->instance_id);
6670 qemu_put_be32(f, se->version_id);
6672 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
6675 return 0;
6678 int qemu_savevm_state_iterate(QEMUFile *f)
6680 SaveStateEntry *se;
6681 int ret = 1;
6683 for (se = first_se; se != NULL; se = se->next) {
6684 if (se->save_live_state == NULL)
6685 continue;
6687 /* Section type */
6688 qemu_put_byte(f, QEMU_VM_SECTION_PART);
6689 qemu_put_be32(f, se->section_id);
6691 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
6694 if (ret)
6695 return 1;
6697 return 0;
6700 int qemu_savevm_state_complete(QEMUFile *f)
6702 SaveStateEntry *se;
6704 for (se = first_se; se != NULL; se = se->next) {
6705 if (se->save_live_state == NULL)
6706 continue;
6708 /* Section type */
6709 qemu_put_byte(f, QEMU_VM_SECTION_END);
6710 qemu_put_be32(f, se->section_id);
6712 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
6715 for(se = first_se; se != NULL; se = se->next) {
6716 int len;
6718 if (se->save_state == NULL)
6719 continue;
6721 /* Section type */
6722 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
6723 qemu_put_be32(f, se->section_id);
6725 /* ID string */
6726 len = strlen(se->idstr);
6727 qemu_put_byte(f, len);
6728 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6730 qemu_put_be32(f, se->instance_id);
6731 qemu_put_be32(f, se->version_id);
6733 se->save_state(f, se->opaque);
6736 qemu_put_byte(f, QEMU_VM_EOF);
6738 return 0;
6741 int qemu_savevm_state(QEMUFile *f)
6743 int saved_vm_running;
6744 int ret;
6746 saved_vm_running = vm_running;
6747 vm_stop(0);
6749 ret = qemu_savevm_state_begin(f);
6750 if (ret < 0)
6751 goto out;
6753 do {
6754 ret = qemu_savevm_state_iterate(f);
6755 if (ret < 0)
6756 goto out;
6757 } while (ret == 0);
6759 ret = qemu_savevm_state_complete(f);
6761 out:
6762 if (saved_vm_running)
6763 vm_start();
6764 return ret;
6767 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6769 SaveStateEntry *se;
6771 for(se = first_se; se != NULL; se = se->next) {
6772 if (!strcmp(se->idstr, idstr) &&
6773 instance_id == se->instance_id)
6774 return se;
6776 return NULL;
6779 typedef struct LoadStateEntry {
6780 SaveStateEntry *se;
6781 int section_id;
6782 int version_id;
6783 struct LoadStateEntry *next;
6784 } LoadStateEntry;
6786 static int qemu_loadvm_state_v2(QEMUFile *f)
6788 SaveStateEntry *se;
6789 int len, ret, instance_id, record_len, version_id;
6790 int64_t total_len, end_pos, cur_pos;
6791 char idstr[256];
6793 total_len = qemu_get_be64(f);
6794 end_pos = total_len + qemu_ftell(f);
6795 for(;;) {
6796 if (qemu_ftell(f) >= end_pos)
6797 break;
6798 len = qemu_get_byte(f);
6799 qemu_get_buffer(f, (uint8_t *)idstr, len);
6800 idstr[len] = '\0';
6801 instance_id = qemu_get_be32(f);
6802 version_id = qemu_get_be32(f);
6803 record_len = qemu_get_be32(f);
6804 cur_pos = qemu_ftell(f);
6805 se = find_se(idstr, instance_id);
6806 if (!se) {
6807 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6808 instance_id, idstr);
6809 } else {
6810 ret = se->load_state(f, se->opaque, version_id);
6811 if (ret < 0) {
6812 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6813 instance_id, idstr);
6816 /* always seek to exact end of record */
6817 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6819 return 0;
6822 int qemu_loadvm_state(QEMUFile *f)
6824 LoadStateEntry *first_le = NULL;
6825 uint8_t section_type;
6826 unsigned int v;
6827 int ret;
6829 v = qemu_get_be32(f);
6830 if (v != QEMU_VM_FILE_MAGIC)
6831 return -EINVAL;
6833 v = qemu_get_be32(f);
6834 if (v == QEMU_VM_FILE_VERSION_COMPAT)
6835 return qemu_loadvm_state_v2(f);
6836 if (v != QEMU_VM_FILE_VERSION)
6837 return -ENOTSUP;
6839 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
6840 uint32_t instance_id, version_id, section_id;
6841 LoadStateEntry *le;
6842 SaveStateEntry *se;
6843 char idstr[257];
6844 int len;
6846 switch (section_type) {
6847 case QEMU_VM_SECTION_START:
6848 case QEMU_VM_SECTION_FULL:
6849 /* Read section start */
6850 section_id = qemu_get_be32(f);
6851 len = qemu_get_byte(f);
6852 qemu_get_buffer(f, (uint8_t *)idstr, len);
6853 idstr[len] = 0;
6854 instance_id = qemu_get_be32(f);
6855 version_id = qemu_get_be32(f);
6857 /* Find savevm section */
6858 se = find_se(idstr, instance_id);
6859 if (se == NULL) {
6860 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
6861 ret = -EINVAL;
6862 goto out;
6865 /* Validate version */
6866 if (version_id > se->version_id) {
6867 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
6868 version_id, idstr, se->version_id);
6869 ret = -EINVAL;
6870 goto out;
6873 /* Add entry */
6874 le = qemu_mallocz(sizeof(*le));
6875 if (le == NULL) {
6876 ret = -ENOMEM;
6877 goto out;
6880 le->se = se;
6881 le->section_id = section_id;
6882 le->version_id = version_id;
6883 le->next = first_le;
6884 first_le = le;
6886 le->se->load_state(f, le->se->opaque, le->version_id);
6887 break;
6888 case QEMU_VM_SECTION_PART:
6889 case QEMU_VM_SECTION_END:
6890 section_id = qemu_get_be32(f);
6892 for (le = first_le; le && le->section_id != section_id; le = le->next);
6893 if (le == NULL) {
6894 fprintf(stderr, "Unknown savevm section %d\n", section_id);
6895 ret = -EINVAL;
6896 goto out;
6899 le->se->load_state(f, le->se->opaque, le->version_id);
6900 break;
6901 default:
6902 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
6903 ret = -EINVAL;
6904 goto out;
6908 ret = 0;
6910 out:
6911 while (first_le) {
6912 LoadStateEntry *le = first_le;
6913 first_le = first_le->next;
6914 qemu_free(le);
6917 return ret;
6920 /* device can contain snapshots */
6921 static int bdrv_can_snapshot(BlockDriverState *bs)
6923 return (bs &&
6924 !bdrv_is_removable(bs) &&
6925 !bdrv_is_read_only(bs));
6928 /* device must be snapshots in order to have a reliable snapshot */
6929 static int bdrv_has_snapshot(BlockDriverState *bs)
6931 return (bs &&
6932 !bdrv_is_removable(bs) &&
6933 !bdrv_is_read_only(bs));
6936 static BlockDriverState *get_bs_snapshots(void)
6938 BlockDriverState *bs;
6939 int i;
6941 if (bs_snapshots)
6942 return bs_snapshots;
6943 for(i = 0; i <= nb_drives; i++) {
6944 bs = drives_table[i].bdrv;
6945 if (bdrv_can_snapshot(bs))
6946 goto ok;
6948 return NULL;
6950 bs_snapshots = bs;
6951 return bs;
6954 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6955 const char *name)
6957 QEMUSnapshotInfo *sn_tab, *sn;
6958 int nb_sns, i, ret;
6960 ret = -ENOENT;
6961 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6962 if (nb_sns < 0)
6963 return ret;
6964 for(i = 0; i < nb_sns; i++) {
6965 sn = &sn_tab[i];
6966 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6967 *sn_info = *sn;
6968 ret = 0;
6969 break;
6972 qemu_free(sn_tab);
6973 return ret;
6976 void do_savevm(const char *name)
6978 BlockDriverState *bs, *bs1;
6979 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6980 int must_delete, ret, i;
6981 BlockDriverInfo bdi1, *bdi = &bdi1;
6982 QEMUFile *f;
6983 int saved_vm_running;
6984 #ifdef _WIN32
6985 struct _timeb tb;
6986 #else
6987 struct timeval tv;
6988 #endif
6990 bs = get_bs_snapshots();
6991 if (!bs) {
6992 term_printf("No block device can accept snapshots\n");
6993 return;
6996 /* ??? Should this occur after vm_stop? */
6997 qemu_aio_flush();
6999 saved_vm_running = vm_running;
7000 vm_stop(0);
7002 must_delete = 0;
7003 if (name) {
7004 ret = bdrv_snapshot_find(bs, old_sn, name);
7005 if (ret >= 0) {
7006 must_delete = 1;
7009 memset(sn, 0, sizeof(*sn));
7010 if (must_delete) {
7011 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7012 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7013 } else {
7014 if (name)
7015 pstrcpy(sn->name, sizeof(sn->name), name);
7018 /* fill auxiliary fields */
7019 #ifdef _WIN32
7020 _ftime(&tb);
7021 sn->date_sec = tb.time;
7022 sn->date_nsec = tb.millitm * 1000000;
7023 #else
7024 gettimeofday(&tv, NULL);
7025 sn->date_sec = tv.tv_sec;
7026 sn->date_nsec = tv.tv_usec * 1000;
7027 #endif
7028 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7030 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7031 term_printf("Device %s does not support VM state snapshots\n",
7032 bdrv_get_device_name(bs));
7033 goto the_end;
7036 /* save the VM state */
7037 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7038 if (!f) {
7039 term_printf("Could not open VM state file\n");
7040 goto the_end;
7042 ret = qemu_savevm_state(f);
7043 sn->vm_state_size = qemu_ftell(f);
7044 qemu_fclose(f);
7045 if (ret < 0) {
7046 term_printf("Error %d while writing VM\n", ret);
7047 goto the_end;
7050 /* create the snapshots */
7052 for(i = 0; i < nb_drives; i++) {
7053 bs1 = drives_table[i].bdrv;
7054 if (bdrv_has_snapshot(bs1)) {
7055 if (must_delete) {
7056 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7057 if (ret < 0) {
7058 term_printf("Error while deleting snapshot on '%s'\n",
7059 bdrv_get_device_name(bs1));
7062 ret = bdrv_snapshot_create(bs1, sn);
7063 if (ret < 0) {
7064 term_printf("Error while creating snapshot on '%s'\n",
7065 bdrv_get_device_name(bs1));
7070 the_end:
7071 if (saved_vm_running)
7072 vm_start();
7075 void do_loadvm(const char *name)
7077 BlockDriverState *bs, *bs1;
7078 BlockDriverInfo bdi1, *bdi = &bdi1;
7079 QEMUFile *f;
7080 int i, ret;
7081 int saved_vm_running;
7083 bs = get_bs_snapshots();
7084 if (!bs) {
7085 term_printf("No block device supports snapshots\n");
7086 return;
7089 /* Flush all IO requests so they don't interfere with the new state. */
7090 qemu_aio_flush();
7092 saved_vm_running = vm_running;
7093 vm_stop(0);
7095 for(i = 0; i <= nb_drives; i++) {
7096 bs1 = drives_table[i].bdrv;
7097 if (bdrv_has_snapshot(bs1)) {
7098 ret = bdrv_snapshot_goto(bs1, name);
7099 if (ret < 0) {
7100 if (bs != bs1)
7101 term_printf("Warning: ");
7102 switch(ret) {
7103 case -ENOTSUP:
7104 term_printf("Snapshots not supported on device '%s'\n",
7105 bdrv_get_device_name(bs1));
7106 break;
7107 case -ENOENT:
7108 term_printf("Could not find snapshot '%s' on device '%s'\n",
7109 name, bdrv_get_device_name(bs1));
7110 break;
7111 default:
7112 term_printf("Error %d while activating snapshot on '%s'\n",
7113 ret, bdrv_get_device_name(bs1));
7114 break;
7116 /* fatal on snapshot block device */
7117 if (bs == bs1)
7118 goto the_end;
7123 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7124 term_printf("Device %s does not support VM state snapshots\n",
7125 bdrv_get_device_name(bs));
7126 return;
7129 /* restore the VM state */
7130 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7131 if (!f) {
7132 term_printf("Could not open VM state file\n");
7133 goto the_end;
7135 ret = qemu_loadvm_state(f);
7136 qemu_fclose(f);
7137 if (ret < 0) {
7138 term_printf("Error %d while loading VM state\n", ret);
7140 the_end:
7141 if (saved_vm_running)
7142 vm_start();
7145 void do_delvm(const char *name)
7147 BlockDriverState *bs, *bs1;
7148 int i, ret;
7150 bs = get_bs_snapshots();
7151 if (!bs) {
7152 term_printf("No block device supports snapshots\n");
7153 return;
7156 for(i = 0; i <= nb_drives; i++) {
7157 bs1 = drives_table[i].bdrv;
7158 if (bdrv_has_snapshot(bs1)) {
7159 ret = bdrv_snapshot_delete(bs1, name);
7160 if (ret < 0) {
7161 if (ret == -ENOTSUP)
7162 term_printf("Snapshots not supported on device '%s'\n",
7163 bdrv_get_device_name(bs1));
7164 else
7165 term_printf("Error %d while deleting snapshot on '%s'\n",
7166 ret, bdrv_get_device_name(bs1));
7172 void do_info_snapshots(void)
7174 BlockDriverState *bs, *bs1;
7175 QEMUSnapshotInfo *sn_tab, *sn;
7176 int nb_sns, i;
7177 char buf[256];
7179 bs = get_bs_snapshots();
7180 if (!bs) {
7181 term_printf("No available block device supports snapshots\n");
7182 return;
7184 term_printf("Snapshot devices:");
7185 for(i = 0; i <= nb_drives; i++) {
7186 bs1 = drives_table[i].bdrv;
7187 if (bdrv_has_snapshot(bs1)) {
7188 if (bs == bs1)
7189 term_printf(" %s", bdrv_get_device_name(bs1));
7192 term_printf("\n");
7194 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7195 if (nb_sns < 0) {
7196 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7197 return;
7199 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7200 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7201 for(i = 0; i < nb_sns; i++) {
7202 sn = &sn_tab[i];
7203 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7205 qemu_free(sn_tab);
7208 /***********************************************************/
7209 /* ram save/restore */
7211 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7213 int v;
7215 v = qemu_get_byte(f);
7216 switch(v) {
7217 case 0:
7218 if (qemu_get_buffer(f, buf, len) != len)
7219 return -EIO;
7220 break;
7221 case 1:
7222 v = qemu_get_byte(f);
7223 memset(buf, v, len);
7224 break;
7225 default:
7226 return -EINVAL;
7228 return 0;
7231 static int ram_load_v1(QEMUFile *f, void *opaque)
7233 int ret;
7234 ram_addr_t i;
7236 if (qemu_get_be32(f) != phys_ram_size)
7237 return -EINVAL;
7238 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7239 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7240 if (ret)
7241 return ret;
7243 return 0;
7246 #define BDRV_HASH_BLOCK_SIZE 1024
7247 #define IOBUF_SIZE 4096
7248 #define RAM_CBLOCK_MAGIC 0xfabe
7250 typedef struct RamDecompressState {
7251 z_stream zstream;
7252 QEMUFile *f;
7253 uint8_t buf[IOBUF_SIZE];
7254 } RamDecompressState;
7256 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7258 int ret;
7259 memset(s, 0, sizeof(*s));
7260 s->f = f;
7261 ret = inflateInit(&s->zstream);
7262 if (ret != Z_OK)
7263 return -1;
7264 return 0;
7267 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7269 int ret, clen;
7271 s->zstream.avail_out = len;
7272 s->zstream.next_out = buf;
7273 while (s->zstream.avail_out > 0) {
7274 if (s->zstream.avail_in == 0) {
7275 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7276 return -1;
7277 clen = qemu_get_be16(s->f);
7278 if (clen > IOBUF_SIZE)
7279 return -1;
7280 qemu_get_buffer(s->f, s->buf, clen);
7281 s->zstream.avail_in = clen;
7282 s->zstream.next_in = s->buf;
7284 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7285 if (ret != Z_OK && ret != Z_STREAM_END) {
7286 return -1;
7289 return 0;
7292 static void ram_decompress_close(RamDecompressState *s)
7294 inflateEnd(&s->zstream);
7297 #define RAM_SAVE_FLAG_FULL 0x01
7298 #define RAM_SAVE_FLAG_COMPRESS 0x02
7299 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
7300 #define RAM_SAVE_FLAG_PAGE 0x08
7301 #define RAM_SAVE_FLAG_EOS 0x10
7303 static int is_dup_page(uint8_t *page, uint8_t ch)
7305 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
7306 uint32_t *array = (uint32_t *)page;
7307 int i;
7309 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
7310 if (array[i] != val)
7311 return 0;
7314 return 1;
7317 static int ram_save_block(QEMUFile *f)
7319 static ram_addr_t current_addr = 0;
7320 ram_addr_t saved_addr = current_addr;
7321 ram_addr_t addr = 0;
7322 int found = 0;
7324 while (addr < phys_ram_size) {
7325 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
7326 uint8_t ch;
7328 cpu_physical_memory_reset_dirty(current_addr,
7329 current_addr + TARGET_PAGE_SIZE,
7330 MIGRATION_DIRTY_FLAG);
7332 ch = *(phys_ram_base + current_addr);
7334 if (is_dup_page(phys_ram_base + current_addr, ch)) {
7335 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
7336 qemu_put_byte(f, ch);
7337 } else {
7338 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
7339 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
7342 found = 1;
7343 break;
7345 addr += TARGET_PAGE_SIZE;
7346 current_addr = (saved_addr + addr) % phys_ram_size;
7349 return found;
7352 static ram_addr_t ram_save_threshold = 10;
7354 static ram_addr_t ram_save_remaining(void)
7356 ram_addr_t addr;
7357 ram_addr_t count = 0;
7359 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7360 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7361 count++;
7364 return count;
7367 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
7369 ram_addr_t addr;
7371 if (stage == 1) {
7372 /* Make sure all dirty bits are set */
7373 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7374 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7375 cpu_physical_memory_set_dirty(addr);
7378 /* Enable dirty memory tracking */
7379 cpu_physical_memory_set_dirty_tracking(1);
7381 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
7384 while (!qemu_file_rate_limit(f)) {
7385 int ret;
7387 ret = ram_save_block(f);
7388 if (ret == 0) /* no more blocks */
7389 break;
7392 /* try transferring iterative blocks of memory */
7394 if (stage == 3) {
7395 cpu_physical_memory_set_dirty_tracking(0);
7397 /* flush all remaining blocks regardless of rate limiting */
7398 while (ram_save_block(f) != 0);
7401 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
7403 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
7406 static int ram_load_dead(QEMUFile *f, void *opaque)
7408 RamDecompressState s1, *s = &s1;
7409 uint8_t buf[10];
7410 ram_addr_t i;
7412 if (ram_decompress_open(s, f) < 0)
7413 return -EINVAL;
7414 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7415 if (ram_decompress_buf(s, buf, 1) < 0) {
7416 fprintf(stderr, "Error while reading ram block header\n");
7417 goto error;
7419 if (buf[0] == 0) {
7420 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7421 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7422 goto error;
7424 } else {
7425 error:
7426 printf("Error block header\n");
7427 return -EINVAL;
7430 ram_decompress_close(s);
7432 return 0;
7435 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7437 ram_addr_t addr;
7438 int flags;
7440 if (version_id == 1)
7441 return ram_load_v1(f, opaque);
7443 if (version_id == 2) {
7444 if (qemu_get_be32(f) != phys_ram_size)
7445 return -EINVAL;
7446 return ram_load_dead(f, opaque);
7449 if (version_id != 3)
7450 return -EINVAL;
7452 do {
7453 addr = qemu_get_be64(f);
7455 flags = addr & ~TARGET_PAGE_MASK;
7456 addr &= TARGET_PAGE_MASK;
7458 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
7459 if (addr != phys_ram_size)
7460 return -EINVAL;
7463 if (flags & RAM_SAVE_FLAG_FULL) {
7464 if (ram_load_dead(f, opaque) < 0)
7465 return -EINVAL;
7468 if (flags & RAM_SAVE_FLAG_COMPRESS) {
7469 uint8_t ch = qemu_get_byte(f);
7470 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
7471 } else if (flags & RAM_SAVE_FLAG_PAGE)
7472 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7473 } while (!(flags & RAM_SAVE_FLAG_EOS));
7475 return 0;
7478 void qemu_service_io(void)
7480 CPUState *env = cpu_single_env;
7481 if (env) {
7482 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7483 #ifdef USE_KQEMU
7484 if (env->kqemu_enabled) {
7485 kqemu_cpu_interrupt(env);
7487 #endif
7491 /***********************************************************/
7492 /* bottom halves (can be seen as timers which expire ASAP) */
7494 struct QEMUBH {
7495 QEMUBHFunc *cb;
7496 void *opaque;
7497 int scheduled;
7498 QEMUBH *next;
7501 static QEMUBH *first_bh = NULL;
7503 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7505 QEMUBH *bh;
7506 bh = qemu_mallocz(sizeof(QEMUBH));
7507 if (!bh)
7508 return NULL;
7509 bh->cb = cb;
7510 bh->opaque = opaque;
7511 return bh;
7514 int qemu_bh_poll(void)
7516 QEMUBH *bh, **pbh;
7517 int ret;
7519 ret = 0;
7520 for(;;) {
7521 pbh = &first_bh;
7522 bh = *pbh;
7523 if (!bh)
7524 break;
7525 ret = 1;
7526 *pbh = bh->next;
7527 bh->scheduled = 0;
7528 bh->cb(bh->opaque);
7530 return ret;
7533 void qemu_bh_schedule(QEMUBH *bh)
7535 CPUState *env = cpu_single_env;
7536 if (bh->scheduled)
7537 return;
7538 bh->scheduled = 1;
7539 bh->next = first_bh;
7540 first_bh = bh;
7542 /* stop the currently executing CPU to execute the BH ASAP */
7543 if (env) {
7544 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7548 void qemu_bh_cancel(QEMUBH *bh)
7550 QEMUBH **pbh;
7551 if (bh->scheduled) {
7552 pbh = &first_bh;
7553 while (*pbh != bh)
7554 pbh = &(*pbh)->next;
7555 *pbh = bh->next;
7556 bh->scheduled = 0;
7560 void qemu_bh_delete(QEMUBH *bh)
7562 qemu_bh_cancel(bh);
7563 qemu_free(bh);
7566 /***********************************************************/
7567 /* machine registration */
7569 static QEMUMachine *first_machine = NULL;
7571 int qemu_register_machine(QEMUMachine *m)
7573 QEMUMachine **pm;
7574 pm = &first_machine;
7575 while (*pm != NULL)
7576 pm = &(*pm)->next;
7577 m->next = NULL;
7578 *pm = m;
7579 return 0;
7582 static QEMUMachine *find_machine(const char *name)
7584 QEMUMachine *m;
7586 for(m = first_machine; m != NULL; m = m->next) {
7587 if (!strcmp(m->name, name))
7588 return m;
7590 return NULL;
7593 /***********************************************************/
7594 /* main execution loop */
7596 static void gui_update(void *opaque)
7598 DisplayState *ds = opaque;
7599 ds->dpy_refresh(ds);
7600 qemu_mod_timer(ds->gui_timer,
7601 (ds->gui_timer_interval ?
7602 ds->gui_timer_interval :
7603 GUI_REFRESH_INTERVAL)
7604 + qemu_get_clock(rt_clock));
7607 struct vm_change_state_entry {
7608 VMChangeStateHandler *cb;
7609 void *opaque;
7610 LIST_ENTRY (vm_change_state_entry) entries;
7613 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7615 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7616 void *opaque)
7618 VMChangeStateEntry *e;
7620 e = qemu_mallocz(sizeof (*e));
7621 if (!e)
7622 return NULL;
7624 e->cb = cb;
7625 e->opaque = opaque;
7626 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7627 return e;
7630 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7632 LIST_REMOVE (e, entries);
7633 qemu_free (e);
7636 static void vm_state_notify(int running)
7638 VMChangeStateEntry *e;
7640 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7641 e->cb(e->opaque, running);
7645 /* XXX: support several handlers */
7646 static VMStopHandler *vm_stop_cb;
7647 static void *vm_stop_opaque;
7649 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7651 vm_stop_cb = cb;
7652 vm_stop_opaque = opaque;
7653 return 0;
7656 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7658 vm_stop_cb = NULL;
7661 void vm_start(void)
7663 if (!vm_running) {
7664 cpu_enable_ticks();
7665 vm_running = 1;
7666 vm_state_notify(1);
7667 qemu_rearm_alarm_timer(alarm_timer);
7671 void vm_stop(int reason)
7673 if (vm_running) {
7674 cpu_disable_ticks();
7675 vm_running = 0;
7676 if (reason != 0) {
7677 if (vm_stop_cb) {
7678 vm_stop_cb(vm_stop_opaque, reason);
7681 vm_state_notify(0);
7685 /* reset/shutdown handler */
7687 typedef struct QEMUResetEntry {
7688 QEMUResetHandler *func;
7689 void *opaque;
7690 struct QEMUResetEntry *next;
7691 } QEMUResetEntry;
7693 static QEMUResetEntry *first_reset_entry;
7694 static int reset_requested;
7695 static int shutdown_requested;
7696 static int powerdown_requested;
7698 int qemu_shutdown_requested(void)
7700 int r = shutdown_requested;
7701 shutdown_requested = 0;
7702 return r;
7705 int qemu_reset_requested(void)
7707 int r = reset_requested;
7708 reset_requested = 0;
7709 return r;
7712 int qemu_powerdown_requested(void)
7714 int r = powerdown_requested;
7715 powerdown_requested = 0;
7716 return r;
7719 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7721 QEMUResetEntry **pre, *re;
7723 pre = &first_reset_entry;
7724 while (*pre != NULL)
7725 pre = &(*pre)->next;
7726 re = qemu_mallocz(sizeof(QEMUResetEntry));
7727 re->func = func;
7728 re->opaque = opaque;
7729 re->next = NULL;
7730 *pre = re;
7733 void qemu_system_reset(void)
7735 QEMUResetEntry *re;
7737 /* reset all devices */
7738 for(re = first_reset_entry; re != NULL; re = re->next) {
7739 re->func(re->opaque);
7743 void qemu_system_reset_request(void)
7745 if (no_reboot) {
7746 shutdown_requested = 1;
7747 } else {
7748 reset_requested = 1;
7750 if (cpu_single_env)
7751 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7754 void qemu_system_shutdown_request(void)
7756 shutdown_requested = 1;
7757 if (cpu_single_env)
7758 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7761 void qemu_system_powerdown_request(void)
7763 powerdown_requested = 1;
7764 if (cpu_single_env)
7765 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7768 void main_loop_wait(int timeout)
7770 IOHandlerRecord *ioh;
7771 fd_set rfds, wfds, xfds;
7772 int ret, nfds;
7773 #ifdef _WIN32
7774 int ret2, i;
7775 #endif
7776 struct timeval tv;
7777 PollingEntry *pe;
7780 /* XXX: need to suppress polling by better using win32 events */
7781 ret = 0;
7782 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7783 ret |= pe->func(pe->opaque);
7785 #ifdef _WIN32
7786 if (ret == 0) {
7787 int err;
7788 WaitObjects *w = &wait_objects;
7790 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7791 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7792 if (w->func[ret - WAIT_OBJECT_0])
7793 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7795 /* Check for additional signaled events */
7796 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7798 /* Check if event is signaled */
7799 ret2 = WaitForSingleObject(w->events[i], 0);
7800 if(ret2 == WAIT_OBJECT_0) {
7801 if (w->func[i])
7802 w->func[i](w->opaque[i]);
7803 } else if (ret2 == WAIT_TIMEOUT) {
7804 } else {
7805 err = GetLastError();
7806 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7809 } else if (ret == WAIT_TIMEOUT) {
7810 } else {
7811 err = GetLastError();
7812 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7815 #endif
7816 /* poll any events */
7817 /* XXX: separate device handlers from system ones */
7818 nfds = -1;
7819 FD_ZERO(&rfds);
7820 FD_ZERO(&wfds);
7821 FD_ZERO(&xfds);
7822 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7823 if (ioh->deleted)
7824 continue;
7825 if (ioh->fd_read &&
7826 (!ioh->fd_read_poll ||
7827 ioh->fd_read_poll(ioh->opaque) != 0)) {
7828 FD_SET(ioh->fd, &rfds);
7829 if (ioh->fd > nfds)
7830 nfds = ioh->fd;
7832 if (ioh->fd_write) {
7833 FD_SET(ioh->fd, &wfds);
7834 if (ioh->fd > nfds)
7835 nfds = ioh->fd;
7839 tv.tv_sec = 0;
7840 #ifdef _WIN32
7841 tv.tv_usec = 0;
7842 #else
7843 tv.tv_usec = timeout * 1000;
7844 #endif
7845 #if defined(CONFIG_SLIRP)
7846 if (slirp_inited) {
7847 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7849 #endif
7850 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7851 if (ret > 0) {
7852 IOHandlerRecord **pioh;
7854 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7855 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7856 ioh->fd_read(ioh->opaque);
7858 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7859 ioh->fd_write(ioh->opaque);
7863 /* remove deleted IO handlers */
7864 pioh = &first_io_handler;
7865 while (*pioh) {
7866 ioh = *pioh;
7867 if (ioh->deleted) {
7868 *pioh = ioh->next;
7869 qemu_free(ioh);
7870 } else
7871 pioh = &ioh->next;
7874 #if defined(CONFIG_SLIRP)
7875 if (slirp_inited) {
7876 if (ret < 0) {
7877 FD_ZERO(&rfds);
7878 FD_ZERO(&wfds);
7879 FD_ZERO(&xfds);
7881 slirp_select_poll(&rfds, &wfds, &xfds);
7883 #endif
7885 if (vm_running) {
7886 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7887 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7888 qemu_get_clock(vm_clock));
7889 /* run dma transfers, if any */
7890 DMA_run();
7893 /* real time timers */
7894 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7895 qemu_get_clock(rt_clock));
7897 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7898 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7899 qemu_rearm_alarm_timer(alarm_timer);
7902 /* Check bottom-halves last in case any of the earlier events triggered
7903 them. */
7904 qemu_bh_poll();
7908 static int main_loop(void)
7910 int ret, timeout;
7911 #ifdef CONFIG_PROFILER
7912 int64_t ti;
7913 #endif
7914 CPUState *env;
7916 cur_cpu = first_cpu;
7917 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7918 for(;;) {
7919 if (vm_running) {
7921 for(;;) {
7922 /* get next cpu */
7923 env = next_cpu;
7924 #ifdef CONFIG_PROFILER
7925 ti = profile_getclock();
7926 #endif
7927 if (use_icount) {
7928 int64_t count;
7929 int decr;
7930 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7931 env->icount_decr.u16.low = 0;
7932 env->icount_extra = 0;
7933 count = qemu_next_deadline();
7934 count = (count + (1 << icount_time_shift) - 1)
7935 >> icount_time_shift;
7936 qemu_icount += count;
7937 decr = (count > 0xffff) ? 0xffff : count;
7938 count -= decr;
7939 env->icount_decr.u16.low = decr;
7940 env->icount_extra = count;
7942 ret = cpu_exec(env);
7943 #ifdef CONFIG_PROFILER
7944 qemu_time += profile_getclock() - ti;
7945 #endif
7946 if (use_icount) {
7947 /* Fold pending instructions back into the
7948 instruction counter, and clear the interrupt flag. */
7949 qemu_icount -= (env->icount_decr.u16.low
7950 + env->icount_extra);
7951 env->icount_decr.u32 = 0;
7952 env->icount_extra = 0;
7954 next_cpu = env->next_cpu ?: first_cpu;
7955 if (event_pending && likely(ret != EXCP_DEBUG)) {
7956 ret = EXCP_INTERRUPT;
7957 event_pending = 0;
7958 break;
7960 if (ret == EXCP_HLT) {
7961 /* Give the next CPU a chance to run. */
7962 cur_cpu = env;
7963 continue;
7965 if (ret != EXCP_HALTED)
7966 break;
7967 /* all CPUs are halted ? */
7968 if (env == cur_cpu)
7969 break;
7971 cur_cpu = env;
7973 if (shutdown_requested) {
7974 ret = EXCP_INTERRUPT;
7975 if (no_shutdown) {
7976 vm_stop(0);
7977 no_shutdown = 0;
7979 else
7980 break;
7982 if (reset_requested) {
7983 reset_requested = 0;
7984 qemu_system_reset();
7985 ret = EXCP_INTERRUPT;
7987 if (powerdown_requested) {
7988 powerdown_requested = 0;
7989 qemu_system_powerdown();
7990 ret = EXCP_INTERRUPT;
7992 if (unlikely(ret == EXCP_DEBUG)) {
7993 vm_stop(EXCP_DEBUG);
7995 /* If all cpus are halted then wait until the next IRQ */
7996 /* XXX: use timeout computed from timers */
7997 if (ret == EXCP_HALTED) {
7998 if (use_icount) {
7999 int64_t add;
8000 int64_t delta;
8001 /* Advance virtual time to the next event. */
8002 if (use_icount == 1) {
8003 /* When not using an adaptive execution frequency
8004 we tend to get badly out of sync with real time,
8005 so just delay for a reasonable amount of time. */
8006 delta = 0;
8007 } else {
8008 delta = cpu_get_icount() - cpu_get_clock();
8010 if (delta > 0) {
8011 /* If virtual time is ahead of real time then just
8012 wait for IO. */
8013 timeout = (delta / 1000000) + 1;
8014 } else {
8015 /* Wait for either IO to occur or the next
8016 timer event. */
8017 add = qemu_next_deadline();
8018 /* We advance the timer before checking for IO.
8019 Limit the amount we advance so that early IO
8020 activity won't get the guest too far ahead. */
8021 if (add > 10000000)
8022 add = 10000000;
8023 delta += add;
8024 add = (add + (1 << icount_time_shift) - 1)
8025 >> icount_time_shift;
8026 qemu_icount += add;
8027 timeout = delta / 1000000;
8028 if (timeout < 0)
8029 timeout = 0;
8031 } else {
8032 timeout = 10;
8034 } else {
8035 timeout = 0;
8037 } else {
8038 if (shutdown_requested) {
8039 ret = EXCP_INTERRUPT;
8040 break;
8042 timeout = 10;
8044 #ifdef CONFIG_PROFILER
8045 ti = profile_getclock();
8046 #endif
8047 main_loop_wait(timeout);
8048 #ifdef CONFIG_PROFILER
8049 dev_time += profile_getclock() - ti;
8050 #endif
8052 cpu_disable_ticks();
8053 return ret;
8056 static void help(int exitcode)
8058 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8059 "usage: %s [options] [disk_image]\n"
8060 "\n"
8061 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8062 "\n"
8063 "Standard options:\n"
8064 "-M machine select emulated machine (-M ? for list)\n"
8065 "-cpu cpu select CPU (-cpu ? for list)\n"
8066 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8067 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8068 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8069 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8070 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8071 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8072 " [,cache=on|off][,format=f]\n"
8073 " use 'file' as a drive image\n"
8074 "-mtdblock file use 'file' as on-board Flash memory image\n"
8075 "-sd file use 'file' as SecureDigital card image\n"
8076 "-pflash file use 'file' as a parallel flash image\n"
8077 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8078 "-snapshot write to temporary files instead of disk image files\n"
8079 #ifdef CONFIG_SDL
8080 "-no-frame open SDL window without a frame and window decorations\n"
8081 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8082 "-no-quit disable SDL window close capability\n"
8083 #endif
8084 #ifdef TARGET_I386
8085 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8086 #endif
8087 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8088 "-smp n set the number of CPUs to 'n' [default=1]\n"
8089 "-nographic disable graphical output and redirect serial I/Os to console\n"
8090 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8091 #ifndef _WIN32
8092 "-k language use keyboard layout (for example \"fr\" for French)\n"
8093 #endif
8094 #ifdef HAS_AUDIO
8095 "-audio-help print list of audio drivers and their options\n"
8096 "-soundhw c1,... enable audio support\n"
8097 " and only specified sound cards (comma separated list)\n"
8098 " use -soundhw ? to get the list of supported cards\n"
8099 " use -soundhw all to enable all of them\n"
8100 #endif
8101 "-vga [std|cirrus|vmware]\n"
8102 " select video card type\n"
8103 "-localtime set the real time clock to local time [default=utc]\n"
8104 "-full-screen start in full screen\n"
8105 #ifdef TARGET_I386
8106 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8107 #endif
8108 "-usb enable the USB driver (will be the default soon)\n"
8109 "-usbdevice name add the host or guest USB device 'name'\n"
8110 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8111 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8112 #endif
8113 "-name string set the name of the guest\n"
8114 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
8115 "\n"
8116 "Network options:\n"
8117 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8118 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8119 #ifdef CONFIG_SLIRP
8120 "-net user[,vlan=n][,hostname=host]\n"
8121 " connect the user mode network stack to VLAN 'n' and send\n"
8122 " hostname 'host' to DHCP clients\n"
8123 #endif
8124 #ifdef _WIN32
8125 "-net tap[,vlan=n],ifname=name\n"
8126 " connect the host TAP network interface to VLAN 'n'\n"
8127 #else
8128 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8129 " connect the host TAP network interface to VLAN 'n' and use the\n"
8130 " network scripts 'file' (default=%s)\n"
8131 " and 'dfile' (default=%s);\n"
8132 " use '[down]script=no' to disable script execution;\n"
8133 " use 'fd=h' to connect to an already opened TAP interface\n"
8134 #endif
8135 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8136 " connect the vlan 'n' to another VLAN using a socket connection\n"
8137 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8138 " connect the vlan 'n' to multicast maddr and port\n"
8139 #ifdef CONFIG_VDE
8140 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8141 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8142 " on host and listening for incoming connections on 'socketpath'.\n"
8143 " Use group 'groupname' and mode 'octalmode' to change default\n"
8144 " ownership and permissions for communication port.\n"
8145 #endif
8146 "-net none use it alone to have zero network devices; if no -net option\n"
8147 " is provided, the default is '-net nic -net user'\n"
8148 "\n"
8149 #ifdef CONFIG_SLIRP
8150 "-tftp dir allow tftp access to files in dir [-net user]\n"
8151 "-bootp file advertise file in BOOTP replies\n"
8152 #ifndef _WIN32
8153 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8154 #endif
8155 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8156 " redirect TCP or UDP connections from host to guest [-net user]\n"
8157 #endif
8158 "\n"
8159 "Linux boot specific:\n"
8160 "-kernel bzImage use 'bzImage' as kernel image\n"
8161 "-append cmdline use 'cmdline' as kernel command line\n"
8162 "-initrd file use 'file' as initial ram disk\n"
8163 "\n"
8164 "Debug/Expert options:\n"
8165 "-monitor dev redirect the monitor to char device 'dev'\n"
8166 "-serial dev redirect the serial port to char device 'dev'\n"
8167 "-parallel dev redirect the parallel port to char device 'dev'\n"
8168 "-pidfile file Write PID to 'file'\n"
8169 "-S freeze CPU at startup (use 'c' to start execution)\n"
8170 "-s wait gdb connection to port\n"
8171 "-p port set gdb connection port [default=%s]\n"
8172 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8173 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8174 " translation (t=none or lba) (usually qemu can guess them)\n"
8175 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8176 #ifdef USE_KQEMU
8177 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8178 "-no-kqemu disable KQEMU kernel module usage\n"
8179 #endif
8180 #ifdef TARGET_I386
8181 "-no-acpi disable ACPI\n"
8182 #endif
8183 #ifdef CONFIG_CURSES
8184 "-curses use a curses/ncurses interface instead of SDL\n"
8185 #endif
8186 "-no-reboot exit instead of rebooting\n"
8187 "-no-shutdown stop before shutdown\n"
8188 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8189 "-vnc display start a VNC server on display\n"
8190 #ifndef _WIN32
8191 "-daemonize daemonize QEMU after initializing\n"
8192 #endif
8193 "-option-rom rom load a file, rom, into the option ROM space\n"
8194 #ifdef TARGET_SPARC
8195 "-prom-env variable=value set OpenBIOS nvram variables\n"
8196 #endif
8197 "-clock force the use of the given methods for timer alarm.\n"
8198 " To see what timers are available use -clock ?\n"
8199 "-startdate select initial date of the clock\n"
8200 "-icount [N|auto]\n"
8201 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8202 "\n"
8203 "During emulation, the following keys are useful:\n"
8204 "ctrl-alt-f toggle full screen\n"
8205 "ctrl-alt-n switch to virtual console 'n'\n"
8206 "ctrl-alt toggle mouse and keyboard grab\n"
8207 "\n"
8208 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8210 "qemu",
8211 DEFAULT_RAM_SIZE,
8212 #ifndef _WIN32
8213 DEFAULT_NETWORK_SCRIPT,
8214 DEFAULT_NETWORK_DOWN_SCRIPT,
8215 #endif
8216 DEFAULT_GDBSTUB_PORT,
8217 "/tmp/qemu.log");
8218 exit(exitcode);
8221 #define HAS_ARG 0x0001
8223 enum {
8224 QEMU_OPTION_h,
8226 QEMU_OPTION_M,
8227 QEMU_OPTION_cpu,
8228 QEMU_OPTION_fda,
8229 QEMU_OPTION_fdb,
8230 QEMU_OPTION_hda,
8231 QEMU_OPTION_hdb,
8232 QEMU_OPTION_hdc,
8233 QEMU_OPTION_hdd,
8234 QEMU_OPTION_drive,
8235 QEMU_OPTION_cdrom,
8236 QEMU_OPTION_mtdblock,
8237 QEMU_OPTION_sd,
8238 QEMU_OPTION_pflash,
8239 QEMU_OPTION_boot,
8240 QEMU_OPTION_snapshot,
8241 #ifdef TARGET_I386
8242 QEMU_OPTION_no_fd_bootchk,
8243 #endif
8244 QEMU_OPTION_m,
8245 QEMU_OPTION_nographic,
8246 QEMU_OPTION_portrait,
8247 #ifdef HAS_AUDIO
8248 QEMU_OPTION_audio_help,
8249 QEMU_OPTION_soundhw,
8250 #endif
8252 QEMU_OPTION_net,
8253 QEMU_OPTION_tftp,
8254 QEMU_OPTION_bootp,
8255 QEMU_OPTION_smb,
8256 QEMU_OPTION_redir,
8258 QEMU_OPTION_kernel,
8259 QEMU_OPTION_append,
8260 QEMU_OPTION_initrd,
8262 QEMU_OPTION_S,
8263 QEMU_OPTION_s,
8264 QEMU_OPTION_p,
8265 QEMU_OPTION_d,
8266 QEMU_OPTION_hdachs,
8267 QEMU_OPTION_L,
8268 QEMU_OPTION_bios,
8269 QEMU_OPTION_k,
8270 QEMU_OPTION_localtime,
8271 QEMU_OPTION_g,
8272 QEMU_OPTION_vga,
8273 QEMU_OPTION_echr,
8274 QEMU_OPTION_monitor,
8275 QEMU_OPTION_serial,
8276 QEMU_OPTION_parallel,
8277 QEMU_OPTION_loadvm,
8278 QEMU_OPTION_full_screen,
8279 QEMU_OPTION_no_frame,
8280 QEMU_OPTION_alt_grab,
8281 QEMU_OPTION_no_quit,
8282 QEMU_OPTION_pidfile,
8283 QEMU_OPTION_no_kqemu,
8284 QEMU_OPTION_kernel_kqemu,
8285 QEMU_OPTION_win2k_hack,
8286 QEMU_OPTION_usb,
8287 QEMU_OPTION_usbdevice,
8288 QEMU_OPTION_smp,
8289 QEMU_OPTION_vnc,
8290 QEMU_OPTION_no_acpi,
8291 QEMU_OPTION_curses,
8292 QEMU_OPTION_no_reboot,
8293 QEMU_OPTION_no_shutdown,
8294 QEMU_OPTION_show_cursor,
8295 QEMU_OPTION_daemonize,
8296 QEMU_OPTION_option_rom,
8297 QEMU_OPTION_semihosting,
8298 QEMU_OPTION_name,
8299 QEMU_OPTION_prom_env,
8300 QEMU_OPTION_old_param,
8301 QEMU_OPTION_clock,
8302 QEMU_OPTION_startdate,
8303 QEMU_OPTION_tb_size,
8304 QEMU_OPTION_icount,
8305 QEMU_OPTION_uuid,
8308 typedef struct QEMUOption {
8309 const char *name;
8310 int flags;
8311 int index;
8312 } QEMUOption;
8314 static const QEMUOption qemu_options[] = {
8315 { "h", 0, QEMU_OPTION_h },
8316 { "help", 0, QEMU_OPTION_h },
8318 { "M", HAS_ARG, QEMU_OPTION_M },
8319 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8320 { "fda", HAS_ARG, QEMU_OPTION_fda },
8321 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8322 { "hda", HAS_ARG, QEMU_OPTION_hda },
8323 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8324 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8325 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8326 { "drive", HAS_ARG, QEMU_OPTION_drive },
8327 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8328 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8329 { "sd", HAS_ARG, QEMU_OPTION_sd },
8330 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8331 { "boot", HAS_ARG, QEMU_OPTION_boot },
8332 { "snapshot", 0, QEMU_OPTION_snapshot },
8333 #ifdef TARGET_I386
8334 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8335 #endif
8336 { "m", HAS_ARG, QEMU_OPTION_m },
8337 { "nographic", 0, QEMU_OPTION_nographic },
8338 { "portrait", 0, QEMU_OPTION_portrait },
8339 { "k", HAS_ARG, QEMU_OPTION_k },
8340 #ifdef HAS_AUDIO
8341 { "audio-help", 0, QEMU_OPTION_audio_help },
8342 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8343 #endif
8345 { "net", HAS_ARG, QEMU_OPTION_net},
8346 #ifdef CONFIG_SLIRP
8347 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8348 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8349 #ifndef _WIN32
8350 { "smb", HAS_ARG, QEMU_OPTION_smb },
8351 #endif
8352 { "redir", HAS_ARG, QEMU_OPTION_redir },
8353 #endif
8355 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8356 { "append", HAS_ARG, QEMU_OPTION_append },
8357 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8359 { "S", 0, QEMU_OPTION_S },
8360 { "s", 0, QEMU_OPTION_s },
8361 { "p", HAS_ARG, QEMU_OPTION_p },
8362 { "d", HAS_ARG, QEMU_OPTION_d },
8363 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8364 { "L", HAS_ARG, QEMU_OPTION_L },
8365 { "bios", HAS_ARG, QEMU_OPTION_bios },
8366 #ifdef USE_KQEMU
8367 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8368 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8369 #endif
8370 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8371 { "g", 1, QEMU_OPTION_g },
8372 #endif
8373 { "localtime", 0, QEMU_OPTION_localtime },
8374 { "vga", HAS_ARG, QEMU_OPTION_vga },
8375 { "echr", HAS_ARG, QEMU_OPTION_echr },
8376 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8377 { "serial", HAS_ARG, QEMU_OPTION_serial },
8378 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8379 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8380 { "full-screen", 0, QEMU_OPTION_full_screen },
8381 #ifdef CONFIG_SDL
8382 { "no-frame", 0, QEMU_OPTION_no_frame },
8383 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8384 { "no-quit", 0, QEMU_OPTION_no_quit },
8385 #endif
8386 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8387 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8388 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8389 { "smp", HAS_ARG, QEMU_OPTION_smp },
8390 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8391 #ifdef CONFIG_CURSES
8392 { "curses", 0, QEMU_OPTION_curses },
8393 #endif
8394 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
8396 /* temporary options */
8397 { "usb", 0, QEMU_OPTION_usb },
8398 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8399 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8400 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8401 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8402 { "daemonize", 0, QEMU_OPTION_daemonize },
8403 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8404 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8405 { "semihosting", 0, QEMU_OPTION_semihosting },
8406 #endif
8407 { "name", HAS_ARG, QEMU_OPTION_name },
8408 #if defined(TARGET_SPARC)
8409 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8410 #endif
8411 #if defined(TARGET_ARM)
8412 { "old-param", 0, QEMU_OPTION_old_param },
8413 #endif
8414 { "clock", HAS_ARG, QEMU_OPTION_clock },
8415 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8416 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8417 { "icount", HAS_ARG, QEMU_OPTION_icount },
8418 { NULL },
8421 /* password input */
8423 int qemu_key_check(BlockDriverState *bs, const char *name)
8425 char password[256];
8426 int i;
8428 if (!bdrv_is_encrypted(bs))
8429 return 0;
8431 term_printf("%s is encrypted.\n", name);
8432 for(i = 0; i < 3; i++) {
8433 monitor_readline("Password: ", 1, password, sizeof(password));
8434 if (bdrv_set_key(bs, password) == 0)
8435 return 0;
8436 term_printf("invalid password\n");
8438 return -EPERM;
8441 static BlockDriverState *get_bdrv(int index)
8443 if (index > nb_drives)
8444 return NULL;
8445 return drives_table[index].bdrv;
8448 static void read_passwords(void)
8450 BlockDriverState *bs;
8451 int i;
8453 for(i = 0; i < 6; i++) {
8454 bs = get_bdrv(i);
8455 if (bs)
8456 qemu_key_check(bs, bdrv_get_device_name(bs));
8460 #ifdef HAS_AUDIO
8461 struct soundhw soundhw[] = {
8462 #ifdef HAS_AUDIO_CHOICE
8463 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8465 "pcspk",
8466 "PC speaker",
8469 { .init_isa = pcspk_audio_init }
8471 #endif
8473 "sb16",
8474 "Creative Sound Blaster 16",
8477 { .init_isa = SB16_init }
8480 #ifdef CONFIG_CS4231A
8482 "cs4231a",
8483 "CS4231A",
8486 { .init_isa = cs4231a_init }
8488 #endif
8490 #ifdef CONFIG_ADLIB
8492 "adlib",
8493 #ifdef HAS_YMF262
8494 "Yamaha YMF262 (OPL3)",
8495 #else
8496 "Yamaha YM3812 (OPL2)",
8497 #endif
8500 { .init_isa = Adlib_init }
8502 #endif
8504 #ifdef CONFIG_GUS
8506 "gus",
8507 "Gravis Ultrasound GF1",
8510 { .init_isa = GUS_init }
8512 #endif
8514 #ifdef CONFIG_AC97
8516 "ac97",
8517 "Intel 82801AA AC97 Audio",
8520 { .init_pci = ac97_init }
8522 #endif
8525 "es1370",
8526 "ENSONIQ AudioPCI ES1370",
8529 { .init_pci = es1370_init }
8531 #endif
8533 { NULL, NULL, 0, 0, { NULL } }
8536 static void select_soundhw (const char *optarg)
8538 struct soundhw *c;
8540 if (*optarg == '?') {
8541 show_valid_cards:
8543 printf ("Valid sound card names (comma separated):\n");
8544 for (c = soundhw; c->name; ++c) {
8545 printf ("%-11s %s\n", c->name, c->descr);
8547 printf ("\n-soundhw all will enable all of the above\n");
8548 exit (*optarg != '?');
8550 else {
8551 size_t l;
8552 const char *p;
8553 char *e;
8554 int bad_card = 0;
8556 if (!strcmp (optarg, "all")) {
8557 for (c = soundhw; c->name; ++c) {
8558 c->enabled = 1;
8560 return;
8563 p = optarg;
8564 while (*p) {
8565 e = strchr (p, ',');
8566 l = !e ? strlen (p) : (size_t) (e - p);
8568 for (c = soundhw; c->name; ++c) {
8569 if (!strncmp (c->name, p, l)) {
8570 c->enabled = 1;
8571 break;
8575 if (!c->name) {
8576 if (l > 80) {
8577 fprintf (stderr,
8578 "Unknown sound card name (too big to show)\n");
8580 else {
8581 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8582 (int) l, p);
8584 bad_card = 1;
8586 p += l + (e != NULL);
8589 if (bad_card)
8590 goto show_valid_cards;
8593 #endif
8595 static void select_vgahw (const char *p)
8597 const char *opts;
8599 if (strstart(p, "std", &opts)) {
8600 cirrus_vga_enabled = 0;
8601 vmsvga_enabled = 0;
8602 } else if (strstart(p, "cirrus", &opts)) {
8603 cirrus_vga_enabled = 1;
8604 vmsvga_enabled = 0;
8605 } else if (strstart(p, "vmware", &opts)) {
8606 cirrus_vga_enabled = 0;
8607 vmsvga_enabled = 1;
8608 } else {
8609 invalid_vga:
8610 fprintf(stderr, "Unknown vga type: %s\n", p);
8611 exit(1);
8613 while (*opts) {
8614 const char *nextopt;
8616 if (strstart(opts, ",retrace=", &nextopt)) {
8617 opts = nextopt;
8618 if (strstart(opts, "dumb", &nextopt))
8619 vga_retrace_method = VGA_RETRACE_DUMB;
8620 else if (strstart(opts, "precise", &nextopt))
8621 vga_retrace_method = VGA_RETRACE_PRECISE;
8622 else goto invalid_vga;
8623 } else goto invalid_vga;
8624 opts = nextopt;
8628 #ifdef _WIN32
8629 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8631 exit(STATUS_CONTROL_C_EXIT);
8632 return TRUE;
8634 #endif
8636 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
8638 int ret;
8640 if(strlen(str) != 36)
8641 return -1;
8643 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
8644 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
8645 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
8647 if(ret != 16)
8648 return -1;
8650 return 0;
8653 #define MAX_NET_CLIENTS 32
8655 #ifndef _WIN32
8657 static void termsig_handler(int signal)
8659 qemu_system_shutdown_request();
8662 static void termsig_setup(void)
8664 struct sigaction act;
8666 memset(&act, 0, sizeof(act));
8667 act.sa_handler = termsig_handler;
8668 sigaction(SIGINT, &act, NULL);
8669 sigaction(SIGHUP, &act, NULL);
8670 sigaction(SIGTERM, &act, NULL);
8673 #endif
8675 int main(int argc, char **argv)
8677 #ifdef CONFIG_GDBSTUB
8678 int use_gdbstub;
8679 const char *gdbstub_port;
8680 #endif
8681 uint32_t boot_devices_bitmap = 0;
8682 int i;
8683 int snapshot, linux_boot, net_boot;
8684 const char *initrd_filename;
8685 const char *kernel_filename, *kernel_cmdline;
8686 const char *boot_devices = "";
8687 DisplayState *ds = &display_state;
8688 int cyls, heads, secs, translation;
8689 const char *net_clients[MAX_NET_CLIENTS];
8690 int nb_net_clients;
8691 int hda_index;
8692 int optind;
8693 const char *r, *optarg;
8694 CharDriverState *monitor_hd;
8695 const char *monitor_device;
8696 const char *serial_devices[MAX_SERIAL_PORTS];
8697 int serial_device_index;
8698 const char *parallel_devices[MAX_PARALLEL_PORTS];
8699 int parallel_device_index;
8700 const char *loadvm = NULL;
8701 QEMUMachine *machine;
8702 const char *cpu_model;
8703 const char *usb_devices[MAX_USB_CMDLINE];
8704 int usb_devices_index;
8705 int fds[2];
8706 int tb_size;
8707 const char *pid_file = NULL;
8708 VLANState *vlan;
8709 int autostart;
8711 LIST_INIT (&vm_change_state_head);
8712 #ifndef _WIN32
8714 struct sigaction act;
8715 sigfillset(&act.sa_mask);
8716 act.sa_flags = 0;
8717 act.sa_handler = SIG_IGN;
8718 sigaction(SIGPIPE, &act, NULL);
8720 #else
8721 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8722 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8723 QEMU to run on a single CPU */
8725 HANDLE h;
8726 DWORD mask, smask;
8727 int i;
8728 h = GetCurrentProcess();
8729 if (GetProcessAffinityMask(h, &mask, &smask)) {
8730 for(i = 0; i < 32; i++) {
8731 if (mask & (1 << i))
8732 break;
8734 if (i != 32) {
8735 mask = 1 << i;
8736 SetProcessAffinityMask(h, mask);
8740 #endif
8742 register_machines();
8743 machine = first_machine;
8744 cpu_model = NULL;
8745 initrd_filename = NULL;
8746 ram_size = 0;
8747 vga_ram_size = VGA_RAM_SIZE;
8748 #ifdef CONFIG_GDBSTUB
8749 use_gdbstub = 0;
8750 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8751 #endif
8752 snapshot = 0;
8753 nographic = 0;
8754 curses = 0;
8755 kernel_filename = NULL;
8756 kernel_cmdline = "";
8757 cyls = heads = secs = 0;
8758 translation = BIOS_ATA_TRANSLATION_AUTO;
8759 monitor_device = "vc";
8761 serial_devices[0] = "vc:80Cx24C";
8762 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8763 serial_devices[i] = NULL;
8764 serial_device_index = 0;
8766 parallel_devices[0] = "vc:640x480";
8767 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8768 parallel_devices[i] = NULL;
8769 parallel_device_index = 0;
8771 usb_devices_index = 0;
8773 nb_net_clients = 0;
8774 nb_drives = 0;
8775 nb_drives_opt = 0;
8776 hda_index = -1;
8778 nb_nics = 0;
8780 tb_size = 0;
8781 autostart= 1;
8783 optind = 1;
8784 for(;;) {
8785 if (optind >= argc)
8786 break;
8787 r = argv[optind];
8788 if (r[0] != '-') {
8789 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8790 } else {
8791 const QEMUOption *popt;
8793 optind++;
8794 /* Treat --foo the same as -foo. */
8795 if (r[1] == '-')
8796 r++;
8797 popt = qemu_options;
8798 for(;;) {
8799 if (!popt->name) {
8800 fprintf(stderr, "%s: invalid option -- '%s'\n",
8801 argv[0], r);
8802 exit(1);
8804 if (!strcmp(popt->name, r + 1))
8805 break;
8806 popt++;
8808 if (popt->flags & HAS_ARG) {
8809 if (optind >= argc) {
8810 fprintf(stderr, "%s: option '%s' requires an argument\n",
8811 argv[0], r);
8812 exit(1);
8814 optarg = argv[optind++];
8815 } else {
8816 optarg = NULL;
8819 switch(popt->index) {
8820 case QEMU_OPTION_M:
8821 machine = find_machine(optarg);
8822 if (!machine) {
8823 QEMUMachine *m;
8824 printf("Supported machines are:\n");
8825 for(m = first_machine; m != NULL; m = m->next) {
8826 printf("%-10s %s%s\n",
8827 m->name, m->desc,
8828 m == first_machine ? " (default)" : "");
8830 exit(*optarg != '?');
8832 break;
8833 case QEMU_OPTION_cpu:
8834 /* hw initialization will check this */
8835 if (*optarg == '?') {
8836 /* XXX: implement xxx_cpu_list for targets that still miss it */
8837 #if defined(cpu_list)
8838 cpu_list(stdout, &fprintf);
8839 #endif
8840 exit(0);
8841 } else {
8842 cpu_model = optarg;
8844 break;
8845 case QEMU_OPTION_initrd:
8846 initrd_filename = optarg;
8847 break;
8848 case QEMU_OPTION_hda:
8849 if (cyls == 0)
8850 hda_index = drive_add(optarg, HD_ALIAS, 0);
8851 else
8852 hda_index = drive_add(optarg, HD_ALIAS
8853 ",cyls=%d,heads=%d,secs=%d%s",
8854 0, cyls, heads, secs,
8855 translation == BIOS_ATA_TRANSLATION_LBA ?
8856 ",trans=lba" :
8857 translation == BIOS_ATA_TRANSLATION_NONE ?
8858 ",trans=none" : "");
8859 break;
8860 case QEMU_OPTION_hdb:
8861 case QEMU_OPTION_hdc:
8862 case QEMU_OPTION_hdd:
8863 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8864 break;
8865 case QEMU_OPTION_drive:
8866 drive_add(NULL, "%s", optarg);
8867 break;
8868 case QEMU_OPTION_mtdblock:
8869 drive_add(optarg, MTD_ALIAS);
8870 break;
8871 case QEMU_OPTION_sd:
8872 drive_add(optarg, SD_ALIAS);
8873 break;
8874 case QEMU_OPTION_pflash:
8875 drive_add(optarg, PFLASH_ALIAS);
8876 break;
8877 case QEMU_OPTION_snapshot:
8878 snapshot = 1;
8879 break;
8880 case QEMU_OPTION_hdachs:
8882 const char *p;
8883 p = optarg;
8884 cyls = strtol(p, (char **)&p, 0);
8885 if (cyls < 1 || cyls > 16383)
8886 goto chs_fail;
8887 if (*p != ',')
8888 goto chs_fail;
8889 p++;
8890 heads = strtol(p, (char **)&p, 0);
8891 if (heads < 1 || heads > 16)
8892 goto chs_fail;
8893 if (*p != ',')
8894 goto chs_fail;
8895 p++;
8896 secs = strtol(p, (char **)&p, 0);
8897 if (secs < 1 || secs > 63)
8898 goto chs_fail;
8899 if (*p == ',') {
8900 p++;
8901 if (!strcmp(p, "none"))
8902 translation = BIOS_ATA_TRANSLATION_NONE;
8903 else if (!strcmp(p, "lba"))
8904 translation = BIOS_ATA_TRANSLATION_LBA;
8905 else if (!strcmp(p, "auto"))
8906 translation = BIOS_ATA_TRANSLATION_AUTO;
8907 else
8908 goto chs_fail;
8909 } else if (*p != '\0') {
8910 chs_fail:
8911 fprintf(stderr, "qemu: invalid physical CHS format\n");
8912 exit(1);
8914 if (hda_index != -1)
8915 snprintf(drives_opt[hda_index].opt,
8916 sizeof(drives_opt[hda_index].opt),
8917 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8918 0, cyls, heads, secs,
8919 translation == BIOS_ATA_TRANSLATION_LBA ?
8920 ",trans=lba" :
8921 translation == BIOS_ATA_TRANSLATION_NONE ?
8922 ",trans=none" : "");
8924 break;
8925 case QEMU_OPTION_nographic:
8926 nographic = 1;
8927 break;
8928 #ifdef CONFIG_CURSES
8929 case QEMU_OPTION_curses:
8930 curses = 1;
8931 break;
8932 #endif
8933 case QEMU_OPTION_portrait:
8934 graphic_rotate = 1;
8935 break;
8936 case QEMU_OPTION_kernel:
8937 kernel_filename = optarg;
8938 break;
8939 case QEMU_OPTION_append:
8940 kernel_cmdline = optarg;
8941 break;
8942 case QEMU_OPTION_cdrom:
8943 drive_add(optarg, CDROM_ALIAS);
8944 break;
8945 case QEMU_OPTION_boot:
8946 boot_devices = optarg;
8947 /* We just do some generic consistency checks */
8949 /* Could easily be extended to 64 devices if needed */
8950 const char *p;
8952 boot_devices_bitmap = 0;
8953 for (p = boot_devices; *p != '\0'; p++) {
8954 /* Allowed boot devices are:
8955 * a b : floppy disk drives
8956 * c ... f : IDE disk drives
8957 * g ... m : machine implementation dependant drives
8958 * n ... p : network devices
8959 * It's up to each machine implementation to check
8960 * if the given boot devices match the actual hardware
8961 * implementation and firmware features.
8963 if (*p < 'a' || *p > 'q') {
8964 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8965 exit(1);
8967 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8968 fprintf(stderr,
8969 "Boot device '%c' was given twice\n",*p);
8970 exit(1);
8972 boot_devices_bitmap |= 1 << (*p - 'a');
8975 break;
8976 case QEMU_OPTION_fda:
8977 case QEMU_OPTION_fdb:
8978 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8979 break;
8980 #ifdef TARGET_I386
8981 case QEMU_OPTION_no_fd_bootchk:
8982 fd_bootchk = 0;
8983 break;
8984 #endif
8985 case QEMU_OPTION_net:
8986 if (nb_net_clients >= MAX_NET_CLIENTS) {
8987 fprintf(stderr, "qemu: too many network clients\n");
8988 exit(1);
8990 net_clients[nb_net_clients] = optarg;
8991 nb_net_clients++;
8992 break;
8993 #ifdef CONFIG_SLIRP
8994 case QEMU_OPTION_tftp:
8995 tftp_prefix = optarg;
8996 break;
8997 case QEMU_OPTION_bootp:
8998 bootp_filename = optarg;
8999 break;
9000 #ifndef _WIN32
9001 case QEMU_OPTION_smb:
9002 net_slirp_smb(optarg);
9003 break;
9004 #endif
9005 case QEMU_OPTION_redir:
9006 net_slirp_redir(optarg);
9007 break;
9008 #endif
9009 #ifdef HAS_AUDIO
9010 case QEMU_OPTION_audio_help:
9011 AUD_help ();
9012 exit (0);
9013 break;
9014 case QEMU_OPTION_soundhw:
9015 select_soundhw (optarg);
9016 break;
9017 #endif
9018 case QEMU_OPTION_h:
9019 help(0);
9020 break;
9021 case QEMU_OPTION_m: {
9022 uint64_t value;
9023 char *ptr;
9025 value = strtoul(optarg, &ptr, 10);
9026 switch (*ptr) {
9027 case 0: case 'M': case 'm':
9028 value <<= 20;
9029 break;
9030 case 'G': case 'g':
9031 value <<= 30;
9032 break;
9033 default:
9034 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9035 exit(1);
9038 /* On 32-bit hosts, QEMU is limited by virtual address space */
9039 if (value > (2047 << 20)
9040 #ifndef USE_KQEMU
9041 && HOST_LONG_BITS == 32
9042 #endif
9044 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9045 exit(1);
9047 if (value != (uint64_t)(ram_addr_t)value) {
9048 fprintf(stderr, "qemu: ram size too large\n");
9049 exit(1);
9051 ram_size = value;
9052 break;
9054 case QEMU_OPTION_d:
9056 int mask;
9057 const CPULogItem *item;
9059 mask = cpu_str_to_log_mask(optarg);
9060 if (!mask) {
9061 printf("Log items (comma separated):\n");
9062 for(item = cpu_log_items; item->mask != 0; item++) {
9063 printf("%-10s %s\n", item->name, item->help);
9065 exit(1);
9067 cpu_set_log(mask);
9069 break;
9070 #ifdef CONFIG_GDBSTUB
9071 case QEMU_OPTION_s:
9072 use_gdbstub = 1;
9073 break;
9074 case QEMU_OPTION_p:
9075 gdbstub_port = optarg;
9076 break;
9077 #endif
9078 case QEMU_OPTION_L:
9079 bios_dir = optarg;
9080 break;
9081 case QEMU_OPTION_bios:
9082 bios_name = optarg;
9083 break;
9084 case QEMU_OPTION_S:
9085 autostart = 0;
9086 break;
9087 case QEMU_OPTION_k:
9088 keyboard_layout = optarg;
9089 break;
9090 case QEMU_OPTION_localtime:
9091 rtc_utc = 0;
9092 break;
9093 case QEMU_OPTION_vga:
9094 select_vgahw (optarg);
9095 break;
9096 case QEMU_OPTION_g:
9098 const char *p;
9099 int w, h, depth;
9100 p = optarg;
9101 w = strtol(p, (char **)&p, 10);
9102 if (w <= 0) {
9103 graphic_error:
9104 fprintf(stderr, "qemu: invalid resolution or depth\n");
9105 exit(1);
9107 if (*p != 'x')
9108 goto graphic_error;
9109 p++;
9110 h = strtol(p, (char **)&p, 10);
9111 if (h <= 0)
9112 goto graphic_error;
9113 if (*p == 'x') {
9114 p++;
9115 depth = strtol(p, (char **)&p, 10);
9116 if (depth != 8 && depth != 15 && depth != 16 &&
9117 depth != 24 && depth != 32)
9118 goto graphic_error;
9119 } else if (*p == '\0') {
9120 depth = graphic_depth;
9121 } else {
9122 goto graphic_error;
9125 graphic_width = w;
9126 graphic_height = h;
9127 graphic_depth = depth;
9129 break;
9130 case QEMU_OPTION_echr:
9132 char *r;
9133 term_escape_char = strtol(optarg, &r, 0);
9134 if (r == optarg)
9135 printf("Bad argument to echr\n");
9136 break;
9138 case QEMU_OPTION_monitor:
9139 monitor_device = optarg;
9140 break;
9141 case QEMU_OPTION_serial:
9142 if (serial_device_index >= MAX_SERIAL_PORTS) {
9143 fprintf(stderr, "qemu: too many serial ports\n");
9144 exit(1);
9146 serial_devices[serial_device_index] = optarg;
9147 serial_device_index++;
9148 break;
9149 case QEMU_OPTION_parallel:
9150 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9151 fprintf(stderr, "qemu: too many parallel ports\n");
9152 exit(1);
9154 parallel_devices[parallel_device_index] = optarg;
9155 parallel_device_index++;
9156 break;
9157 case QEMU_OPTION_loadvm:
9158 loadvm = optarg;
9159 break;
9160 case QEMU_OPTION_full_screen:
9161 full_screen = 1;
9162 break;
9163 #ifdef CONFIG_SDL
9164 case QEMU_OPTION_no_frame:
9165 no_frame = 1;
9166 break;
9167 case QEMU_OPTION_alt_grab:
9168 alt_grab = 1;
9169 break;
9170 case QEMU_OPTION_no_quit:
9171 no_quit = 1;
9172 break;
9173 #endif
9174 case QEMU_OPTION_pidfile:
9175 pid_file = optarg;
9176 break;
9177 #ifdef TARGET_I386
9178 case QEMU_OPTION_win2k_hack:
9179 win2k_install_hack = 1;
9180 break;
9181 #endif
9182 #ifdef USE_KQEMU
9183 case QEMU_OPTION_no_kqemu:
9184 kqemu_allowed = 0;
9185 break;
9186 case QEMU_OPTION_kernel_kqemu:
9187 kqemu_allowed = 2;
9188 break;
9189 #endif
9190 case QEMU_OPTION_usb:
9191 usb_enabled = 1;
9192 break;
9193 case QEMU_OPTION_usbdevice:
9194 usb_enabled = 1;
9195 if (usb_devices_index >= MAX_USB_CMDLINE) {
9196 fprintf(stderr, "Too many USB devices\n");
9197 exit(1);
9199 usb_devices[usb_devices_index] = optarg;
9200 usb_devices_index++;
9201 break;
9202 case QEMU_OPTION_smp:
9203 smp_cpus = atoi(optarg);
9204 if (smp_cpus < 1) {
9205 fprintf(stderr, "Invalid number of CPUs\n");
9206 exit(1);
9208 break;
9209 case QEMU_OPTION_vnc:
9210 vnc_display = optarg;
9211 break;
9212 case QEMU_OPTION_no_acpi:
9213 acpi_enabled = 0;
9214 break;
9215 case QEMU_OPTION_no_reboot:
9216 no_reboot = 1;
9217 break;
9218 case QEMU_OPTION_no_shutdown:
9219 no_shutdown = 1;
9220 break;
9221 case QEMU_OPTION_show_cursor:
9222 cursor_hide = 0;
9223 break;
9224 case QEMU_OPTION_uuid:
9225 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
9226 fprintf(stderr, "Fail to parse UUID string."
9227 " Wrong format.\n");
9228 exit(1);
9230 break;
9231 case QEMU_OPTION_daemonize:
9232 daemonize = 1;
9233 break;
9234 case QEMU_OPTION_option_rom:
9235 if (nb_option_roms >= MAX_OPTION_ROMS) {
9236 fprintf(stderr, "Too many option ROMs\n");
9237 exit(1);
9239 option_rom[nb_option_roms] = optarg;
9240 nb_option_roms++;
9241 break;
9242 case QEMU_OPTION_semihosting:
9243 semihosting_enabled = 1;
9244 break;
9245 case QEMU_OPTION_name:
9246 qemu_name = optarg;
9247 break;
9248 #ifdef TARGET_SPARC
9249 case QEMU_OPTION_prom_env:
9250 if (nb_prom_envs >= MAX_PROM_ENVS) {
9251 fprintf(stderr, "Too many prom variables\n");
9252 exit(1);
9254 prom_envs[nb_prom_envs] = optarg;
9255 nb_prom_envs++;
9256 break;
9257 #endif
9258 #ifdef TARGET_ARM
9259 case QEMU_OPTION_old_param:
9260 old_param = 1;
9261 break;
9262 #endif
9263 case QEMU_OPTION_clock:
9264 configure_alarms(optarg);
9265 break;
9266 case QEMU_OPTION_startdate:
9268 struct tm tm;
9269 time_t rtc_start_date;
9270 if (!strcmp(optarg, "now")) {
9271 rtc_date_offset = -1;
9272 } else {
9273 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9274 &tm.tm_year,
9275 &tm.tm_mon,
9276 &tm.tm_mday,
9277 &tm.tm_hour,
9278 &tm.tm_min,
9279 &tm.tm_sec) == 6) {
9280 /* OK */
9281 } else if (sscanf(optarg, "%d-%d-%d",
9282 &tm.tm_year,
9283 &tm.tm_mon,
9284 &tm.tm_mday) == 3) {
9285 tm.tm_hour = 0;
9286 tm.tm_min = 0;
9287 tm.tm_sec = 0;
9288 } else {
9289 goto date_fail;
9291 tm.tm_year -= 1900;
9292 tm.tm_mon--;
9293 rtc_start_date = mktimegm(&tm);
9294 if (rtc_start_date == -1) {
9295 date_fail:
9296 fprintf(stderr, "Invalid date format. Valid format are:\n"
9297 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9298 exit(1);
9300 rtc_date_offset = time(NULL) - rtc_start_date;
9303 break;
9304 case QEMU_OPTION_tb_size:
9305 tb_size = strtol(optarg, NULL, 0);
9306 if (tb_size < 0)
9307 tb_size = 0;
9308 break;
9309 case QEMU_OPTION_icount:
9310 use_icount = 1;
9311 if (strcmp(optarg, "auto") == 0) {
9312 icount_time_shift = -1;
9313 } else {
9314 icount_time_shift = strtol(optarg, NULL, 0);
9316 break;
9321 if (smp_cpus > machine->max_cpus) {
9322 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
9323 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
9324 machine->max_cpus);
9325 exit(1);
9328 if (nographic) {
9329 if (serial_device_index == 0)
9330 serial_devices[0] = "stdio";
9331 if (parallel_device_index == 0)
9332 parallel_devices[0] = "null";
9333 if (strncmp(monitor_device, "vc", 2) == 0)
9334 monitor_device = "stdio";
9337 #ifndef _WIN32
9338 if (daemonize) {
9339 pid_t pid;
9341 if (pipe(fds) == -1)
9342 exit(1);
9344 pid = fork();
9345 if (pid > 0) {
9346 uint8_t status;
9347 ssize_t len;
9349 close(fds[1]);
9351 again:
9352 len = read(fds[0], &status, 1);
9353 if (len == -1 && (errno == EINTR))
9354 goto again;
9356 if (len != 1)
9357 exit(1);
9358 else if (status == 1) {
9359 fprintf(stderr, "Could not acquire pidfile\n");
9360 exit(1);
9361 } else
9362 exit(0);
9363 } else if (pid < 0)
9364 exit(1);
9366 setsid();
9368 pid = fork();
9369 if (pid > 0)
9370 exit(0);
9371 else if (pid < 0)
9372 exit(1);
9374 umask(027);
9376 signal(SIGTSTP, SIG_IGN);
9377 signal(SIGTTOU, SIG_IGN);
9378 signal(SIGTTIN, SIG_IGN);
9380 #endif
9382 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9383 if (daemonize) {
9384 uint8_t status = 1;
9385 write(fds[1], &status, 1);
9386 } else
9387 fprintf(stderr, "Could not acquire pid file\n");
9388 exit(1);
9391 #ifdef USE_KQEMU
9392 if (smp_cpus > 1)
9393 kqemu_allowed = 0;
9394 #endif
9395 linux_boot = (kernel_filename != NULL);
9396 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9398 if (!linux_boot && net_boot == 0 &&
9399 !machine->nodisk_ok && nb_drives_opt == 0)
9400 help(1);
9402 if (!linux_boot && *kernel_cmdline != '\0') {
9403 fprintf(stderr, "-append only allowed with -kernel option\n");
9404 exit(1);
9407 if (!linux_boot && initrd_filename != NULL) {
9408 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9409 exit(1);
9412 /* boot to floppy or the default cd if no hard disk defined yet */
9413 if (!boot_devices[0]) {
9414 boot_devices = "cad";
9416 setvbuf(stdout, NULL, _IOLBF, 0);
9418 init_timers();
9419 init_timer_alarm();
9420 if (use_icount && icount_time_shift < 0) {
9421 use_icount = 2;
9422 /* 125MIPS seems a reasonable initial guess at the guest speed.
9423 It will be corrected fairly quickly anyway. */
9424 icount_time_shift = 3;
9425 init_icount_adjust();
9428 #ifdef _WIN32
9429 socket_init();
9430 #endif
9432 /* init network clients */
9433 if (nb_net_clients == 0) {
9434 /* if no clients, we use a default config */
9435 net_clients[nb_net_clients++] = "nic";
9436 #ifdef CONFIG_SLIRP
9437 net_clients[nb_net_clients++] = "user";
9438 #endif
9441 for(i = 0;i < nb_net_clients; i++) {
9442 if (net_client_parse(net_clients[i]) < 0)
9443 exit(1);
9445 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9446 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9447 continue;
9448 if (vlan->nb_guest_devs == 0)
9449 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9450 if (vlan->nb_host_devs == 0)
9451 fprintf(stderr,
9452 "Warning: vlan %d is not connected to host network\n",
9453 vlan->id);
9456 #ifdef TARGET_I386
9457 /* XXX: this should be moved in the PC machine instantiation code */
9458 if (net_boot != 0) {
9459 int netroms = 0;
9460 for (i = 0; i < nb_nics && i < 4; i++) {
9461 const char *model = nd_table[i].model;
9462 char buf[1024];
9463 if (net_boot & (1 << i)) {
9464 if (model == NULL)
9465 model = "ne2k_pci";
9466 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9467 if (get_image_size(buf) > 0) {
9468 if (nb_option_roms >= MAX_OPTION_ROMS) {
9469 fprintf(stderr, "Too many option ROMs\n");
9470 exit(1);
9472 option_rom[nb_option_roms] = strdup(buf);
9473 nb_option_roms++;
9474 netroms++;
9478 if (netroms == 0) {
9479 fprintf(stderr, "No valid PXE rom found for network device\n");
9480 exit(1);
9483 #endif
9485 /* init the memory */
9486 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9488 if (machine->ram_require & RAMSIZE_FIXED) {
9489 if (ram_size > 0) {
9490 if (ram_size < phys_ram_size) {
9491 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9492 machine->name, (unsigned long long) phys_ram_size);
9493 exit(-1);
9496 phys_ram_size = ram_size;
9497 } else
9498 ram_size = phys_ram_size;
9499 } else {
9500 if (ram_size == 0)
9501 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9503 phys_ram_size += ram_size;
9506 phys_ram_base = qemu_vmalloc(phys_ram_size);
9507 if (!phys_ram_base) {
9508 fprintf(stderr, "Could not allocate physical memory\n");
9509 exit(1);
9512 /* init the dynamic translator */
9513 cpu_exec_init_all(tb_size * 1024 * 1024);
9515 bdrv_init();
9517 /* we always create the cdrom drive, even if no disk is there */
9519 if (nb_drives_opt < MAX_DRIVES)
9520 drive_add(NULL, CDROM_ALIAS);
9522 /* we always create at least one floppy */
9524 if (nb_drives_opt < MAX_DRIVES)
9525 drive_add(NULL, FD_ALIAS, 0);
9527 /* we always create one sd slot, even if no card is in it */
9529 if (nb_drives_opt < MAX_DRIVES)
9530 drive_add(NULL, SD_ALIAS);
9532 /* open the virtual block devices */
9534 for(i = 0; i < nb_drives_opt; i++)
9535 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9536 exit(1);
9538 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9539 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
9541 /* terminal init */
9542 memset(&display_state, 0, sizeof(display_state));
9543 if (nographic) {
9544 if (curses) {
9545 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9546 exit(1);
9548 /* nearly nothing to do */
9549 dumb_display_init(ds);
9550 } else if (vnc_display != NULL) {
9551 vnc_display_init(ds);
9552 if (vnc_display_open(ds, vnc_display) < 0)
9553 exit(1);
9554 } else
9555 #if defined(CONFIG_CURSES)
9556 if (curses) {
9557 curses_display_init(ds, full_screen);
9558 } else
9559 #endif
9561 #if defined(CONFIG_SDL)
9562 sdl_display_init(ds, full_screen, no_frame);
9563 #elif defined(CONFIG_COCOA)
9564 cocoa_display_init(ds, full_screen);
9565 #else
9566 dumb_display_init(ds);
9567 #endif
9570 #ifndef _WIN32
9571 /* must be after terminal init, SDL library changes signal handlers */
9572 termsig_setup();
9573 #endif
9575 /* Maintain compatibility with multiple stdio monitors */
9576 if (!strcmp(monitor_device,"stdio")) {
9577 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9578 const char *devname = serial_devices[i];
9579 if (devname && !strcmp(devname,"mon:stdio")) {
9580 monitor_device = NULL;
9581 break;
9582 } else if (devname && !strcmp(devname,"stdio")) {
9583 monitor_device = NULL;
9584 serial_devices[i] = "mon:stdio";
9585 break;
9589 if (monitor_device) {
9590 monitor_hd = qemu_chr_open(monitor_device);
9591 if (!monitor_hd) {
9592 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9593 exit(1);
9595 monitor_init(monitor_hd, !nographic);
9598 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9599 const char *devname = serial_devices[i];
9600 if (devname && strcmp(devname, "none")) {
9601 serial_hds[i] = qemu_chr_open(devname);
9602 if (!serial_hds[i]) {
9603 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9604 devname);
9605 exit(1);
9607 if (strstart(devname, "vc", 0))
9608 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9612 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9613 const char *devname = parallel_devices[i];
9614 if (devname && strcmp(devname, "none")) {
9615 parallel_hds[i] = qemu_chr_open(devname);
9616 if (!parallel_hds[i]) {
9617 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9618 devname);
9619 exit(1);
9621 if (strstart(devname, "vc", 0))
9622 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9626 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9627 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9629 /* init USB devices */
9630 if (usb_enabled) {
9631 for(i = 0; i < usb_devices_index; i++) {
9632 if (usb_device_add(usb_devices[i]) < 0) {
9633 fprintf(stderr, "Warning: could not add USB device %s\n",
9634 usb_devices[i]);
9639 if (display_state.dpy_refresh) {
9640 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9641 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9644 #ifdef CONFIG_GDBSTUB
9645 if (use_gdbstub) {
9646 /* XXX: use standard host:port notation and modify options
9647 accordingly. */
9648 if (gdbserver_start(gdbstub_port) < 0) {
9649 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9650 gdbstub_port);
9651 exit(1);
9654 #endif
9656 if (loadvm)
9657 do_loadvm(loadvm);
9660 /* XXX: simplify init */
9661 read_passwords();
9662 if (autostart) {
9663 vm_start();
9667 if (daemonize) {
9668 uint8_t status = 0;
9669 ssize_t len;
9670 int fd;
9672 again1:
9673 len = write(fds[1], &status, 1);
9674 if (len == -1 && (errno == EINTR))
9675 goto again1;
9677 if (len != 1)
9678 exit(1);
9680 chdir("/");
9681 TFR(fd = open("/dev/null", O_RDWR));
9682 if (fd == -1)
9683 exit(1);
9685 dup2(fd, 0);
9686 dup2(fd, 1);
9687 dup2(fd, 2);
9689 close(fd);
9692 main_loop();
9693 quit_timers();
9695 #if !defined(_WIN32)
9696 /* close network clients */
9697 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9698 VLANClientState *vc;
9700 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9701 if (vc->fd_read == tap_receive) {
9702 char ifname[64];
9703 TAPState *s = vc->opaque;
9705 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9706 s->down_script[0])
9707 launch_script(s->down_script, ifname, s->fd);
9709 #if defined(CONFIG_VDE)
9710 if (vc->fd_read == vde_from_qemu) {
9711 VDEState *s = vc->opaque;
9712 vde_close(s->vde);
9714 #endif
9717 #endif
9718 return 0;