Remove >= asserts on unsigned inputs
[qemu-kvm/fedora.git] / vl.c
blobc8db57983b146ffb138896e554fd4771b569899a
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <sys/time.h>
47 #include <zlib.h>
49 #ifndef _WIN32
50 #include <sys/times.h>
51 #include <sys/wait.h>
52 #include <termios.h>
53 #include <sys/poll.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <dirent.h>
59 #include <netdb.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #ifndef __APPLE__
65 #include <libutil.h>
66 #endif
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
69 #else
70 #ifndef __sun__
71 #include <linux/if.h>
72 #include <linux/if_tun.h>
73 #include <pty.h>
74 #include <malloc.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
80 #include "hpet.h"
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
84 #else
85 #include <sys/stat.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
95 #include <net/if.h>
96 #include <syslog.h>
97 #include <stropts.h>
98 #endif
99 #endif
100 #else
101 #include <winsock2.h>
102 int inet_aton(const char *cp, struct in_addr *ia);
103 #endif
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
107 #endif
109 #ifdef _WIN32
110 #include <malloc.h>
111 #include <sys/timeb.h>
112 #include <mmsystem.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
115 #endif
117 #include "qemu_socket.h"
119 #ifdef CONFIG_SDL
120 #ifdef __APPLE__
121 #include <SDL/SDL.h>
122 #endif
123 #endif /* CONFIG_SDL */
125 #ifdef CONFIG_COCOA
126 #undef main
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
130 #include "disas.h"
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136 #ifdef __sun__
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138 #else
139 #define SMBD_COMMAND "/usr/sbin/smbd"
140 #endif
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
145 #ifdef TARGET_PPC
146 #define DEFAULT_RAM_SIZE 144
147 #else
148 #define DEFAULT_RAM_SIZE 128
149 #endif
150 /* in ms */
151 #define GUI_REFRESH_INTERVAL 30
153 /* Max number of USB devices that can be specified on the commandline. */
154 #define MAX_USB_CMDLINE 8
156 /* XXX: use a two level table to limit memory usage */
157 #define MAX_IOPORTS 65536
159 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
160 const char *bios_name = NULL;
161 void *ioport_opaque[MAX_IOPORTS];
162 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
163 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
164 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
165 to store the VM snapshots */
166 DriveInfo drives_table[MAX_DRIVES+1];
167 int nb_drives;
168 /* point to the block driver where the snapshots are managed */
169 BlockDriverState *bs_snapshots;
170 int vga_ram_size;
171 static DisplayState display_state;
172 int nographic;
173 int curses;
174 const char* keyboard_layout = NULL;
175 int64_t ticks_per_sec;
176 ram_addr_t ram_size;
177 int pit_min_timer_count = 0;
178 int nb_nics;
179 NICInfo nd_table[MAX_NICS];
180 int vm_running;
181 static int rtc_utc = 1;
182 static int rtc_date_offset = -1; /* -1 means no change */
183 int cirrus_vga_enabled = 1;
184 int vmsvga_enabled = 0;
185 #ifdef TARGET_SPARC
186 int graphic_width = 1024;
187 int graphic_height = 768;
188 int graphic_depth = 8;
189 #else
190 int graphic_width = 800;
191 int graphic_height = 600;
192 int graphic_depth = 15;
193 #endif
194 int full_screen = 0;
195 int no_frame = 0;
196 int no_quit = 0;
197 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
198 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
199 #ifdef TARGET_I386
200 int win2k_install_hack = 0;
201 #endif
202 int usb_enabled = 0;
203 static VLANState *first_vlan;
204 int smp_cpus = 1;
205 const char *vnc_display;
206 #if defined(TARGET_SPARC)
207 #define MAX_CPUS 16
208 #elif defined(TARGET_I386)
209 #define MAX_CPUS 255
210 #else
211 #define MAX_CPUS 1
212 #endif
213 int acpi_enabled = 1;
214 int fd_bootchk = 1;
215 int no_reboot = 0;
216 int no_shutdown = 0;
217 int cursor_hide = 1;
218 int graphic_rotate = 0;
219 int daemonize = 0;
220 const char *option_rom[MAX_OPTION_ROMS];
221 int nb_option_roms;
222 int semihosting_enabled = 0;
223 int autostart = 1;
224 #ifdef TARGET_ARM
225 int old_param = 0;
226 #endif
227 const char *qemu_name;
228 int alt_grab = 0;
229 #ifdef TARGET_SPARC
230 unsigned int nb_prom_envs = 0;
231 const char *prom_envs[MAX_PROM_ENVS];
232 #endif
233 int nb_drives_opt;
234 struct drive_opt {
235 const char *file;
236 char opt[1024];
237 } drives_opt[MAX_DRIVES];
239 static CPUState *cur_cpu;
240 static CPUState *next_cpu;
241 static int event_pending = 1;
242 /* Conversion factor from emulated instructions to virtual clock ticks. */
243 static int icount_time_shift;
244 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
245 #define MAX_ICOUNT_SHIFT 10
246 /* Compensate for varying guest execution speed. */
247 static int64_t qemu_icount_bias;
248 QEMUTimer *icount_rt_timer;
249 QEMUTimer *icount_vm_timer;
251 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
253 /***********************************************************/
254 /* x86 ISA bus support */
256 target_phys_addr_t isa_mem_base = 0;
257 PicState2 *isa_pic;
259 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
261 #ifdef DEBUG_UNUSED_IOPORT
262 fprintf(stderr, "unused inb: port=0x%04x\n", address);
263 #endif
264 return 0xff;
267 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
269 #ifdef DEBUG_UNUSED_IOPORT
270 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
271 #endif
274 /* default is to make two byte accesses */
275 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
277 uint32_t data;
278 data = ioport_read_table[0][address](ioport_opaque[address], address);
279 address = (address + 1) & (MAX_IOPORTS - 1);
280 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
281 return data;
284 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
286 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
287 address = (address + 1) & (MAX_IOPORTS - 1);
288 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
291 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
293 #ifdef DEBUG_UNUSED_IOPORT
294 fprintf(stderr, "unused inl: port=0x%04x\n", address);
295 #endif
296 return 0xffffffff;
299 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
301 #ifdef DEBUG_UNUSED_IOPORT
302 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
303 #endif
306 static void init_ioports(void)
308 int i;
310 for(i = 0; i < MAX_IOPORTS; i++) {
311 ioport_read_table[0][i] = default_ioport_readb;
312 ioport_write_table[0][i] = default_ioport_writeb;
313 ioport_read_table[1][i] = default_ioport_readw;
314 ioport_write_table[1][i] = default_ioport_writew;
315 ioport_read_table[2][i] = default_ioport_readl;
316 ioport_write_table[2][i] = default_ioport_writel;
320 /* size is the word size in byte */
321 int register_ioport_read(int start, int length, int size,
322 IOPortReadFunc *func, void *opaque)
324 int i, bsize;
326 if (size == 1) {
327 bsize = 0;
328 } else if (size == 2) {
329 bsize = 1;
330 } else if (size == 4) {
331 bsize = 2;
332 } else {
333 hw_error("register_ioport_read: invalid size");
334 return -1;
336 for(i = start; i < start + length; i += size) {
337 ioport_read_table[bsize][i] = func;
338 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
339 hw_error("register_ioport_read: invalid opaque");
340 ioport_opaque[i] = opaque;
342 return 0;
345 /* size is the word size in byte */
346 int register_ioport_write(int start, int length, int size,
347 IOPortWriteFunc *func, void *opaque)
349 int i, bsize;
351 if (size == 1) {
352 bsize = 0;
353 } else if (size == 2) {
354 bsize = 1;
355 } else if (size == 4) {
356 bsize = 2;
357 } else {
358 hw_error("register_ioport_write: invalid size");
359 return -1;
361 for(i = start; i < start + length; i += size) {
362 ioport_write_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_write: invalid opaque");
365 ioport_opaque[i] = opaque;
367 return 0;
370 void isa_unassign_ioport(int start, int length)
372 int i;
374 for(i = start; i < start + length; i++) {
375 ioport_read_table[0][i] = default_ioport_readb;
376 ioport_read_table[1][i] = default_ioport_readw;
377 ioport_read_table[2][i] = default_ioport_readl;
379 ioport_write_table[0][i] = default_ioport_writeb;
380 ioport_write_table[1][i] = default_ioport_writew;
381 ioport_write_table[2][i] = default_ioport_writel;
385 /***********************************************************/
387 void cpu_outb(CPUState *env, int addr, int val)
389 #ifdef DEBUG_IOPORT
390 if (loglevel & CPU_LOG_IOPORT)
391 fprintf(logfile, "outb: %04x %02x\n", addr, val);
392 #endif
393 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
394 #ifdef USE_KQEMU
395 if (env)
396 env->last_io_time = cpu_get_time_fast();
397 #endif
400 void cpu_outw(CPUState *env, int addr, int val)
402 #ifdef DEBUG_IOPORT
403 if (loglevel & CPU_LOG_IOPORT)
404 fprintf(logfile, "outw: %04x %04x\n", addr, val);
405 #endif
406 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
407 #ifdef USE_KQEMU
408 if (env)
409 env->last_io_time = cpu_get_time_fast();
410 #endif
413 void cpu_outl(CPUState *env, int addr, int val)
415 #ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "outl: %04x %08x\n", addr, val);
418 #endif
419 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
420 #ifdef USE_KQEMU
421 if (env)
422 env->last_io_time = cpu_get_time_fast();
423 #endif
426 int cpu_inb(CPUState *env, int addr)
428 int val;
429 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
430 #ifdef DEBUG_IOPORT
431 if (loglevel & CPU_LOG_IOPORT)
432 fprintf(logfile, "inb : %04x %02x\n", addr, val);
433 #endif
434 #ifdef USE_KQEMU
435 if (env)
436 env->last_io_time = cpu_get_time_fast();
437 #endif
438 return val;
441 int cpu_inw(CPUState *env, int addr)
443 int val;
444 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
445 #ifdef DEBUG_IOPORT
446 if (loglevel & CPU_LOG_IOPORT)
447 fprintf(logfile, "inw : %04x %04x\n", addr, val);
448 #endif
449 #ifdef USE_KQEMU
450 if (env)
451 env->last_io_time = cpu_get_time_fast();
452 #endif
453 return val;
456 int cpu_inl(CPUState *env, int addr)
458 int val;
459 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
460 #ifdef DEBUG_IOPORT
461 if (loglevel & CPU_LOG_IOPORT)
462 fprintf(logfile, "inl : %04x %08x\n", addr, val);
463 #endif
464 #ifdef USE_KQEMU
465 if (env)
466 env->last_io_time = cpu_get_time_fast();
467 #endif
468 return val;
471 /***********************************************************/
472 void hw_error(const char *fmt, ...)
474 va_list ap;
475 CPUState *env;
477 va_start(ap, fmt);
478 fprintf(stderr, "qemu: hardware error: ");
479 vfprintf(stderr, fmt, ap);
480 fprintf(stderr, "\n");
481 for(env = first_cpu; env != NULL; env = env->next_cpu) {
482 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
483 #ifdef TARGET_I386
484 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
485 #else
486 cpu_dump_state(env, stderr, fprintf, 0);
487 #endif
489 va_end(ap);
490 abort();
493 /***********************************************************/
494 /* keyboard/mouse */
496 static QEMUPutKBDEvent *qemu_put_kbd_event;
497 static void *qemu_put_kbd_event_opaque;
498 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
499 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
501 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
503 qemu_put_kbd_event_opaque = opaque;
504 qemu_put_kbd_event = func;
507 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
508 void *opaque, int absolute,
509 const char *name)
511 QEMUPutMouseEntry *s, *cursor;
513 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
514 if (!s)
515 return NULL;
517 s->qemu_put_mouse_event = func;
518 s->qemu_put_mouse_event_opaque = opaque;
519 s->qemu_put_mouse_event_absolute = absolute;
520 s->qemu_put_mouse_event_name = qemu_strdup(name);
521 s->next = NULL;
523 if (!qemu_put_mouse_event_head) {
524 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
525 return s;
528 cursor = qemu_put_mouse_event_head;
529 while (cursor->next != NULL)
530 cursor = cursor->next;
532 cursor->next = s;
533 qemu_put_mouse_event_current = s;
535 return s;
538 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
540 QEMUPutMouseEntry *prev = NULL, *cursor;
542 if (!qemu_put_mouse_event_head || entry == NULL)
543 return;
545 cursor = qemu_put_mouse_event_head;
546 while (cursor != NULL && cursor != entry) {
547 prev = cursor;
548 cursor = cursor->next;
551 if (cursor == NULL) // does not exist or list empty
552 return;
553 else if (prev == NULL) { // entry is head
554 qemu_put_mouse_event_head = cursor->next;
555 if (qemu_put_mouse_event_current == entry)
556 qemu_put_mouse_event_current = cursor->next;
557 qemu_free(entry->qemu_put_mouse_event_name);
558 qemu_free(entry);
559 return;
562 prev->next = entry->next;
564 if (qemu_put_mouse_event_current == entry)
565 qemu_put_mouse_event_current = prev;
567 qemu_free(entry->qemu_put_mouse_event_name);
568 qemu_free(entry);
571 void kbd_put_keycode(int keycode)
573 if (qemu_put_kbd_event) {
574 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
578 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
580 QEMUPutMouseEvent *mouse_event;
581 void *mouse_event_opaque;
582 int width;
584 if (!qemu_put_mouse_event_current) {
585 return;
588 mouse_event =
589 qemu_put_mouse_event_current->qemu_put_mouse_event;
590 mouse_event_opaque =
591 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
593 if (mouse_event) {
594 if (graphic_rotate) {
595 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
596 width = 0x7fff;
597 else
598 width = graphic_width - 1;
599 mouse_event(mouse_event_opaque,
600 width - dy, dx, dz, buttons_state);
601 } else
602 mouse_event(mouse_event_opaque,
603 dx, dy, dz, buttons_state);
607 int kbd_mouse_is_absolute(void)
609 if (!qemu_put_mouse_event_current)
610 return 0;
612 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
615 void do_info_mice(void)
617 QEMUPutMouseEntry *cursor;
618 int index = 0;
620 if (!qemu_put_mouse_event_head) {
621 term_printf("No mouse devices connected\n");
622 return;
625 term_printf("Mouse devices available:\n");
626 cursor = qemu_put_mouse_event_head;
627 while (cursor != NULL) {
628 term_printf("%c Mouse #%d: %s\n",
629 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
630 index, cursor->qemu_put_mouse_event_name);
631 index++;
632 cursor = cursor->next;
636 void do_mouse_set(int index)
638 QEMUPutMouseEntry *cursor;
639 int i = 0;
641 if (!qemu_put_mouse_event_head) {
642 term_printf("No mouse devices connected\n");
643 return;
646 cursor = qemu_put_mouse_event_head;
647 while (cursor != NULL && index != i) {
648 i++;
649 cursor = cursor->next;
652 if (cursor != NULL)
653 qemu_put_mouse_event_current = cursor;
654 else
655 term_printf("Mouse at given index not found\n");
658 /* compute with 96 bit intermediate result: (a*b)/c */
659 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
661 union {
662 uint64_t ll;
663 struct {
664 #ifdef WORDS_BIGENDIAN
665 uint32_t high, low;
666 #else
667 uint32_t low, high;
668 #endif
669 } l;
670 } u, res;
671 uint64_t rl, rh;
673 u.ll = a;
674 rl = (uint64_t)u.l.low * (uint64_t)b;
675 rh = (uint64_t)u.l.high * (uint64_t)b;
676 rh += (rl >> 32);
677 res.l.high = rh / c;
678 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
679 return res.ll;
682 /***********************************************************/
683 /* real time host monotonic timer */
685 #define QEMU_TIMER_BASE 1000000000LL
687 #ifdef WIN32
689 static int64_t clock_freq;
691 static void init_get_clock(void)
693 LARGE_INTEGER freq;
694 int ret;
695 ret = QueryPerformanceFrequency(&freq);
696 if (ret == 0) {
697 fprintf(stderr, "Could not calibrate ticks\n");
698 exit(1);
700 clock_freq = freq.QuadPart;
703 static int64_t get_clock(void)
705 LARGE_INTEGER ti;
706 QueryPerformanceCounter(&ti);
707 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
710 #else
712 static int use_rt_clock;
714 static void init_get_clock(void)
716 use_rt_clock = 0;
717 #if defined(__linux__)
719 struct timespec ts;
720 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
721 use_rt_clock = 1;
724 #endif
727 static int64_t get_clock(void)
729 #if defined(__linux__)
730 if (use_rt_clock) {
731 struct timespec ts;
732 clock_gettime(CLOCK_MONOTONIC, &ts);
733 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
734 } else
735 #endif
737 /* XXX: using gettimeofday leads to problems if the date
738 changes, so it should be avoided. */
739 struct timeval tv;
740 gettimeofday(&tv, NULL);
741 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
744 #endif
746 /* Return the virtual CPU time, based on the instruction counter. */
747 static int64_t cpu_get_icount(void)
749 int64_t icount;
750 CPUState *env = cpu_single_env;;
751 icount = qemu_icount;
752 if (env) {
753 if (!can_do_io(env))
754 fprintf(stderr, "Bad clock read\n");
755 icount -= (env->icount_decr.u16.low + env->icount_extra);
757 return qemu_icount_bias + (icount << icount_time_shift);
760 /***********************************************************/
761 /* guest cycle counter */
763 static int64_t cpu_ticks_prev;
764 static int64_t cpu_ticks_offset;
765 static int64_t cpu_clock_offset;
766 static int cpu_ticks_enabled;
768 /* return the host CPU cycle counter and handle stop/restart */
769 int64_t cpu_get_ticks(void)
771 if (use_icount) {
772 return cpu_get_icount();
774 if (!cpu_ticks_enabled) {
775 return cpu_ticks_offset;
776 } else {
777 int64_t ticks;
778 ticks = cpu_get_real_ticks();
779 if (cpu_ticks_prev > ticks) {
780 /* Note: non increasing ticks may happen if the host uses
781 software suspend */
782 cpu_ticks_offset += cpu_ticks_prev - ticks;
784 cpu_ticks_prev = ticks;
785 return ticks + cpu_ticks_offset;
789 /* return the host CPU monotonic timer and handle stop/restart */
790 static int64_t cpu_get_clock(void)
792 int64_t ti;
793 if (!cpu_ticks_enabled) {
794 return cpu_clock_offset;
795 } else {
796 ti = get_clock();
797 return ti + cpu_clock_offset;
801 /* enable cpu_get_ticks() */
802 void cpu_enable_ticks(void)
804 if (!cpu_ticks_enabled) {
805 cpu_ticks_offset -= cpu_get_real_ticks();
806 cpu_clock_offset -= get_clock();
807 cpu_ticks_enabled = 1;
811 /* disable cpu_get_ticks() : the clock is stopped. You must not call
812 cpu_get_ticks() after that. */
813 void cpu_disable_ticks(void)
815 if (cpu_ticks_enabled) {
816 cpu_ticks_offset = cpu_get_ticks();
817 cpu_clock_offset = cpu_get_clock();
818 cpu_ticks_enabled = 0;
822 /***********************************************************/
823 /* timers */
825 #define QEMU_TIMER_REALTIME 0
826 #define QEMU_TIMER_VIRTUAL 1
828 struct QEMUClock {
829 int type;
830 /* XXX: add frequency */
833 struct QEMUTimer {
834 QEMUClock *clock;
835 int64_t expire_time;
836 QEMUTimerCB *cb;
837 void *opaque;
838 struct QEMUTimer *next;
841 struct qemu_alarm_timer {
842 char const *name;
843 unsigned int flags;
845 int (*start)(struct qemu_alarm_timer *t);
846 void (*stop)(struct qemu_alarm_timer *t);
847 void (*rearm)(struct qemu_alarm_timer *t);
848 void *priv;
851 #define ALARM_FLAG_DYNTICKS 0x1
852 #define ALARM_FLAG_EXPIRED 0x2
854 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
856 return t->flags & ALARM_FLAG_DYNTICKS;
859 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
861 if (!alarm_has_dynticks(t))
862 return;
864 t->rearm(t);
867 /* TODO: MIN_TIMER_REARM_US should be optimized */
868 #define MIN_TIMER_REARM_US 250
870 static struct qemu_alarm_timer *alarm_timer;
872 #ifdef _WIN32
874 struct qemu_alarm_win32 {
875 MMRESULT timerId;
876 HANDLE host_alarm;
877 unsigned int period;
878 } alarm_win32_data = {0, NULL, -1};
880 static int win32_start_timer(struct qemu_alarm_timer *t);
881 static void win32_stop_timer(struct qemu_alarm_timer *t);
882 static void win32_rearm_timer(struct qemu_alarm_timer *t);
884 #else
886 static int unix_start_timer(struct qemu_alarm_timer *t);
887 static void unix_stop_timer(struct qemu_alarm_timer *t);
889 #ifdef __linux__
891 static int dynticks_start_timer(struct qemu_alarm_timer *t);
892 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
893 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
895 static int hpet_start_timer(struct qemu_alarm_timer *t);
896 static void hpet_stop_timer(struct qemu_alarm_timer *t);
898 static int rtc_start_timer(struct qemu_alarm_timer *t);
899 static void rtc_stop_timer(struct qemu_alarm_timer *t);
901 #endif /* __linux__ */
903 #endif /* _WIN32 */
905 /* Correlation between real and virtual time is always going to be
906 fairly approximate, so ignore small variation.
907 When the guest is idle real and virtual time will be aligned in
908 the IO wait loop. */
909 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
911 static void icount_adjust(void)
913 int64_t cur_time;
914 int64_t cur_icount;
915 int64_t delta;
916 static int64_t last_delta;
917 /* If the VM is not running, then do nothing. */
918 if (!vm_running)
919 return;
921 cur_time = cpu_get_clock();
922 cur_icount = qemu_get_clock(vm_clock);
923 delta = cur_icount - cur_time;
924 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
925 if (delta > 0
926 && last_delta + ICOUNT_WOBBLE < delta * 2
927 && icount_time_shift > 0) {
928 /* The guest is getting too far ahead. Slow time down. */
929 icount_time_shift--;
931 if (delta < 0
932 && last_delta - ICOUNT_WOBBLE > delta * 2
933 && icount_time_shift < MAX_ICOUNT_SHIFT) {
934 /* The guest is getting too far behind. Speed time up. */
935 icount_time_shift++;
937 last_delta = delta;
938 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
941 static void icount_adjust_rt(void * opaque)
943 qemu_mod_timer(icount_rt_timer,
944 qemu_get_clock(rt_clock) + 1000);
945 icount_adjust();
948 static void icount_adjust_vm(void * opaque)
950 qemu_mod_timer(icount_vm_timer,
951 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
952 icount_adjust();
955 static void init_icount_adjust(void)
957 /* Have both realtime and virtual time triggers for speed adjustment.
958 The realtime trigger catches emulated time passing too slowly,
959 the virtual time trigger catches emulated time passing too fast.
960 Realtime triggers occur even when idle, so use them less frequently
961 than VM triggers. */
962 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
963 qemu_mod_timer(icount_rt_timer,
964 qemu_get_clock(rt_clock) + 1000);
965 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
966 qemu_mod_timer(icount_vm_timer,
967 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
970 static struct qemu_alarm_timer alarm_timers[] = {
971 #ifndef _WIN32
972 #ifdef __linux__
973 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
974 dynticks_stop_timer, dynticks_rearm_timer, NULL},
975 /* HPET - if available - is preferred */
976 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
977 /* ...otherwise try RTC */
978 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
979 #endif
980 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
981 #else
982 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
983 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
984 {"win32", 0, win32_start_timer,
985 win32_stop_timer, NULL, &alarm_win32_data},
986 #endif
987 {NULL, }
990 static void show_available_alarms(void)
992 int i;
994 printf("Available alarm timers, in order of precedence:\n");
995 for (i = 0; alarm_timers[i].name; i++)
996 printf("%s\n", alarm_timers[i].name);
999 static void configure_alarms(char const *opt)
1001 int i;
1002 int cur = 0;
1003 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1004 char *arg;
1005 char *name;
1006 struct qemu_alarm_timer tmp;
1008 if (!strcmp(opt, "?")) {
1009 show_available_alarms();
1010 exit(0);
1013 arg = strdup(opt);
1015 /* Reorder the array */
1016 name = strtok(arg, ",");
1017 while (name) {
1018 for (i = 0; i < count && alarm_timers[i].name; i++) {
1019 if (!strcmp(alarm_timers[i].name, name))
1020 break;
1023 if (i == count) {
1024 fprintf(stderr, "Unknown clock %s\n", name);
1025 goto next;
1028 if (i < cur)
1029 /* Ignore */
1030 goto next;
1032 /* Swap */
1033 tmp = alarm_timers[i];
1034 alarm_timers[i] = alarm_timers[cur];
1035 alarm_timers[cur] = tmp;
1037 cur++;
1038 next:
1039 name = strtok(NULL, ",");
1042 free(arg);
1044 if (cur) {
1045 /* Disable remaining timers */
1046 for (i = cur; i < count; i++)
1047 alarm_timers[i].name = NULL;
1048 } else {
1049 show_available_alarms();
1050 exit(1);
1054 QEMUClock *rt_clock;
1055 QEMUClock *vm_clock;
1057 static QEMUTimer *active_timers[2];
1059 static QEMUClock *qemu_new_clock(int type)
1061 QEMUClock *clock;
1062 clock = qemu_mallocz(sizeof(QEMUClock));
1063 if (!clock)
1064 return NULL;
1065 clock->type = type;
1066 return clock;
1069 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1071 QEMUTimer *ts;
1073 ts = qemu_mallocz(sizeof(QEMUTimer));
1074 ts->clock = clock;
1075 ts->cb = cb;
1076 ts->opaque = opaque;
1077 return ts;
1080 void qemu_free_timer(QEMUTimer *ts)
1082 qemu_free(ts);
1085 /* stop a timer, but do not dealloc it */
1086 void qemu_del_timer(QEMUTimer *ts)
1088 QEMUTimer **pt, *t;
1090 /* NOTE: this code must be signal safe because
1091 qemu_timer_expired() can be called from a signal. */
1092 pt = &active_timers[ts->clock->type];
1093 for(;;) {
1094 t = *pt;
1095 if (!t)
1096 break;
1097 if (t == ts) {
1098 *pt = t->next;
1099 break;
1101 pt = &t->next;
1105 /* modify the current timer so that it will be fired when current_time
1106 >= expire_time. The corresponding callback will be called. */
1107 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1109 QEMUTimer **pt, *t;
1111 qemu_del_timer(ts);
1113 /* add the timer in the sorted list */
1114 /* NOTE: this code must be signal safe because
1115 qemu_timer_expired() can be called from a signal. */
1116 pt = &active_timers[ts->clock->type];
1117 for(;;) {
1118 t = *pt;
1119 if (!t)
1120 break;
1121 if (t->expire_time > expire_time)
1122 break;
1123 pt = &t->next;
1125 ts->expire_time = expire_time;
1126 ts->next = *pt;
1127 *pt = ts;
1129 /* Rearm if necessary */
1130 if (pt == &active_timers[ts->clock->type]) {
1131 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1132 qemu_rearm_alarm_timer(alarm_timer);
1134 /* Interrupt execution to force deadline recalculation. */
1135 if (use_icount && cpu_single_env) {
1136 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1141 int qemu_timer_pending(QEMUTimer *ts)
1143 QEMUTimer *t;
1144 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1145 if (t == ts)
1146 return 1;
1148 return 0;
1151 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1153 if (!timer_head)
1154 return 0;
1155 return (timer_head->expire_time <= current_time);
1158 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1160 QEMUTimer *ts;
1162 for(;;) {
1163 ts = *ptimer_head;
1164 if (!ts || ts->expire_time > current_time)
1165 break;
1166 /* remove timer from the list before calling the callback */
1167 *ptimer_head = ts->next;
1168 ts->next = NULL;
1170 /* run the callback (the timer list can be modified) */
1171 ts->cb(ts->opaque);
1175 int64_t qemu_get_clock(QEMUClock *clock)
1177 switch(clock->type) {
1178 case QEMU_TIMER_REALTIME:
1179 return get_clock() / 1000000;
1180 default:
1181 case QEMU_TIMER_VIRTUAL:
1182 if (use_icount) {
1183 return cpu_get_icount();
1184 } else {
1185 return cpu_get_clock();
1190 static void init_timers(void)
1192 init_get_clock();
1193 ticks_per_sec = QEMU_TIMER_BASE;
1194 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1195 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1198 /* save a timer */
1199 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1201 uint64_t expire_time;
1203 if (qemu_timer_pending(ts)) {
1204 expire_time = ts->expire_time;
1205 } else {
1206 expire_time = -1;
1208 qemu_put_be64(f, expire_time);
1211 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1213 uint64_t expire_time;
1215 expire_time = qemu_get_be64(f);
1216 if (expire_time != -1) {
1217 qemu_mod_timer(ts, expire_time);
1218 } else {
1219 qemu_del_timer(ts);
1223 static void timer_save(QEMUFile *f, void *opaque)
1225 if (cpu_ticks_enabled) {
1226 hw_error("cannot save state if virtual timers are running");
1228 qemu_put_be64(f, cpu_ticks_offset);
1229 qemu_put_be64(f, ticks_per_sec);
1230 qemu_put_be64(f, cpu_clock_offset);
1233 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1235 if (version_id != 1 && version_id != 2)
1236 return -EINVAL;
1237 if (cpu_ticks_enabled) {
1238 return -EINVAL;
1240 cpu_ticks_offset=qemu_get_be64(f);
1241 ticks_per_sec=qemu_get_be64(f);
1242 if (version_id == 2) {
1243 cpu_clock_offset=qemu_get_be64(f);
1245 return 0;
1248 #ifdef _WIN32
1249 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1250 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1251 #else
1252 static void host_alarm_handler(int host_signum)
1253 #endif
1255 #if 0
1256 #define DISP_FREQ 1000
1258 static int64_t delta_min = INT64_MAX;
1259 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1260 static int count;
1261 ti = qemu_get_clock(vm_clock);
1262 if (last_clock != 0) {
1263 delta = ti - last_clock;
1264 if (delta < delta_min)
1265 delta_min = delta;
1266 if (delta > delta_max)
1267 delta_max = delta;
1268 delta_cum += delta;
1269 if (++count == DISP_FREQ) {
1270 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1271 muldiv64(delta_min, 1000000, ticks_per_sec),
1272 muldiv64(delta_max, 1000000, ticks_per_sec),
1273 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1274 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1275 count = 0;
1276 delta_min = INT64_MAX;
1277 delta_max = 0;
1278 delta_cum = 0;
1281 last_clock = ti;
1283 #endif
1284 if (alarm_has_dynticks(alarm_timer) ||
1285 (!use_icount &&
1286 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1287 qemu_get_clock(vm_clock))) ||
1288 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1289 qemu_get_clock(rt_clock))) {
1290 #ifdef _WIN32
1291 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1292 SetEvent(data->host_alarm);
1293 #endif
1294 CPUState *env = next_cpu;
1296 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1298 if (env) {
1299 /* stop the currently executing cpu because a timer occured */
1300 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1301 #ifdef USE_KQEMU
1302 if (env->kqemu_enabled) {
1303 kqemu_cpu_interrupt(env);
1305 #endif
1307 event_pending = 1;
1311 static int64_t qemu_next_deadline(void)
1313 int64_t delta;
1315 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1316 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1317 qemu_get_clock(vm_clock);
1318 } else {
1319 /* To avoid problems with overflow limit this to 2^32. */
1320 delta = INT32_MAX;
1323 if (delta < 0)
1324 delta = 0;
1326 return delta;
1329 static uint64_t qemu_next_deadline_dyntick(void)
1331 int64_t delta;
1332 int64_t rtdelta;
1334 if (use_icount)
1335 delta = INT32_MAX;
1336 else
1337 delta = (qemu_next_deadline() + 999) / 1000;
1339 if (active_timers[QEMU_TIMER_REALTIME]) {
1340 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1341 qemu_get_clock(rt_clock))*1000;
1342 if (rtdelta < delta)
1343 delta = rtdelta;
1346 if (delta < MIN_TIMER_REARM_US)
1347 delta = MIN_TIMER_REARM_US;
1349 return delta;
1352 #ifndef _WIN32
1354 #if defined(__linux__)
1356 #define RTC_FREQ 1024
1358 static void enable_sigio_timer(int fd)
1360 struct sigaction act;
1362 /* timer signal */
1363 sigfillset(&act.sa_mask);
1364 act.sa_flags = 0;
1365 act.sa_handler = host_alarm_handler;
1367 sigaction(SIGIO, &act, NULL);
1368 fcntl(fd, F_SETFL, O_ASYNC);
1369 fcntl(fd, F_SETOWN, getpid());
1372 static int hpet_start_timer(struct qemu_alarm_timer *t)
1374 struct hpet_info info;
1375 int r, fd;
1377 fd = open("/dev/hpet", O_RDONLY);
1378 if (fd < 0)
1379 return -1;
1381 /* Set frequency */
1382 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1383 if (r < 0) {
1384 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1385 "error, but for better emulation accuracy type:\n"
1386 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1387 goto fail;
1390 /* Check capabilities */
1391 r = ioctl(fd, HPET_INFO, &info);
1392 if (r < 0)
1393 goto fail;
1395 /* Enable periodic mode */
1396 r = ioctl(fd, HPET_EPI, 0);
1397 if (info.hi_flags && (r < 0))
1398 goto fail;
1400 /* Enable interrupt */
1401 r = ioctl(fd, HPET_IE_ON, 0);
1402 if (r < 0)
1403 goto fail;
1405 enable_sigio_timer(fd);
1406 t->priv = (void *)(long)fd;
1408 return 0;
1409 fail:
1410 close(fd);
1411 return -1;
1414 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1416 int fd = (long)t->priv;
1418 close(fd);
1421 static int rtc_start_timer(struct qemu_alarm_timer *t)
1423 int rtc_fd;
1424 unsigned long current_rtc_freq = 0;
1426 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1427 if (rtc_fd < 0)
1428 return -1;
1429 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1430 if (current_rtc_freq != RTC_FREQ &&
1431 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1432 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1433 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1434 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1435 goto fail;
1437 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1438 fail:
1439 close(rtc_fd);
1440 return -1;
1443 enable_sigio_timer(rtc_fd);
1445 t->priv = (void *)(long)rtc_fd;
1447 return 0;
1450 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1452 int rtc_fd = (long)t->priv;
1454 close(rtc_fd);
1457 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1459 struct sigevent ev;
1460 timer_t host_timer;
1461 struct sigaction act;
1463 sigfillset(&act.sa_mask);
1464 act.sa_flags = 0;
1465 act.sa_handler = host_alarm_handler;
1467 sigaction(SIGALRM, &act, NULL);
1469 ev.sigev_value.sival_int = 0;
1470 ev.sigev_notify = SIGEV_SIGNAL;
1471 ev.sigev_signo = SIGALRM;
1473 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1474 perror("timer_create");
1476 /* disable dynticks */
1477 fprintf(stderr, "Dynamic Ticks disabled\n");
1479 return -1;
1482 t->priv = (void *)host_timer;
1484 return 0;
1487 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1489 timer_t host_timer = (timer_t)t->priv;
1491 timer_delete(host_timer);
1494 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1496 timer_t host_timer = (timer_t)t->priv;
1497 struct itimerspec timeout;
1498 int64_t nearest_delta_us = INT64_MAX;
1499 int64_t current_us;
1501 if (!active_timers[QEMU_TIMER_REALTIME] &&
1502 !active_timers[QEMU_TIMER_VIRTUAL])
1503 return;
1505 nearest_delta_us = qemu_next_deadline_dyntick();
1507 /* check whether a timer is already running */
1508 if (timer_gettime(host_timer, &timeout)) {
1509 perror("gettime");
1510 fprintf(stderr, "Internal timer error: aborting\n");
1511 exit(1);
1513 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1514 if (current_us && current_us <= nearest_delta_us)
1515 return;
1517 timeout.it_interval.tv_sec = 0;
1518 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1519 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1520 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1521 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1522 perror("settime");
1523 fprintf(stderr, "Internal timer error: aborting\n");
1524 exit(1);
1528 #endif /* defined(__linux__) */
1530 static int unix_start_timer(struct qemu_alarm_timer *t)
1532 struct sigaction act;
1533 struct itimerval itv;
1534 int err;
1536 /* timer signal */
1537 sigfillset(&act.sa_mask);
1538 act.sa_flags = 0;
1539 act.sa_handler = host_alarm_handler;
1541 sigaction(SIGALRM, &act, NULL);
1543 itv.it_interval.tv_sec = 0;
1544 /* for i386 kernel 2.6 to get 1 ms */
1545 itv.it_interval.tv_usec = 999;
1546 itv.it_value.tv_sec = 0;
1547 itv.it_value.tv_usec = 10 * 1000;
1549 err = setitimer(ITIMER_REAL, &itv, NULL);
1550 if (err)
1551 return -1;
1553 return 0;
1556 static void unix_stop_timer(struct qemu_alarm_timer *t)
1558 struct itimerval itv;
1560 memset(&itv, 0, sizeof(itv));
1561 setitimer(ITIMER_REAL, &itv, NULL);
1564 #endif /* !defined(_WIN32) */
1566 #ifdef _WIN32
1568 static int win32_start_timer(struct qemu_alarm_timer *t)
1570 TIMECAPS tc;
1571 struct qemu_alarm_win32 *data = t->priv;
1572 UINT flags;
1574 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1575 if (!data->host_alarm) {
1576 perror("Failed CreateEvent");
1577 return -1;
1580 memset(&tc, 0, sizeof(tc));
1581 timeGetDevCaps(&tc, sizeof(tc));
1583 if (data->period < tc.wPeriodMin)
1584 data->period = tc.wPeriodMin;
1586 timeBeginPeriod(data->period);
1588 flags = TIME_CALLBACK_FUNCTION;
1589 if (alarm_has_dynticks(t))
1590 flags |= TIME_ONESHOT;
1591 else
1592 flags |= TIME_PERIODIC;
1594 data->timerId = timeSetEvent(1, // interval (ms)
1595 data->period, // resolution
1596 host_alarm_handler, // function
1597 (DWORD)t, // parameter
1598 flags);
1600 if (!data->timerId) {
1601 perror("Failed to initialize win32 alarm timer");
1603 timeEndPeriod(data->period);
1604 CloseHandle(data->host_alarm);
1605 return -1;
1608 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1610 return 0;
1613 static void win32_stop_timer(struct qemu_alarm_timer *t)
1615 struct qemu_alarm_win32 *data = t->priv;
1617 timeKillEvent(data->timerId);
1618 timeEndPeriod(data->period);
1620 CloseHandle(data->host_alarm);
1623 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1625 struct qemu_alarm_win32 *data = t->priv;
1626 uint64_t nearest_delta_us;
1628 if (!active_timers[QEMU_TIMER_REALTIME] &&
1629 !active_timers[QEMU_TIMER_VIRTUAL])
1630 return;
1632 nearest_delta_us = qemu_next_deadline_dyntick();
1633 nearest_delta_us /= 1000;
1635 timeKillEvent(data->timerId);
1637 data->timerId = timeSetEvent(1,
1638 data->period,
1639 host_alarm_handler,
1640 (DWORD)t,
1641 TIME_ONESHOT | TIME_PERIODIC);
1643 if (!data->timerId) {
1644 perror("Failed to re-arm win32 alarm timer");
1646 timeEndPeriod(data->period);
1647 CloseHandle(data->host_alarm);
1648 exit(1);
1652 #endif /* _WIN32 */
1654 static void init_timer_alarm(void)
1656 struct qemu_alarm_timer *t;
1657 int i, err = -1;
1659 for (i = 0; alarm_timers[i].name; i++) {
1660 t = &alarm_timers[i];
1662 err = t->start(t);
1663 if (!err)
1664 break;
1667 if (err) {
1668 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1669 fprintf(stderr, "Terminating\n");
1670 exit(1);
1673 alarm_timer = t;
1676 static void quit_timers(void)
1678 alarm_timer->stop(alarm_timer);
1679 alarm_timer = NULL;
1682 /***********************************************************/
1683 /* host time/date access */
1684 void qemu_get_timedate(struct tm *tm, int offset)
1686 time_t ti;
1687 struct tm *ret;
1689 time(&ti);
1690 ti += offset;
1691 if (rtc_date_offset == -1) {
1692 if (rtc_utc)
1693 ret = gmtime(&ti);
1694 else
1695 ret = localtime(&ti);
1696 } else {
1697 ti -= rtc_date_offset;
1698 ret = gmtime(&ti);
1701 memcpy(tm, ret, sizeof(struct tm));
1704 int qemu_timedate_diff(struct tm *tm)
1706 time_t seconds;
1708 if (rtc_date_offset == -1)
1709 if (rtc_utc)
1710 seconds = mktimegm(tm);
1711 else
1712 seconds = mktime(tm);
1713 else
1714 seconds = mktimegm(tm) + rtc_date_offset;
1716 return seconds - time(NULL);
1719 /***********************************************************/
1720 /* character device */
1722 static void qemu_chr_event(CharDriverState *s, int event)
1724 if (!s->chr_event)
1725 return;
1726 s->chr_event(s->handler_opaque, event);
1729 static void qemu_chr_reset_bh(void *opaque)
1731 CharDriverState *s = opaque;
1732 qemu_chr_event(s, CHR_EVENT_RESET);
1733 qemu_bh_delete(s->bh);
1734 s->bh = NULL;
1737 void qemu_chr_reset(CharDriverState *s)
1739 if (s->bh == NULL) {
1740 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1741 qemu_bh_schedule(s->bh);
1745 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1747 return s->chr_write(s, buf, len);
1750 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1752 if (!s->chr_ioctl)
1753 return -ENOTSUP;
1754 return s->chr_ioctl(s, cmd, arg);
1757 int qemu_chr_can_read(CharDriverState *s)
1759 if (!s->chr_can_read)
1760 return 0;
1761 return s->chr_can_read(s->handler_opaque);
1764 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1766 s->chr_read(s->handler_opaque, buf, len);
1769 void qemu_chr_accept_input(CharDriverState *s)
1771 if (s->chr_accept_input)
1772 s->chr_accept_input(s);
1775 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1777 char buf[4096];
1778 va_list ap;
1779 va_start(ap, fmt);
1780 vsnprintf(buf, sizeof(buf), fmt, ap);
1781 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1782 va_end(ap);
1785 void qemu_chr_send_event(CharDriverState *s, int event)
1787 if (s->chr_send_event)
1788 s->chr_send_event(s, event);
1791 void qemu_chr_add_handlers(CharDriverState *s,
1792 IOCanRWHandler *fd_can_read,
1793 IOReadHandler *fd_read,
1794 IOEventHandler *fd_event,
1795 void *opaque)
1797 s->chr_can_read = fd_can_read;
1798 s->chr_read = fd_read;
1799 s->chr_event = fd_event;
1800 s->handler_opaque = opaque;
1801 if (s->chr_update_read_handler)
1802 s->chr_update_read_handler(s);
1805 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1807 return len;
1810 static CharDriverState *qemu_chr_open_null(void)
1812 CharDriverState *chr;
1814 chr = qemu_mallocz(sizeof(CharDriverState));
1815 if (!chr)
1816 return NULL;
1817 chr->chr_write = null_chr_write;
1818 return chr;
1821 /* MUX driver for serial I/O splitting */
1822 static int term_timestamps;
1823 static int64_t term_timestamps_start;
1824 #define MAX_MUX 4
1825 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1826 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1827 typedef struct {
1828 IOCanRWHandler *chr_can_read[MAX_MUX];
1829 IOReadHandler *chr_read[MAX_MUX];
1830 IOEventHandler *chr_event[MAX_MUX];
1831 void *ext_opaque[MAX_MUX];
1832 CharDriverState *drv;
1833 unsigned char buffer[MUX_BUFFER_SIZE];
1834 int prod;
1835 int cons;
1836 int mux_cnt;
1837 int term_got_escape;
1838 int max_size;
1839 } MuxDriver;
1842 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1844 MuxDriver *d = chr->opaque;
1845 int ret;
1846 if (!term_timestamps) {
1847 ret = d->drv->chr_write(d->drv, buf, len);
1848 } else {
1849 int i;
1851 ret = 0;
1852 for(i = 0; i < len; i++) {
1853 ret += d->drv->chr_write(d->drv, buf+i, 1);
1854 if (buf[i] == '\n') {
1855 char buf1[64];
1856 int64_t ti;
1857 int secs;
1859 ti = get_clock();
1860 if (term_timestamps_start == -1)
1861 term_timestamps_start = ti;
1862 ti -= term_timestamps_start;
1863 secs = ti / 1000000000;
1864 snprintf(buf1, sizeof(buf1),
1865 "[%02d:%02d:%02d.%03d] ",
1866 secs / 3600,
1867 (secs / 60) % 60,
1868 secs % 60,
1869 (int)((ti / 1000000) % 1000));
1870 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1874 return ret;
1877 static char *mux_help[] = {
1878 "% h print this help\n\r",
1879 "% x exit emulator\n\r",
1880 "% s save disk data back to file (if -snapshot)\n\r",
1881 "% t toggle console timestamps\n\r"
1882 "% b send break (magic sysrq)\n\r",
1883 "% c switch between console and monitor\n\r",
1884 "% % sends %\n\r",
1885 NULL
1888 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1889 static void mux_print_help(CharDriverState *chr)
1891 int i, j;
1892 char ebuf[15] = "Escape-Char";
1893 char cbuf[50] = "\n\r";
1895 if (term_escape_char > 0 && term_escape_char < 26) {
1896 sprintf(cbuf,"\n\r");
1897 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1898 } else {
1899 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1900 term_escape_char);
1902 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1903 for (i = 0; mux_help[i] != NULL; i++) {
1904 for (j=0; mux_help[i][j] != '\0'; j++) {
1905 if (mux_help[i][j] == '%')
1906 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1907 else
1908 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1913 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1915 if (d->term_got_escape) {
1916 d->term_got_escape = 0;
1917 if (ch == term_escape_char)
1918 goto send_char;
1919 switch(ch) {
1920 case '?':
1921 case 'h':
1922 mux_print_help(chr);
1923 break;
1924 case 'x':
1926 char *term = "QEMU: Terminated\n\r";
1927 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1928 exit(0);
1929 break;
1931 case 's':
1933 int i;
1934 for (i = 0; i < nb_drives; i++) {
1935 bdrv_commit(drives_table[i].bdrv);
1938 break;
1939 case 'b':
1940 qemu_chr_event(chr, CHR_EVENT_BREAK);
1941 break;
1942 case 'c':
1943 /* Switch to the next registered device */
1944 chr->focus++;
1945 if (chr->focus >= d->mux_cnt)
1946 chr->focus = 0;
1947 break;
1948 case 't':
1949 term_timestamps = !term_timestamps;
1950 term_timestamps_start = -1;
1951 break;
1953 } else if (ch == term_escape_char) {
1954 d->term_got_escape = 1;
1955 } else {
1956 send_char:
1957 return 1;
1959 return 0;
1962 static void mux_chr_accept_input(CharDriverState *chr)
1964 int m = chr->focus;
1965 MuxDriver *d = chr->opaque;
1967 while (d->prod != d->cons &&
1968 d->chr_can_read[m] &&
1969 d->chr_can_read[m](d->ext_opaque[m])) {
1970 d->chr_read[m](d->ext_opaque[m],
1971 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1975 static int mux_chr_can_read(void *opaque)
1977 CharDriverState *chr = opaque;
1978 MuxDriver *d = chr->opaque;
1980 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1981 return 1;
1982 if (d->chr_can_read[chr->focus])
1983 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1984 return 0;
1987 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1989 CharDriverState *chr = opaque;
1990 MuxDriver *d = chr->opaque;
1991 int m = chr->focus;
1992 int i;
1994 mux_chr_accept_input (opaque);
1996 for(i = 0; i < size; i++)
1997 if (mux_proc_byte(chr, d, buf[i])) {
1998 if (d->prod == d->cons &&
1999 d->chr_can_read[m] &&
2000 d->chr_can_read[m](d->ext_opaque[m]))
2001 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2002 else
2003 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2007 static void mux_chr_event(void *opaque, int event)
2009 CharDriverState *chr = opaque;
2010 MuxDriver *d = chr->opaque;
2011 int i;
2013 /* Send the event to all registered listeners */
2014 for (i = 0; i < d->mux_cnt; i++)
2015 if (d->chr_event[i])
2016 d->chr_event[i](d->ext_opaque[i], event);
2019 static void mux_chr_update_read_handler(CharDriverState *chr)
2021 MuxDriver *d = chr->opaque;
2023 if (d->mux_cnt >= MAX_MUX) {
2024 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2025 return;
2027 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2028 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2029 d->chr_read[d->mux_cnt] = chr->chr_read;
2030 d->chr_event[d->mux_cnt] = chr->chr_event;
2031 /* Fix up the real driver with mux routines */
2032 if (d->mux_cnt == 0) {
2033 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2034 mux_chr_event, chr);
2036 chr->focus = d->mux_cnt;
2037 d->mux_cnt++;
2040 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2042 CharDriverState *chr;
2043 MuxDriver *d;
2045 chr = qemu_mallocz(sizeof(CharDriverState));
2046 if (!chr)
2047 return NULL;
2048 d = qemu_mallocz(sizeof(MuxDriver));
2049 if (!d) {
2050 free(chr);
2051 return NULL;
2054 chr->opaque = d;
2055 d->drv = drv;
2056 chr->focus = -1;
2057 chr->chr_write = mux_chr_write;
2058 chr->chr_update_read_handler = mux_chr_update_read_handler;
2059 chr->chr_accept_input = mux_chr_accept_input;
2060 return chr;
2064 #ifdef _WIN32
2066 static void socket_cleanup(void)
2068 WSACleanup();
2071 static int socket_init(void)
2073 WSADATA Data;
2074 int ret, err;
2076 ret = WSAStartup(MAKEWORD(2,2), &Data);
2077 if (ret != 0) {
2078 err = WSAGetLastError();
2079 fprintf(stderr, "WSAStartup: %d\n", err);
2080 return -1;
2082 atexit(socket_cleanup);
2083 return 0;
2086 static int send_all(int fd, const uint8_t *buf, int len1)
2088 int ret, len;
2090 len = len1;
2091 while (len > 0) {
2092 ret = send(fd, buf, len, 0);
2093 if (ret < 0) {
2094 int errno;
2095 errno = WSAGetLastError();
2096 if (errno != WSAEWOULDBLOCK) {
2097 return -1;
2099 } else if (ret == 0) {
2100 break;
2101 } else {
2102 buf += ret;
2103 len -= ret;
2106 return len1 - len;
2109 void socket_set_nonblock(int fd)
2111 unsigned long opt = 1;
2112 ioctlsocket(fd, FIONBIO, &opt);
2115 #else
2117 static int unix_write(int fd, const uint8_t *buf, int len1)
2119 int ret, len;
2121 len = len1;
2122 while (len > 0) {
2123 ret = write(fd, buf, len);
2124 if (ret < 0) {
2125 if (errno != EINTR && errno != EAGAIN)
2126 return -1;
2127 } else if (ret == 0) {
2128 break;
2129 } else {
2130 buf += ret;
2131 len -= ret;
2134 return len1 - len;
2137 static inline int send_all(int fd, const uint8_t *buf, int len1)
2139 return unix_write(fd, buf, len1);
2142 void socket_set_nonblock(int fd)
2144 fcntl(fd, F_SETFL, O_NONBLOCK);
2146 #endif /* !_WIN32 */
2148 #ifndef _WIN32
2150 typedef struct {
2151 int fd_in, fd_out;
2152 int max_size;
2153 } FDCharDriver;
2155 #define STDIO_MAX_CLIENTS 1
2156 static int stdio_nb_clients = 0;
2158 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2160 FDCharDriver *s = chr->opaque;
2161 return unix_write(s->fd_out, buf, len);
2164 static int fd_chr_read_poll(void *opaque)
2166 CharDriverState *chr = opaque;
2167 FDCharDriver *s = chr->opaque;
2169 s->max_size = qemu_chr_can_read(chr);
2170 return s->max_size;
2173 static void fd_chr_read(void *opaque)
2175 CharDriverState *chr = opaque;
2176 FDCharDriver *s = chr->opaque;
2177 int size, len;
2178 uint8_t buf[1024];
2180 len = sizeof(buf);
2181 if (len > s->max_size)
2182 len = s->max_size;
2183 if (len == 0)
2184 return;
2185 size = read(s->fd_in, buf, len);
2186 if (size == 0) {
2187 /* FD has been closed. Remove it from the active list. */
2188 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2189 return;
2191 if (size > 0) {
2192 qemu_chr_read(chr, buf, size);
2196 static void fd_chr_update_read_handler(CharDriverState *chr)
2198 FDCharDriver *s = chr->opaque;
2200 if (s->fd_in >= 0) {
2201 if (nographic && s->fd_in == 0) {
2202 } else {
2203 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2204 fd_chr_read, NULL, chr);
2209 static void fd_chr_close(struct CharDriverState *chr)
2211 FDCharDriver *s = chr->opaque;
2213 if (s->fd_in >= 0) {
2214 if (nographic && s->fd_in == 0) {
2215 } else {
2216 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2220 qemu_free(s);
2223 /* open a character device to a unix fd */
2224 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2226 CharDriverState *chr;
2227 FDCharDriver *s;
2229 chr = qemu_mallocz(sizeof(CharDriverState));
2230 if (!chr)
2231 return NULL;
2232 s = qemu_mallocz(sizeof(FDCharDriver));
2233 if (!s) {
2234 free(chr);
2235 return NULL;
2237 s->fd_in = fd_in;
2238 s->fd_out = fd_out;
2239 chr->opaque = s;
2240 chr->chr_write = fd_chr_write;
2241 chr->chr_update_read_handler = fd_chr_update_read_handler;
2242 chr->chr_close = fd_chr_close;
2244 qemu_chr_reset(chr);
2246 return chr;
2249 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2251 int fd_out;
2253 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2254 if (fd_out < 0)
2255 return NULL;
2256 return qemu_chr_open_fd(-1, fd_out);
2259 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2261 int fd_in, fd_out;
2262 char filename_in[256], filename_out[256];
2264 snprintf(filename_in, 256, "%s.in", filename);
2265 snprintf(filename_out, 256, "%s.out", filename);
2266 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2267 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2268 if (fd_in < 0 || fd_out < 0) {
2269 if (fd_in >= 0)
2270 close(fd_in);
2271 if (fd_out >= 0)
2272 close(fd_out);
2273 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2274 if (fd_in < 0)
2275 return NULL;
2277 return qemu_chr_open_fd(fd_in, fd_out);
2281 /* for STDIO, we handle the case where several clients use it
2282 (nographic mode) */
2284 #define TERM_FIFO_MAX_SIZE 1
2286 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2287 static int term_fifo_size;
2289 static int stdio_read_poll(void *opaque)
2291 CharDriverState *chr = opaque;
2293 /* try to flush the queue if needed */
2294 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2295 qemu_chr_read(chr, term_fifo, 1);
2296 term_fifo_size = 0;
2298 /* see if we can absorb more chars */
2299 if (term_fifo_size == 0)
2300 return 1;
2301 else
2302 return 0;
2305 static void stdio_read(void *opaque)
2307 int size;
2308 uint8_t buf[1];
2309 CharDriverState *chr = opaque;
2311 size = read(0, buf, 1);
2312 if (size == 0) {
2313 /* stdin has been closed. Remove it from the active list. */
2314 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2315 return;
2317 if (size > 0) {
2318 if (qemu_chr_can_read(chr) > 0) {
2319 qemu_chr_read(chr, buf, 1);
2320 } else if (term_fifo_size == 0) {
2321 term_fifo[term_fifo_size++] = buf[0];
2326 /* init terminal so that we can grab keys */
2327 static struct termios oldtty;
2328 static int old_fd0_flags;
2329 static int term_atexit_done;
2331 static void term_exit(void)
2333 tcsetattr (0, TCSANOW, &oldtty);
2334 fcntl(0, F_SETFL, old_fd0_flags);
2337 static void term_init(void)
2339 struct termios tty;
2341 tcgetattr (0, &tty);
2342 oldtty = tty;
2343 old_fd0_flags = fcntl(0, F_GETFL);
2345 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2346 |INLCR|IGNCR|ICRNL|IXON);
2347 tty.c_oflag |= OPOST;
2348 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2349 /* if graphical mode, we allow Ctrl-C handling */
2350 if (nographic)
2351 tty.c_lflag &= ~ISIG;
2352 tty.c_cflag &= ~(CSIZE|PARENB);
2353 tty.c_cflag |= CS8;
2354 tty.c_cc[VMIN] = 1;
2355 tty.c_cc[VTIME] = 0;
2357 tcsetattr (0, TCSANOW, &tty);
2359 if (!term_atexit_done++)
2360 atexit(term_exit);
2362 fcntl(0, F_SETFL, O_NONBLOCK);
2365 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2367 term_exit();
2368 stdio_nb_clients--;
2369 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2370 fd_chr_close(chr);
2373 static CharDriverState *qemu_chr_open_stdio(void)
2375 CharDriverState *chr;
2377 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2378 return NULL;
2379 chr = qemu_chr_open_fd(0, 1);
2380 chr->chr_close = qemu_chr_close_stdio;
2381 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2382 stdio_nb_clients++;
2383 term_init();
2385 return chr;
2388 #ifdef __sun__
2389 /* Once Solaris has openpty(), this is going to be removed. */
2390 int openpty(int *amaster, int *aslave, char *name,
2391 struct termios *termp, struct winsize *winp)
2393 const char *slave;
2394 int mfd = -1, sfd = -1;
2396 *amaster = *aslave = -1;
2398 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2399 if (mfd < 0)
2400 goto err;
2402 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2403 goto err;
2405 if ((slave = ptsname(mfd)) == NULL)
2406 goto err;
2408 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2409 goto err;
2411 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2412 (termp != NULL && tcgetattr(sfd, termp) < 0))
2413 goto err;
2415 if (amaster)
2416 *amaster = mfd;
2417 if (aslave)
2418 *aslave = sfd;
2419 if (winp)
2420 ioctl(sfd, TIOCSWINSZ, winp);
2422 return 0;
2424 err:
2425 if (sfd != -1)
2426 close(sfd);
2427 close(mfd);
2428 return -1;
2431 void cfmakeraw (struct termios *termios_p)
2433 termios_p->c_iflag &=
2434 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2435 termios_p->c_oflag &= ~OPOST;
2436 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2437 termios_p->c_cflag &= ~(CSIZE|PARENB);
2438 termios_p->c_cflag |= CS8;
2440 termios_p->c_cc[VMIN] = 0;
2441 termios_p->c_cc[VTIME] = 0;
2443 #endif
2445 #if defined(__linux__) || defined(__sun__)
2446 static CharDriverState *qemu_chr_open_pty(void)
2448 struct termios tty;
2449 int master_fd, slave_fd;
2451 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
2452 return NULL;
2455 /* Set raw attributes on the pty. */
2456 cfmakeraw(&tty);
2457 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2459 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
2460 return qemu_chr_open_fd(master_fd, master_fd);
2463 static void tty_serial_init(int fd, int speed,
2464 int parity, int data_bits, int stop_bits)
2466 struct termios tty;
2467 speed_t spd;
2469 #if 0
2470 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2471 speed, parity, data_bits, stop_bits);
2472 #endif
2473 tcgetattr (fd, &tty);
2475 #define MARGIN 1.1
2476 if (speed <= 50 * MARGIN)
2477 spd = B50;
2478 else if (speed <= 75 * MARGIN)
2479 spd = B75;
2480 else if (speed <= 300 * MARGIN)
2481 spd = B300;
2482 else if (speed <= 600 * MARGIN)
2483 spd = B600;
2484 else if (speed <= 1200 * MARGIN)
2485 spd = B1200;
2486 else if (speed <= 2400 * MARGIN)
2487 spd = B2400;
2488 else if (speed <= 4800 * MARGIN)
2489 spd = B4800;
2490 else if (speed <= 9600 * MARGIN)
2491 spd = B9600;
2492 else if (speed <= 19200 * MARGIN)
2493 spd = B19200;
2494 else if (speed <= 38400 * MARGIN)
2495 spd = B38400;
2496 else if (speed <= 57600 * MARGIN)
2497 spd = B57600;
2498 else if (speed <= 115200 * MARGIN)
2499 spd = B115200;
2500 else
2501 spd = B115200;
2503 cfsetispeed(&tty, spd);
2504 cfsetospeed(&tty, spd);
2506 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2507 |INLCR|IGNCR|ICRNL|IXON);
2508 tty.c_oflag |= OPOST;
2509 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2510 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2511 switch(data_bits) {
2512 default:
2513 case 8:
2514 tty.c_cflag |= CS8;
2515 break;
2516 case 7:
2517 tty.c_cflag |= CS7;
2518 break;
2519 case 6:
2520 tty.c_cflag |= CS6;
2521 break;
2522 case 5:
2523 tty.c_cflag |= CS5;
2524 break;
2526 switch(parity) {
2527 default:
2528 case 'N':
2529 break;
2530 case 'E':
2531 tty.c_cflag |= PARENB;
2532 break;
2533 case 'O':
2534 tty.c_cflag |= PARENB | PARODD;
2535 break;
2537 if (stop_bits == 2)
2538 tty.c_cflag |= CSTOPB;
2540 tcsetattr (fd, TCSANOW, &tty);
2543 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2545 FDCharDriver *s = chr->opaque;
2547 switch(cmd) {
2548 case CHR_IOCTL_SERIAL_SET_PARAMS:
2550 QEMUSerialSetParams *ssp = arg;
2551 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2552 ssp->data_bits, ssp->stop_bits);
2554 break;
2555 case CHR_IOCTL_SERIAL_SET_BREAK:
2557 int enable = *(int *)arg;
2558 if (enable)
2559 tcsendbreak(s->fd_in, 1);
2561 break;
2562 default:
2563 return -ENOTSUP;
2565 return 0;
2568 static CharDriverState *qemu_chr_open_tty(const char *filename)
2570 CharDriverState *chr;
2571 int fd;
2573 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2574 fcntl(fd, F_SETFL, O_NONBLOCK);
2575 tty_serial_init(fd, 115200, 'N', 8, 1);
2576 chr = qemu_chr_open_fd(fd, fd);
2577 if (!chr) {
2578 close(fd);
2579 return NULL;
2581 chr->chr_ioctl = tty_serial_ioctl;
2582 qemu_chr_reset(chr);
2583 return chr;
2585 #else /* ! __linux__ && ! __sun__ */
2586 static CharDriverState *qemu_chr_open_pty(void)
2588 return NULL;
2590 #endif /* __linux__ || __sun__ */
2592 #if defined(__linux__)
2593 typedef struct {
2594 int fd;
2595 int mode;
2596 } ParallelCharDriver;
2598 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2600 if (s->mode != mode) {
2601 int m = mode;
2602 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2603 return 0;
2604 s->mode = mode;
2606 return 1;
2609 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2611 ParallelCharDriver *drv = chr->opaque;
2612 int fd = drv->fd;
2613 uint8_t b;
2615 switch(cmd) {
2616 case CHR_IOCTL_PP_READ_DATA:
2617 if (ioctl(fd, PPRDATA, &b) < 0)
2618 return -ENOTSUP;
2619 *(uint8_t *)arg = b;
2620 break;
2621 case CHR_IOCTL_PP_WRITE_DATA:
2622 b = *(uint8_t *)arg;
2623 if (ioctl(fd, PPWDATA, &b) < 0)
2624 return -ENOTSUP;
2625 break;
2626 case CHR_IOCTL_PP_READ_CONTROL:
2627 if (ioctl(fd, PPRCONTROL, &b) < 0)
2628 return -ENOTSUP;
2629 /* Linux gives only the lowest bits, and no way to know data
2630 direction! For better compatibility set the fixed upper
2631 bits. */
2632 *(uint8_t *)arg = b | 0xc0;
2633 break;
2634 case CHR_IOCTL_PP_WRITE_CONTROL:
2635 b = *(uint8_t *)arg;
2636 if (ioctl(fd, PPWCONTROL, &b) < 0)
2637 return -ENOTSUP;
2638 break;
2639 case CHR_IOCTL_PP_READ_STATUS:
2640 if (ioctl(fd, PPRSTATUS, &b) < 0)
2641 return -ENOTSUP;
2642 *(uint8_t *)arg = b;
2643 break;
2644 case CHR_IOCTL_PP_EPP_READ_ADDR:
2645 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2646 struct ParallelIOArg *parg = arg;
2647 int n = read(fd, parg->buffer, parg->count);
2648 if (n != parg->count) {
2649 return -EIO;
2652 break;
2653 case CHR_IOCTL_PP_EPP_READ:
2654 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2655 struct ParallelIOArg *parg = arg;
2656 int n = read(fd, parg->buffer, parg->count);
2657 if (n != parg->count) {
2658 return -EIO;
2661 break;
2662 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2663 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2664 struct ParallelIOArg *parg = arg;
2665 int n = write(fd, parg->buffer, parg->count);
2666 if (n != parg->count) {
2667 return -EIO;
2670 break;
2671 case CHR_IOCTL_PP_EPP_WRITE:
2672 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2673 struct ParallelIOArg *parg = arg;
2674 int n = write(fd, parg->buffer, parg->count);
2675 if (n != parg->count) {
2676 return -EIO;
2679 break;
2680 default:
2681 return -ENOTSUP;
2683 return 0;
2686 static void pp_close(CharDriverState *chr)
2688 ParallelCharDriver *drv = chr->opaque;
2689 int fd = drv->fd;
2691 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2692 ioctl(fd, PPRELEASE);
2693 close(fd);
2694 qemu_free(drv);
2697 static CharDriverState *qemu_chr_open_pp(const char *filename)
2699 CharDriverState *chr;
2700 ParallelCharDriver *drv;
2701 int fd;
2703 TFR(fd = open(filename, O_RDWR));
2704 if (fd < 0)
2705 return NULL;
2707 if (ioctl(fd, PPCLAIM) < 0) {
2708 close(fd);
2709 return NULL;
2712 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2713 if (!drv) {
2714 close(fd);
2715 return NULL;
2717 drv->fd = fd;
2718 drv->mode = IEEE1284_MODE_COMPAT;
2720 chr = qemu_mallocz(sizeof(CharDriverState));
2721 if (!chr) {
2722 qemu_free(drv);
2723 close(fd);
2724 return NULL;
2726 chr->chr_write = null_chr_write;
2727 chr->chr_ioctl = pp_ioctl;
2728 chr->chr_close = pp_close;
2729 chr->opaque = drv;
2731 qemu_chr_reset(chr);
2733 return chr;
2735 #endif /* __linux__ */
2737 #else /* _WIN32 */
2739 typedef struct {
2740 int max_size;
2741 HANDLE hcom, hrecv, hsend;
2742 OVERLAPPED orecv, osend;
2743 BOOL fpipe;
2744 DWORD len;
2745 } WinCharState;
2747 #define NSENDBUF 2048
2748 #define NRECVBUF 2048
2749 #define MAXCONNECT 1
2750 #define NTIMEOUT 5000
2752 static int win_chr_poll(void *opaque);
2753 static int win_chr_pipe_poll(void *opaque);
2755 static void win_chr_close(CharDriverState *chr)
2757 WinCharState *s = chr->opaque;
2759 if (s->hsend) {
2760 CloseHandle(s->hsend);
2761 s->hsend = NULL;
2763 if (s->hrecv) {
2764 CloseHandle(s->hrecv);
2765 s->hrecv = NULL;
2767 if (s->hcom) {
2768 CloseHandle(s->hcom);
2769 s->hcom = NULL;
2771 if (s->fpipe)
2772 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2773 else
2774 qemu_del_polling_cb(win_chr_poll, chr);
2777 static int win_chr_init(CharDriverState *chr, const char *filename)
2779 WinCharState *s = chr->opaque;
2780 COMMCONFIG comcfg;
2781 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2782 COMSTAT comstat;
2783 DWORD size;
2784 DWORD err;
2786 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2787 if (!s->hsend) {
2788 fprintf(stderr, "Failed CreateEvent\n");
2789 goto fail;
2791 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2792 if (!s->hrecv) {
2793 fprintf(stderr, "Failed CreateEvent\n");
2794 goto fail;
2797 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2798 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2799 if (s->hcom == INVALID_HANDLE_VALUE) {
2800 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2801 s->hcom = NULL;
2802 goto fail;
2805 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2806 fprintf(stderr, "Failed SetupComm\n");
2807 goto fail;
2810 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2811 size = sizeof(COMMCONFIG);
2812 GetDefaultCommConfig(filename, &comcfg, &size);
2813 comcfg.dcb.DCBlength = sizeof(DCB);
2814 CommConfigDialog(filename, NULL, &comcfg);
2816 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2817 fprintf(stderr, "Failed SetCommState\n");
2818 goto fail;
2821 if (!SetCommMask(s->hcom, EV_ERR)) {
2822 fprintf(stderr, "Failed SetCommMask\n");
2823 goto fail;
2826 cto.ReadIntervalTimeout = MAXDWORD;
2827 if (!SetCommTimeouts(s->hcom, &cto)) {
2828 fprintf(stderr, "Failed SetCommTimeouts\n");
2829 goto fail;
2832 if (!ClearCommError(s->hcom, &err, &comstat)) {
2833 fprintf(stderr, "Failed ClearCommError\n");
2834 goto fail;
2836 qemu_add_polling_cb(win_chr_poll, chr);
2837 return 0;
2839 fail:
2840 win_chr_close(chr);
2841 return -1;
2844 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2846 WinCharState *s = chr->opaque;
2847 DWORD len, ret, size, err;
2849 len = len1;
2850 ZeroMemory(&s->osend, sizeof(s->osend));
2851 s->osend.hEvent = s->hsend;
2852 while (len > 0) {
2853 if (s->hsend)
2854 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2855 else
2856 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2857 if (!ret) {
2858 err = GetLastError();
2859 if (err == ERROR_IO_PENDING) {
2860 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2861 if (ret) {
2862 buf += size;
2863 len -= size;
2864 } else {
2865 break;
2867 } else {
2868 break;
2870 } else {
2871 buf += size;
2872 len -= size;
2875 return len1 - len;
2878 static int win_chr_read_poll(CharDriverState *chr)
2880 WinCharState *s = chr->opaque;
2882 s->max_size = qemu_chr_can_read(chr);
2883 return s->max_size;
2886 static void win_chr_readfile(CharDriverState *chr)
2888 WinCharState *s = chr->opaque;
2889 int ret, err;
2890 uint8_t buf[1024];
2891 DWORD size;
2893 ZeroMemory(&s->orecv, sizeof(s->orecv));
2894 s->orecv.hEvent = s->hrecv;
2895 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2896 if (!ret) {
2897 err = GetLastError();
2898 if (err == ERROR_IO_PENDING) {
2899 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2903 if (size > 0) {
2904 qemu_chr_read(chr, buf, size);
2908 static void win_chr_read(CharDriverState *chr)
2910 WinCharState *s = chr->opaque;
2912 if (s->len > s->max_size)
2913 s->len = s->max_size;
2914 if (s->len == 0)
2915 return;
2917 win_chr_readfile(chr);
2920 static int win_chr_poll(void *opaque)
2922 CharDriverState *chr = opaque;
2923 WinCharState *s = chr->opaque;
2924 COMSTAT status;
2925 DWORD comerr;
2927 ClearCommError(s->hcom, &comerr, &status);
2928 if (status.cbInQue > 0) {
2929 s->len = status.cbInQue;
2930 win_chr_read_poll(chr);
2931 win_chr_read(chr);
2932 return 1;
2934 return 0;
2937 static CharDriverState *qemu_chr_open_win(const char *filename)
2939 CharDriverState *chr;
2940 WinCharState *s;
2942 chr = qemu_mallocz(sizeof(CharDriverState));
2943 if (!chr)
2944 return NULL;
2945 s = qemu_mallocz(sizeof(WinCharState));
2946 if (!s) {
2947 free(chr);
2948 return NULL;
2950 chr->opaque = s;
2951 chr->chr_write = win_chr_write;
2952 chr->chr_close = win_chr_close;
2954 if (win_chr_init(chr, filename) < 0) {
2955 free(s);
2956 free(chr);
2957 return NULL;
2959 qemu_chr_reset(chr);
2960 return chr;
2963 static int win_chr_pipe_poll(void *opaque)
2965 CharDriverState *chr = opaque;
2966 WinCharState *s = chr->opaque;
2967 DWORD size;
2969 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2970 if (size > 0) {
2971 s->len = size;
2972 win_chr_read_poll(chr);
2973 win_chr_read(chr);
2974 return 1;
2976 return 0;
2979 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2981 WinCharState *s = chr->opaque;
2982 OVERLAPPED ov;
2983 int ret;
2984 DWORD size;
2985 char openname[256];
2987 s->fpipe = TRUE;
2989 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2990 if (!s->hsend) {
2991 fprintf(stderr, "Failed CreateEvent\n");
2992 goto fail;
2994 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2995 if (!s->hrecv) {
2996 fprintf(stderr, "Failed CreateEvent\n");
2997 goto fail;
3000 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3001 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3002 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3003 PIPE_WAIT,
3004 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3005 if (s->hcom == INVALID_HANDLE_VALUE) {
3006 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3007 s->hcom = NULL;
3008 goto fail;
3011 ZeroMemory(&ov, sizeof(ov));
3012 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3013 ret = ConnectNamedPipe(s->hcom, &ov);
3014 if (ret) {
3015 fprintf(stderr, "Failed ConnectNamedPipe\n");
3016 goto fail;
3019 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3020 if (!ret) {
3021 fprintf(stderr, "Failed GetOverlappedResult\n");
3022 if (ov.hEvent) {
3023 CloseHandle(ov.hEvent);
3024 ov.hEvent = NULL;
3026 goto fail;
3029 if (ov.hEvent) {
3030 CloseHandle(ov.hEvent);
3031 ov.hEvent = NULL;
3033 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3034 return 0;
3036 fail:
3037 win_chr_close(chr);
3038 return -1;
3042 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3044 CharDriverState *chr;
3045 WinCharState *s;
3047 chr = qemu_mallocz(sizeof(CharDriverState));
3048 if (!chr)
3049 return NULL;
3050 s = qemu_mallocz(sizeof(WinCharState));
3051 if (!s) {
3052 free(chr);
3053 return NULL;
3055 chr->opaque = s;
3056 chr->chr_write = win_chr_write;
3057 chr->chr_close = win_chr_close;
3059 if (win_chr_pipe_init(chr, filename) < 0) {
3060 free(s);
3061 free(chr);
3062 return NULL;
3064 qemu_chr_reset(chr);
3065 return chr;
3068 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3070 CharDriverState *chr;
3071 WinCharState *s;
3073 chr = qemu_mallocz(sizeof(CharDriverState));
3074 if (!chr)
3075 return NULL;
3076 s = qemu_mallocz(sizeof(WinCharState));
3077 if (!s) {
3078 free(chr);
3079 return NULL;
3081 s->hcom = fd_out;
3082 chr->opaque = s;
3083 chr->chr_write = win_chr_write;
3084 qemu_chr_reset(chr);
3085 return chr;
3088 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3090 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3093 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3095 HANDLE fd_out;
3097 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3098 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3099 if (fd_out == INVALID_HANDLE_VALUE)
3100 return NULL;
3102 return qemu_chr_open_win_file(fd_out);
3104 #endif /* !_WIN32 */
3106 /***********************************************************/
3107 /* UDP Net console */
3109 typedef struct {
3110 int fd;
3111 struct sockaddr_in daddr;
3112 uint8_t buf[1024];
3113 int bufcnt;
3114 int bufptr;
3115 int max_size;
3116 } NetCharDriver;
3118 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3120 NetCharDriver *s = chr->opaque;
3122 return sendto(s->fd, buf, len, 0,
3123 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3126 static int udp_chr_read_poll(void *opaque)
3128 CharDriverState *chr = opaque;
3129 NetCharDriver *s = chr->opaque;
3131 s->max_size = qemu_chr_can_read(chr);
3133 /* If there were any stray characters in the queue process them
3134 * first
3136 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3137 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3138 s->bufptr++;
3139 s->max_size = qemu_chr_can_read(chr);
3141 return s->max_size;
3144 static void udp_chr_read(void *opaque)
3146 CharDriverState *chr = opaque;
3147 NetCharDriver *s = chr->opaque;
3149 if (s->max_size == 0)
3150 return;
3151 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3152 s->bufptr = s->bufcnt;
3153 if (s->bufcnt <= 0)
3154 return;
3156 s->bufptr = 0;
3157 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3158 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3159 s->bufptr++;
3160 s->max_size = qemu_chr_can_read(chr);
3164 static void udp_chr_update_read_handler(CharDriverState *chr)
3166 NetCharDriver *s = chr->opaque;
3168 if (s->fd >= 0) {
3169 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3170 udp_chr_read, NULL, chr);
3174 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3175 #ifndef _WIN32
3176 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3177 #endif
3178 int parse_host_src_port(struct sockaddr_in *haddr,
3179 struct sockaddr_in *saddr,
3180 const char *str);
3182 static CharDriverState *qemu_chr_open_udp(const char *def)
3184 CharDriverState *chr = NULL;
3185 NetCharDriver *s = NULL;
3186 int fd = -1;
3187 struct sockaddr_in saddr;
3189 chr = qemu_mallocz(sizeof(CharDriverState));
3190 if (!chr)
3191 goto return_err;
3192 s = qemu_mallocz(sizeof(NetCharDriver));
3193 if (!s)
3194 goto return_err;
3196 fd = socket(PF_INET, SOCK_DGRAM, 0);
3197 if (fd < 0) {
3198 perror("socket(PF_INET, SOCK_DGRAM)");
3199 goto return_err;
3202 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3203 printf("Could not parse: %s\n", def);
3204 goto return_err;
3207 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3209 perror("bind");
3210 goto return_err;
3213 s->fd = fd;
3214 s->bufcnt = 0;
3215 s->bufptr = 0;
3216 chr->opaque = s;
3217 chr->chr_write = udp_chr_write;
3218 chr->chr_update_read_handler = udp_chr_update_read_handler;
3219 return chr;
3221 return_err:
3222 if (chr)
3223 free(chr);
3224 if (s)
3225 free(s);
3226 if (fd >= 0)
3227 closesocket(fd);
3228 return NULL;
3231 /***********************************************************/
3232 /* TCP Net console */
3234 typedef struct {
3235 int fd, listen_fd;
3236 int connected;
3237 int max_size;
3238 int do_telnetopt;
3239 int do_nodelay;
3240 int is_unix;
3241 } TCPCharDriver;
3243 static void tcp_chr_accept(void *opaque);
3245 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3247 TCPCharDriver *s = chr->opaque;
3248 if (s->connected) {
3249 return send_all(s->fd, buf, len);
3250 } else {
3251 /* XXX: indicate an error ? */
3252 return len;
3256 static int tcp_chr_read_poll(void *opaque)
3258 CharDriverState *chr = opaque;
3259 TCPCharDriver *s = chr->opaque;
3260 if (!s->connected)
3261 return 0;
3262 s->max_size = qemu_chr_can_read(chr);
3263 return s->max_size;
3266 #define IAC 255
3267 #define IAC_BREAK 243
3268 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3269 TCPCharDriver *s,
3270 uint8_t *buf, int *size)
3272 /* Handle any telnet client's basic IAC options to satisfy char by
3273 * char mode with no echo. All IAC options will be removed from
3274 * the buf and the do_telnetopt variable will be used to track the
3275 * state of the width of the IAC information.
3277 * IAC commands come in sets of 3 bytes with the exception of the
3278 * "IAC BREAK" command and the double IAC.
3281 int i;
3282 int j = 0;
3284 for (i = 0; i < *size; i++) {
3285 if (s->do_telnetopt > 1) {
3286 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3287 /* Double IAC means send an IAC */
3288 if (j != i)
3289 buf[j] = buf[i];
3290 j++;
3291 s->do_telnetopt = 1;
3292 } else {
3293 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3294 /* Handle IAC break commands by sending a serial break */
3295 qemu_chr_event(chr, CHR_EVENT_BREAK);
3296 s->do_telnetopt++;
3298 s->do_telnetopt++;
3300 if (s->do_telnetopt >= 4) {
3301 s->do_telnetopt = 1;
3303 } else {
3304 if ((unsigned char)buf[i] == IAC) {
3305 s->do_telnetopt = 2;
3306 } else {
3307 if (j != i)
3308 buf[j] = buf[i];
3309 j++;
3313 *size = j;
3316 static void tcp_chr_read(void *opaque)
3318 CharDriverState *chr = opaque;
3319 TCPCharDriver *s = chr->opaque;
3320 uint8_t buf[1024];
3321 int len, size;
3323 if (!s->connected || s->max_size <= 0)
3324 return;
3325 len = sizeof(buf);
3326 if (len > s->max_size)
3327 len = s->max_size;
3328 size = recv(s->fd, buf, len, 0);
3329 if (size == 0) {
3330 /* connection closed */
3331 s->connected = 0;
3332 if (s->listen_fd >= 0) {
3333 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3335 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3336 closesocket(s->fd);
3337 s->fd = -1;
3338 } else if (size > 0) {
3339 if (s->do_telnetopt)
3340 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3341 if (size > 0)
3342 qemu_chr_read(chr, buf, size);
3346 static void tcp_chr_connect(void *opaque)
3348 CharDriverState *chr = opaque;
3349 TCPCharDriver *s = chr->opaque;
3351 s->connected = 1;
3352 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3353 tcp_chr_read, NULL, chr);
3354 qemu_chr_reset(chr);
3357 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3358 static void tcp_chr_telnet_init(int fd)
3360 char buf[3];
3361 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3362 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3363 send(fd, (char *)buf, 3, 0);
3364 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3365 send(fd, (char *)buf, 3, 0);
3366 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3367 send(fd, (char *)buf, 3, 0);
3368 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3369 send(fd, (char *)buf, 3, 0);
3372 static void socket_set_nodelay(int fd)
3374 int val = 1;
3375 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3378 static void tcp_chr_accept(void *opaque)
3380 CharDriverState *chr = opaque;
3381 TCPCharDriver *s = chr->opaque;
3382 struct sockaddr_in saddr;
3383 #ifndef _WIN32
3384 struct sockaddr_un uaddr;
3385 #endif
3386 struct sockaddr *addr;
3387 socklen_t len;
3388 int fd;
3390 for(;;) {
3391 #ifndef _WIN32
3392 if (s->is_unix) {
3393 len = sizeof(uaddr);
3394 addr = (struct sockaddr *)&uaddr;
3395 } else
3396 #endif
3398 len = sizeof(saddr);
3399 addr = (struct sockaddr *)&saddr;
3401 fd = accept(s->listen_fd, addr, &len);
3402 if (fd < 0 && errno != EINTR) {
3403 return;
3404 } else if (fd >= 0) {
3405 if (s->do_telnetopt)
3406 tcp_chr_telnet_init(fd);
3407 break;
3410 socket_set_nonblock(fd);
3411 if (s->do_nodelay)
3412 socket_set_nodelay(fd);
3413 s->fd = fd;
3414 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3415 tcp_chr_connect(chr);
3418 static void tcp_chr_close(CharDriverState *chr)
3420 TCPCharDriver *s = chr->opaque;
3421 if (s->fd >= 0)
3422 closesocket(s->fd);
3423 if (s->listen_fd >= 0)
3424 closesocket(s->listen_fd);
3425 qemu_free(s);
3428 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3429 int is_telnet,
3430 int is_unix)
3432 CharDriverState *chr = NULL;
3433 TCPCharDriver *s = NULL;
3434 int fd = -1, ret, err, val;
3435 int is_listen = 0;
3436 int is_waitconnect = 1;
3437 int do_nodelay = 0;
3438 const char *ptr;
3439 struct sockaddr_in saddr;
3440 #ifndef _WIN32
3441 struct sockaddr_un uaddr;
3442 #endif
3443 struct sockaddr *addr;
3444 socklen_t addrlen;
3446 #ifndef _WIN32
3447 if (is_unix) {
3448 addr = (struct sockaddr *)&uaddr;
3449 addrlen = sizeof(uaddr);
3450 if (parse_unix_path(&uaddr, host_str) < 0)
3451 goto fail;
3452 } else
3453 #endif
3455 addr = (struct sockaddr *)&saddr;
3456 addrlen = sizeof(saddr);
3457 if (parse_host_port(&saddr, host_str) < 0)
3458 goto fail;
3461 ptr = host_str;
3462 while((ptr = strchr(ptr,','))) {
3463 ptr++;
3464 if (!strncmp(ptr,"server",6)) {
3465 is_listen = 1;
3466 } else if (!strncmp(ptr,"nowait",6)) {
3467 is_waitconnect = 0;
3468 } else if (!strncmp(ptr,"nodelay",6)) {
3469 do_nodelay = 1;
3470 } else {
3471 printf("Unknown option: %s\n", ptr);
3472 goto fail;
3475 if (!is_listen)
3476 is_waitconnect = 0;
3478 chr = qemu_mallocz(sizeof(CharDriverState));
3479 if (!chr)
3480 goto fail;
3481 s = qemu_mallocz(sizeof(TCPCharDriver));
3482 if (!s)
3483 goto fail;
3485 #ifndef _WIN32
3486 if (is_unix)
3487 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3488 else
3489 #endif
3490 fd = socket(PF_INET, SOCK_STREAM, 0);
3492 if (fd < 0)
3493 goto fail;
3495 if (!is_waitconnect)
3496 socket_set_nonblock(fd);
3498 s->connected = 0;
3499 s->fd = -1;
3500 s->listen_fd = -1;
3501 s->is_unix = is_unix;
3502 s->do_nodelay = do_nodelay && !is_unix;
3504 chr->opaque = s;
3505 chr->chr_write = tcp_chr_write;
3506 chr->chr_close = tcp_chr_close;
3508 if (is_listen) {
3509 /* allow fast reuse */
3510 #ifndef _WIN32
3511 if (is_unix) {
3512 char path[109];
3513 pstrcpy(path, sizeof(path), uaddr.sun_path);
3514 unlink(path);
3515 } else
3516 #endif
3518 val = 1;
3519 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3522 ret = bind(fd, addr, addrlen);
3523 if (ret < 0)
3524 goto fail;
3526 ret = listen(fd, 0);
3527 if (ret < 0)
3528 goto fail;
3530 s->listen_fd = fd;
3531 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3532 if (is_telnet)
3533 s->do_telnetopt = 1;
3534 } else {
3535 for(;;) {
3536 ret = connect(fd, addr, addrlen);
3537 if (ret < 0) {
3538 err = socket_error();
3539 if (err == EINTR || err == EWOULDBLOCK) {
3540 } else if (err == EINPROGRESS) {
3541 break;
3542 #ifdef _WIN32
3543 } else if (err == WSAEALREADY) {
3544 break;
3545 #endif
3546 } else {
3547 goto fail;
3549 } else {
3550 s->connected = 1;
3551 break;
3554 s->fd = fd;
3555 socket_set_nodelay(fd);
3556 if (s->connected)
3557 tcp_chr_connect(chr);
3558 else
3559 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3562 if (is_listen && is_waitconnect) {
3563 printf("QEMU waiting for connection on: %s\n", host_str);
3564 tcp_chr_accept(chr);
3565 socket_set_nonblock(s->listen_fd);
3568 return chr;
3569 fail:
3570 if (fd >= 0)
3571 closesocket(fd);
3572 qemu_free(s);
3573 qemu_free(chr);
3574 return NULL;
3577 CharDriverState *qemu_chr_open(const char *filename)
3579 const char *p;
3581 if (!strcmp(filename, "vc")) {
3582 return text_console_init(&display_state, 0);
3583 } else if (strstart(filename, "vc:", &p)) {
3584 return text_console_init(&display_state, p);
3585 } else if (!strcmp(filename, "null")) {
3586 return qemu_chr_open_null();
3587 } else
3588 if (strstart(filename, "tcp:", &p)) {
3589 return qemu_chr_open_tcp(p, 0, 0);
3590 } else
3591 if (strstart(filename, "telnet:", &p)) {
3592 return qemu_chr_open_tcp(p, 1, 0);
3593 } else
3594 if (strstart(filename, "udp:", &p)) {
3595 return qemu_chr_open_udp(p);
3596 } else
3597 if (strstart(filename, "mon:", &p)) {
3598 CharDriverState *drv = qemu_chr_open(p);
3599 if (drv) {
3600 drv = qemu_chr_open_mux(drv);
3601 monitor_init(drv, !nographic);
3602 return drv;
3604 printf("Unable to open driver: %s\n", p);
3605 return 0;
3606 } else
3607 #ifndef _WIN32
3608 if (strstart(filename, "unix:", &p)) {
3609 return qemu_chr_open_tcp(p, 0, 1);
3610 } else if (strstart(filename, "file:", &p)) {
3611 return qemu_chr_open_file_out(p);
3612 } else if (strstart(filename, "pipe:", &p)) {
3613 return qemu_chr_open_pipe(p);
3614 } else if (!strcmp(filename, "pty")) {
3615 return qemu_chr_open_pty();
3616 } else if (!strcmp(filename, "stdio")) {
3617 return qemu_chr_open_stdio();
3618 } else
3619 #if defined(__linux__)
3620 if (strstart(filename, "/dev/parport", NULL)) {
3621 return qemu_chr_open_pp(filename);
3622 } else
3623 #endif
3624 #if defined(__linux__) || defined(__sun__)
3625 if (strstart(filename, "/dev/", NULL)) {
3626 return qemu_chr_open_tty(filename);
3627 } else
3628 #endif
3629 #else /* !_WIN32 */
3630 if (strstart(filename, "COM", NULL)) {
3631 return qemu_chr_open_win(filename);
3632 } else
3633 if (strstart(filename, "pipe:", &p)) {
3634 return qemu_chr_open_win_pipe(p);
3635 } else
3636 if (strstart(filename, "con:", NULL)) {
3637 return qemu_chr_open_win_con(filename);
3638 } else
3639 if (strstart(filename, "file:", &p)) {
3640 return qemu_chr_open_win_file_out(p);
3641 } else
3642 #endif
3643 #ifdef CONFIG_BRLAPI
3644 if (!strcmp(filename, "braille")) {
3645 return chr_baum_init();
3646 } else
3647 #endif
3649 return NULL;
3653 void qemu_chr_close(CharDriverState *chr)
3655 if (chr->chr_close)
3656 chr->chr_close(chr);
3657 qemu_free(chr);
3660 /***********************************************************/
3661 /* network device redirectors */
3663 __attribute__ (( unused ))
3664 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3666 int len, i, j, c;
3668 for(i=0;i<size;i+=16) {
3669 len = size - i;
3670 if (len > 16)
3671 len = 16;
3672 fprintf(f, "%08x ", i);
3673 for(j=0;j<16;j++) {
3674 if (j < len)
3675 fprintf(f, " %02x", buf[i+j]);
3676 else
3677 fprintf(f, " ");
3679 fprintf(f, " ");
3680 for(j=0;j<len;j++) {
3681 c = buf[i+j];
3682 if (c < ' ' || c > '~')
3683 c = '.';
3684 fprintf(f, "%c", c);
3686 fprintf(f, "\n");
3690 static int parse_macaddr(uint8_t *macaddr, const char *p)
3692 int i;
3693 char *last_char;
3694 long int offset;
3696 errno = 0;
3697 offset = strtol(p, &last_char, 0);
3698 if (0 == errno && '\0' == *last_char &&
3699 offset >= 0 && offset <= 0xFFFFFF) {
3700 macaddr[3] = (offset & 0xFF0000) >> 16;
3701 macaddr[4] = (offset & 0xFF00) >> 8;
3702 macaddr[5] = offset & 0xFF;
3703 return 0;
3704 } else {
3705 for(i = 0; i < 6; i++) {
3706 macaddr[i] = strtol(p, (char **)&p, 16);
3707 if (i == 5) {
3708 if (*p != '\0')
3709 return -1;
3710 } else {
3711 if (*p != ':' && *p != '-')
3712 return -1;
3713 p++;
3716 return 0;
3719 return -1;
3722 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3724 const char *p, *p1;
3725 int len;
3726 p = *pp;
3727 p1 = strchr(p, sep);
3728 if (!p1)
3729 return -1;
3730 len = p1 - p;
3731 p1++;
3732 if (buf_size > 0) {
3733 if (len > buf_size - 1)
3734 len = buf_size - 1;
3735 memcpy(buf, p, len);
3736 buf[len] = '\0';
3738 *pp = p1;
3739 return 0;
3742 int parse_host_src_port(struct sockaddr_in *haddr,
3743 struct sockaddr_in *saddr,
3744 const char *input_str)
3746 char *str = strdup(input_str);
3747 char *host_str = str;
3748 char *src_str;
3749 char *ptr;
3752 * Chop off any extra arguments at the end of the string which
3753 * would start with a comma, then fill in the src port information
3754 * if it was provided else use the "any address" and "any port".
3756 if ((ptr = strchr(str,',')))
3757 *ptr = '\0';
3759 if ((src_str = strchr(input_str,'@'))) {
3760 *src_str = '\0';
3761 src_str++;
3764 if (parse_host_port(haddr, host_str) < 0)
3765 goto fail;
3767 if (!src_str || *src_str == '\0')
3768 src_str = ":0";
3770 if (parse_host_port(saddr, src_str) < 0)
3771 goto fail;
3773 free(str);
3774 return(0);
3776 fail:
3777 free(str);
3778 return -1;
3781 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3783 char buf[512];
3784 struct hostent *he;
3785 const char *p, *r;
3786 int port;
3788 p = str;
3789 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3790 return -1;
3791 saddr->sin_family = AF_INET;
3792 if (buf[0] == '\0') {
3793 saddr->sin_addr.s_addr = 0;
3794 } else {
3795 if (isdigit(buf[0])) {
3796 if (!inet_aton(buf, &saddr->sin_addr))
3797 return -1;
3798 } else {
3799 if ((he = gethostbyname(buf)) == NULL)
3800 return - 1;
3801 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3804 port = strtol(p, (char **)&r, 0);
3805 if (r == p)
3806 return -1;
3807 saddr->sin_port = htons(port);
3808 return 0;
3811 #ifndef _WIN32
3812 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3814 const char *p;
3815 int len;
3817 len = MIN(108, strlen(str));
3818 p = strchr(str, ',');
3819 if (p)
3820 len = MIN(len, p - str);
3822 memset(uaddr, 0, sizeof(*uaddr));
3824 uaddr->sun_family = AF_UNIX;
3825 memcpy(uaddr->sun_path, str, len);
3827 return 0;
3829 #endif
3831 /* find or alloc a new VLAN */
3832 VLANState *qemu_find_vlan(int id)
3834 VLANState **pvlan, *vlan;
3835 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3836 if (vlan->id == id)
3837 return vlan;
3839 vlan = qemu_mallocz(sizeof(VLANState));
3840 if (!vlan)
3841 return NULL;
3842 vlan->id = id;
3843 vlan->next = NULL;
3844 pvlan = &first_vlan;
3845 while (*pvlan != NULL)
3846 pvlan = &(*pvlan)->next;
3847 *pvlan = vlan;
3848 return vlan;
3851 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3852 IOReadHandler *fd_read,
3853 IOCanRWHandler *fd_can_read,
3854 void *opaque)
3856 VLANClientState *vc, **pvc;
3857 vc = qemu_mallocz(sizeof(VLANClientState));
3858 if (!vc)
3859 return NULL;
3860 vc->fd_read = fd_read;
3861 vc->fd_can_read = fd_can_read;
3862 vc->opaque = opaque;
3863 vc->vlan = vlan;
3865 vc->next = NULL;
3866 pvc = &vlan->first_client;
3867 while (*pvc != NULL)
3868 pvc = &(*pvc)->next;
3869 *pvc = vc;
3870 return vc;
3873 int qemu_can_send_packet(VLANClientState *vc1)
3875 VLANState *vlan = vc1->vlan;
3876 VLANClientState *vc;
3878 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3879 if (vc != vc1) {
3880 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3881 return 1;
3884 return 0;
3887 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3889 VLANState *vlan = vc1->vlan;
3890 VLANClientState *vc;
3892 #if 0
3893 printf("vlan %d send:\n", vlan->id);
3894 hex_dump(stdout, buf, size);
3895 #endif
3896 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3897 if (vc != vc1) {
3898 vc->fd_read(vc->opaque, buf, size);
3903 #if defined(CONFIG_SLIRP)
3905 /* slirp network adapter */
3907 static int slirp_inited;
3908 static VLANClientState *slirp_vc;
3910 int slirp_can_output(void)
3912 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3915 void slirp_output(const uint8_t *pkt, int pkt_len)
3917 #if 0
3918 printf("slirp output:\n");
3919 hex_dump(stdout, pkt, pkt_len);
3920 #endif
3921 if (!slirp_vc)
3922 return;
3923 qemu_send_packet(slirp_vc, pkt, pkt_len);
3926 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3928 #if 0
3929 printf("slirp input:\n");
3930 hex_dump(stdout, buf, size);
3931 #endif
3932 slirp_input(buf, size);
3935 static int net_slirp_init(VLANState *vlan)
3937 if (!slirp_inited) {
3938 slirp_inited = 1;
3939 slirp_init();
3941 slirp_vc = qemu_new_vlan_client(vlan,
3942 slirp_receive, NULL, NULL);
3943 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3944 return 0;
3947 static void net_slirp_redir(const char *redir_str)
3949 int is_udp;
3950 char buf[256], *r;
3951 const char *p;
3952 struct in_addr guest_addr;
3953 int host_port, guest_port;
3955 if (!slirp_inited) {
3956 slirp_inited = 1;
3957 slirp_init();
3960 p = redir_str;
3961 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3962 goto fail;
3963 if (!strcmp(buf, "tcp")) {
3964 is_udp = 0;
3965 } else if (!strcmp(buf, "udp")) {
3966 is_udp = 1;
3967 } else {
3968 goto fail;
3971 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3972 goto fail;
3973 host_port = strtol(buf, &r, 0);
3974 if (r == buf)
3975 goto fail;
3977 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3978 goto fail;
3979 if (buf[0] == '\0') {
3980 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3982 if (!inet_aton(buf, &guest_addr))
3983 goto fail;
3985 guest_port = strtol(p, &r, 0);
3986 if (r == p)
3987 goto fail;
3989 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3990 fprintf(stderr, "qemu: could not set up redirection\n");
3991 exit(1);
3993 return;
3994 fail:
3995 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3996 exit(1);
3999 #ifndef _WIN32
4001 char smb_dir[1024];
4003 static void erase_dir(char *dir_name)
4005 DIR *d;
4006 struct dirent *de;
4007 char filename[1024];
4009 /* erase all the files in the directory */
4010 if ((d = opendir(dir_name)) != 0) {
4011 for(;;) {
4012 de = readdir(d);
4013 if (!de)
4014 break;
4015 if (strcmp(de->d_name, ".") != 0 &&
4016 strcmp(de->d_name, "..") != 0) {
4017 snprintf(filename, sizeof(filename), "%s/%s",
4018 smb_dir, de->d_name);
4019 if (unlink(filename) != 0) /* is it a directory? */
4020 erase_dir(filename);
4023 closedir(d);
4024 rmdir(dir_name);
4028 /* automatic user mode samba server configuration */
4029 static void smb_exit(void)
4031 erase_dir(smb_dir);
4034 /* automatic user mode samba server configuration */
4035 static void net_slirp_smb(const char *exported_dir)
4037 char smb_conf[1024];
4038 char smb_cmdline[1024];
4039 FILE *f;
4041 if (!slirp_inited) {
4042 slirp_inited = 1;
4043 slirp_init();
4046 /* XXX: better tmp dir construction */
4047 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4048 if (mkdir(smb_dir, 0700) < 0) {
4049 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4050 exit(1);
4052 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4054 f = fopen(smb_conf, "w");
4055 if (!f) {
4056 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4057 exit(1);
4059 fprintf(f,
4060 "[global]\n"
4061 "private dir=%s\n"
4062 "smb ports=0\n"
4063 "socket address=127.0.0.1\n"
4064 "pid directory=%s\n"
4065 "lock directory=%s\n"
4066 "log file=%s/log.smbd\n"
4067 "smb passwd file=%s/smbpasswd\n"
4068 "security = share\n"
4069 "[qemu]\n"
4070 "path=%s\n"
4071 "read only=no\n"
4072 "guest ok=yes\n",
4073 smb_dir,
4074 smb_dir,
4075 smb_dir,
4076 smb_dir,
4077 smb_dir,
4078 exported_dir
4080 fclose(f);
4081 atexit(smb_exit);
4083 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4084 SMBD_COMMAND, smb_conf);
4086 slirp_add_exec(0, smb_cmdline, 4, 139);
4089 #endif /* !defined(_WIN32) */
4090 void do_info_slirp(void)
4092 slirp_stats();
4095 #endif /* CONFIG_SLIRP */
4097 #if !defined(_WIN32)
4099 typedef struct TAPState {
4100 VLANClientState *vc;
4101 int fd;
4102 char down_script[1024];
4103 } TAPState;
4105 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4107 TAPState *s = opaque;
4108 int ret;
4109 for(;;) {
4110 ret = write(s->fd, buf, size);
4111 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4112 } else {
4113 break;
4118 static void tap_send(void *opaque)
4120 TAPState *s = opaque;
4121 uint8_t buf[4096];
4122 int size;
4124 #ifdef __sun__
4125 struct strbuf sbuf;
4126 int f = 0;
4127 sbuf.maxlen = sizeof(buf);
4128 sbuf.buf = buf;
4129 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4130 #else
4131 size = read(s->fd, buf, sizeof(buf));
4132 #endif
4133 if (size > 0) {
4134 qemu_send_packet(s->vc, buf, size);
4138 /* fd support */
4140 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4142 TAPState *s;
4144 s = qemu_mallocz(sizeof(TAPState));
4145 if (!s)
4146 return NULL;
4147 s->fd = fd;
4148 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4149 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4150 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4151 return s;
4154 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4155 static int tap_open(char *ifname, int ifname_size)
4157 int fd;
4158 char *dev;
4159 struct stat s;
4161 TFR(fd = open("/dev/tap", O_RDWR));
4162 if (fd < 0) {
4163 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4164 return -1;
4167 fstat(fd, &s);
4168 dev = devname(s.st_rdev, S_IFCHR);
4169 pstrcpy(ifname, ifname_size, dev);
4171 fcntl(fd, F_SETFL, O_NONBLOCK);
4172 return fd;
4174 #elif defined(__sun__)
4175 #define TUNNEWPPA (('T'<<16) | 0x0001)
4177 * Allocate TAP device, returns opened fd.
4178 * Stores dev name in the first arg(must be large enough).
4180 int tap_alloc(char *dev)
4182 int tap_fd, if_fd, ppa = -1;
4183 static int ip_fd = 0;
4184 char *ptr;
4186 static int arp_fd = 0;
4187 int ip_muxid, arp_muxid;
4188 struct strioctl strioc_if, strioc_ppa;
4189 int link_type = I_PLINK;;
4190 struct lifreq ifr;
4191 char actual_name[32] = "";
4193 memset(&ifr, 0x0, sizeof(ifr));
4195 if( *dev ){
4196 ptr = dev;
4197 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4198 ppa = atoi(ptr);
4201 /* Check if IP device was opened */
4202 if( ip_fd )
4203 close(ip_fd);
4205 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4206 if (ip_fd < 0) {
4207 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4208 return -1;
4211 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4212 if (tap_fd < 0) {
4213 syslog(LOG_ERR, "Can't open /dev/tap");
4214 return -1;
4217 /* Assign a new PPA and get its unit number. */
4218 strioc_ppa.ic_cmd = TUNNEWPPA;
4219 strioc_ppa.ic_timout = 0;
4220 strioc_ppa.ic_len = sizeof(ppa);
4221 strioc_ppa.ic_dp = (char *)&ppa;
4222 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4223 syslog (LOG_ERR, "Can't assign new interface");
4225 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4226 if (if_fd < 0) {
4227 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4228 return -1;
4230 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4231 syslog(LOG_ERR, "Can't push IP module");
4232 return -1;
4235 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4236 syslog(LOG_ERR, "Can't get flags\n");
4238 snprintf (actual_name, 32, "tap%d", ppa);
4239 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4241 ifr.lifr_ppa = ppa;
4242 /* Assign ppa according to the unit number returned by tun device */
4244 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4245 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4246 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4247 syslog (LOG_ERR, "Can't get flags\n");
4248 /* Push arp module to if_fd */
4249 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4250 syslog (LOG_ERR, "Can't push ARP module (2)");
4252 /* Push arp module to ip_fd */
4253 if (ioctl (ip_fd, I_POP, NULL) < 0)
4254 syslog (LOG_ERR, "I_POP failed\n");
4255 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4256 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4257 /* Open arp_fd */
4258 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4259 if (arp_fd < 0)
4260 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4262 /* Set ifname to arp */
4263 strioc_if.ic_cmd = SIOCSLIFNAME;
4264 strioc_if.ic_timout = 0;
4265 strioc_if.ic_len = sizeof(ifr);
4266 strioc_if.ic_dp = (char *)&ifr;
4267 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4268 syslog (LOG_ERR, "Can't set ifname to arp\n");
4271 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4272 syslog(LOG_ERR, "Can't link TAP device to IP");
4273 return -1;
4276 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4277 syslog (LOG_ERR, "Can't link TAP device to ARP");
4279 close (if_fd);
4281 memset(&ifr, 0x0, sizeof(ifr));
4282 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4283 ifr.lifr_ip_muxid = ip_muxid;
4284 ifr.lifr_arp_muxid = arp_muxid;
4286 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4288 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4289 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4290 syslog (LOG_ERR, "Can't set multiplexor id");
4293 sprintf(dev, "tap%d", ppa);
4294 return tap_fd;
4297 static int tap_open(char *ifname, int ifname_size)
4299 char dev[10]="";
4300 int fd;
4301 if( (fd = tap_alloc(dev)) < 0 ){
4302 fprintf(stderr, "Cannot allocate TAP device\n");
4303 return -1;
4305 pstrcpy(ifname, ifname_size, dev);
4306 fcntl(fd, F_SETFL, O_NONBLOCK);
4307 return fd;
4309 #else
4310 static int tap_open(char *ifname, int ifname_size)
4312 struct ifreq ifr;
4313 int fd, ret;
4315 TFR(fd = open("/dev/net/tun", O_RDWR));
4316 if (fd < 0) {
4317 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4318 return -1;
4320 memset(&ifr, 0, sizeof(ifr));
4321 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4322 if (ifname[0] != '\0')
4323 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4324 else
4325 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4326 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4327 if (ret != 0) {
4328 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4329 close(fd);
4330 return -1;
4332 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4333 fcntl(fd, F_SETFL, O_NONBLOCK);
4334 return fd;
4336 #endif
4338 static int launch_script(const char *setup_script, const char *ifname, int fd)
4340 int pid, status;
4341 char *args[3];
4342 char **parg;
4344 /* try to launch network script */
4345 pid = fork();
4346 if (pid >= 0) {
4347 if (pid == 0) {
4348 int open_max = sysconf (_SC_OPEN_MAX), i;
4349 for (i = 0; i < open_max; i++)
4350 if (i != STDIN_FILENO &&
4351 i != STDOUT_FILENO &&
4352 i != STDERR_FILENO &&
4353 i != fd)
4354 close(i);
4356 parg = args;
4357 *parg++ = (char *)setup_script;
4358 *parg++ = (char *)ifname;
4359 *parg++ = NULL;
4360 execv(setup_script, args);
4361 _exit(1);
4363 while (waitpid(pid, &status, 0) != pid);
4364 if (!WIFEXITED(status) ||
4365 WEXITSTATUS(status) != 0) {
4366 fprintf(stderr, "%s: could not launch network script\n",
4367 setup_script);
4368 return -1;
4371 return 0;
4374 static int net_tap_init(VLANState *vlan, const char *ifname1,
4375 const char *setup_script, const char *down_script)
4377 TAPState *s;
4378 int fd;
4379 char ifname[128];
4381 if (ifname1 != NULL)
4382 pstrcpy(ifname, sizeof(ifname), ifname1);
4383 else
4384 ifname[0] = '\0';
4385 TFR(fd = tap_open(ifname, sizeof(ifname)));
4386 if (fd < 0)
4387 return -1;
4389 if (!setup_script || !strcmp(setup_script, "no"))
4390 setup_script = "";
4391 if (setup_script[0] != '\0') {
4392 if (launch_script(setup_script, ifname, fd))
4393 return -1;
4395 s = net_tap_fd_init(vlan, fd);
4396 if (!s)
4397 return -1;
4398 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4399 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4400 if (down_script && strcmp(down_script, "no"))
4401 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4402 return 0;
4405 #endif /* !_WIN32 */
4407 /* network connection */
4408 typedef struct NetSocketState {
4409 VLANClientState *vc;
4410 int fd;
4411 int state; /* 0 = getting length, 1 = getting data */
4412 int index;
4413 int packet_len;
4414 uint8_t buf[4096];
4415 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4416 } NetSocketState;
4418 typedef struct NetSocketListenState {
4419 VLANState *vlan;
4420 int fd;
4421 } NetSocketListenState;
4423 /* XXX: we consider we can send the whole packet without blocking */
4424 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4426 NetSocketState *s = opaque;
4427 uint32_t len;
4428 len = htonl(size);
4430 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4431 send_all(s->fd, buf, size);
4434 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4436 NetSocketState *s = opaque;
4437 sendto(s->fd, buf, size, 0,
4438 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4441 static void net_socket_send(void *opaque)
4443 NetSocketState *s = opaque;
4444 int l, size, err;
4445 uint8_t buf1[4096];
4446 const uint8_t *buf;
4448 size = recv(s->fd, buf1, sizeof(buf1), 0);
4449 if (size < 0) {
4450 err = socket_error();
4451 if (err != EWOULDBLOCK)
4452 goto eoc;
4453 } else if (size == 0) {
4454 /* end of connection */
4455 eoc:
4456 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4457 closesocket(s->fd);
4458 return;
4460 buf = buf1;
4461 while (size > 0) {
4462 /* reassemble a packet from the network */
4463 switch(s->state) {
4464 case 0:
4465 l = 4 - s->index;
4466 if (l > size)
4467 l = size;
4468 memcpy(s->buf + s->index, buf, l);
4469 buf += l;
4470 size -= l;
4471 s->index += l;
4472 if (s->index == 4) {
4473 /* got length */
4474 s->packet_len = ntohl(*(uint32_t *)s->buf);
4475 s->index = 0;
4476 s->state = 1;
4478 break;
4479 case 1:
4480 l = s->packet_len - s->index;
4481 if (l > size)
4482 l = size;
4483 memcpy(s->buf + s->index, buf, l);
4484 s->index += l;
4485 buf += l;
4486 size -= l;
4487 if (s->index >= s->packet_len) {
4488 qemu_send_packet(s->vc, s->buf, s->packet_len);
4489 s->index = 0;
4490 s->state = 0;
4492 break;
4497 static void net_socket_send_dgram(void *opaque)
4499 NetSocketState *s = opaque;
4500 int size;
4502 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4503 if (size < 0)
4504 return;
4505 if (size == 0) {
4506 /* end of connection */
4507 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4508 return;
4510 qemu_send_packet(s->vc, s->buf, size);
4513 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4515 struct ip_mreq imr;
4516 int fd;
4517 int val, ret;
4518 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4519 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4520 inet_ntoa(mcastaddr->sin_addr),
4521 (int)ntohl(mcastaddr->sin_addr.s_addr));
4522 return -1;
4525 fd = socket(PF_INET, SOCK_DGRAM, 0);
4526 if (fd < 0) {
4527 perror("socket(PF_INET, SOCK_DGRAM)");
4528 return -1;
4531 val = 1;
4532 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4533 (const char *)&val, sizeof(val));
4534 if (ret < 0) {
4535 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4536 goto fail;
4539 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4540 if (ret < 0) {
4541 perror("bind");
4542 goto fail;
4545 /* Add host to multicast group */
4546 imr.imr_multiaddr = mcastaddr->sin_addr;
4547 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4549 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4550 (const char *)&imr, sizeof(struct ip_mreq));
4551 if (ret < 0) {
4552 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4553 goto fail;
4556 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4557 val = 1;
4558 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4559 (const char *)&val, sizeof(val));
4560 if (ret < 0) {
4561 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4562 goto fail;
4565 socket_set_nonblock(fd);
4566 return fd;
4567 fail:
4568 if (fd >= 0)
4569 closesocket(fd);
4570 return -1;
4573 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4574 int is_connected)
4576 struct sockaddr_in saddr;
4577 int newfd;
4578 socklen_t saddr_len;
4579 NetSocketState *s;
4581 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4582 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4583 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4586 if (is_connected) {
4587 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4588 /* must be bound */
4589 if (saddr.sin_addr.s_addr==0) {
4590 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4591 fd);
4592 return NULL;
4594 /* clone dgram socket */
4595 newfd = net_socket_mcast_create(&saddr);
4596 if (newfd < 0) {
4597 /* error already reported by net_socket_mcast_create() */
4598 close(fd);
4599 return NULL;
4601 /* clone newfd to fd, close newfd */
4602 dup2(newfd, fd);
4603 close(newfd);
4605 } else {
4606 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4607 fd, strerror(errno));
4608 return NULL;
4612 s = qemu_mallocz(sizeof(NetSocketState));
4613 if (!s)
4614 return NULL;
4615 s->fd = fd;
4617 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4618 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4620 /* mcast: save bound address as dst */
4621 if (is_connected) s->dgram_dst=saddr;
4623 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4624 "socket: fd=%d (%s mcast=%s:%d)",
4625 fd, is_connected? "cloned" : "",
4626 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4627 return s;
4630 static void net_socket_connect(void *opaque)
4632 NetSocketState *s = opaque;
4633 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4636 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4637 int is_connected)
4639 NetSocketState *s;
4640 s = qemu_mallocz(sizeof(NetSocketState));
4641 if (!s)
4642 return NULL;
4643 s->fd = fd;
4644 s->vc = qemu_new_vlan_client(vlan,
4645 net_socket_receive, NULL, s);
4646 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4647 "socket: fd=%d", fd);
4648 if (is_connected) {
4649 net_socket_connect(s);
4650 } else {
4651 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4653 return s;
4656 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4657 int is_connected)
4659 int so_type=-1, optlen=sizeof(so_type);
4661 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4662 (socklen_t *)&optlen)< 0) {
4663 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4664 return NULL;
4666 switch(so_type) {
4667 case SOCK_DGRAM:
4668 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4669 case SOCK_STREAM:
4670 return net_socket_fd_init_stream(vlan, fd, is_connected);
4671 default:
4672 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4673 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4674 return net_socket_fd_init_stream(vlan, fd, is_connected);
4676 return NULL;
4679 static void net_socket_accept(void *opaque)
4681 NetSocketListenState *s = opaque;
4682 NetSocketState *s1;
4683 struct sockaddr_in saddr;
4684 socklen_t len;
4685 int fd;
4687 for(;;) {
4688 len = sizeof(saddr);
4689 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4690 if (fd < 0 && errno != EINTR) {
4691 return;
4692 } else if (fd >= 0) {
4693 break;
4696 s1 = net_socket_fd_init(s->vlan, fd, 1);
4697 if (!s1) {
4698 closesocket(fd);
4699 } else {
4700 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4701 "socket: connection from %s:%d",
4702 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4706 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4708 NetSocketListenState *s;
4709 int fd, val, ret;
4710 struct sockaddr_in saddr;
4712 if (parse_host_port(&saddr, host_str) < 0)
4713 return -1;
4715 s = qemu_mallocz(sizeof(NetSocketListenState));
4716 if (!s)
4717 return -1;
4719 fd = socket(PF_INET, SOCK_STREAM, 0);
4720 if (fd < 0) {
4721 perror("socket");
4722 return -1;
4724 socket_set_nonblock(fd);
4726 /* allow fast reuse */
4727 val = 1;
4728 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4730 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4731 if (ret < 0) {
4732 perror("bind");
4733 return -1;
4735 ret = listen(fd, 0);
4736 if (ret < 0) {
4737 perror("listen");
4738 return -1;
4740 s->vlan = vlan;
4741 s->fd = fd;
4742 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4743 return 0;
4746 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4748 NetSocketState *s;
4749 int fd, connected, ret, err;
4750 struct sockaddr_in saddr;
4752 if (parse_host_port(&saddr, host_str) < 0)
4753 return -1;
4755 fd = socket(PF_INET, SOCK_STREAM, 0);
4756 if (fd < 0) {
4757 perror("socket");
4758 return -1;
4760 socket_set_nonblock(fd);
4762 connected = 0;
4763 for(;;) {
4764 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4765 if (ret < 0) {
4766 err = socket_error();
4767 if (err == EINTR || err == EWOULDBLOCK) {
4768 } else if (err == EINPROGRESS) {
4769 break;
4770 #ifdef _WIN32
4771 } else if (err == WSAEALREADY) {
4772 break;
4773 #endif
4774 } else {
4775 perror("connect");
4776 closesocket(fd);
4777 return -1;
4779 } else {
4780 connected = 1;
4781 break;
4784 s = net_socket_fd_init(vlan, fd, connected);
4785 if (!s)
4786 return -1;
4787 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4788 "socket: connect to %s:%d",
4789 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4790 return 0;
4793 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4795 NetSocketState *s;
4796 int fd;
4797 struct sockaddr_in saddr;
4799 if (parse_host_port(&saddr, host_str) < 0)
4800 return -1;
4803 fd = net_socket_mcast_create(&saddr);
4804 if (fd < 0)
4805 return -1;
4807 s = net_socket_fd_init(vlan, fd, 0);
4808 if (!s)
4809 return -1;
4811 s->dgram_dst = saddr;
4813 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4814 "socket: mcast=%s:%d",
4815 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4816 return 0;
4820 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4822 char *q;
4824 q = buf;
4825 while (*p != '\0' && *p != '=') {
4826 if (q && (q - buf) < buf_size - 1)
4827 *q++ = *p;
4828 p++;
4830 if (q)
4831 *q = '\0';
4833 return p;
4836 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4838 char *q;
4840 q = buf;
4841 while (*p != '\0') {
4842 if (*p == ',') {
4843 if (*(p + 1) != ',')
4844 break;
4845 p++;
4847 if (q && (q - buf) < buf_size - 1)
4848 *q++ = *p;
4849 p++;
4851 if (q)
4852 *q = '\0';
4854 return p;
4857 static int get_param_value(char *buf, int buf_size,
4858 const char *tag, const char *str)
4860 const char *p;
4861 char option[128];
4863 p = str;
4864 for(;;) {
4865 p = get_opt_name(option, sizeof(option), p);
4866 if (*p != '=')
4867 break;
4868 p++;
4869 if (!strcmp(tag, option)) {
4870 (void)get_opt_value(buf, buf_size, p);
4871 return strlen(buf);
4872 } else {
4873 p = get_opt_value(NULL, 0, p);
4875 if (*p != ',')
4876 break;
4877 p++;
4879 return 0;
4882 static int check_params(char *buf, int buf_size,
4883 char **params, const char *str)
4885 const char *p;
4886 int i;
4888 p = str;
4889 for(;;) {
4890 p = get_opt_name(buf, buf_size, p);
4891 if (*p != '=')
4892 return -1;
4893 p++;
4894 for(i = 0; params[i] != NULL; i++)
4895 if (!strcmp(params[i], buf))
4896 break;
4897 if (params[i] == NULL)
4898 return -1;
4899 p = get_opt_value(NULL, 0, p);
4900 if (*p != ',')
4901 break;
4902 p++;
4904 return 0;
4908 static int net_client_init(const char *str)
4910 const char *p;
4911 char *q;
4912 char device[64];
4913 char buf[1024];
4914 int vlan_id, ret;
4915 VLANState *vlan;
4917 p = str;
4918 q = device;
4919 while (*p != '\0' && *p != ',') {
4920 if ((q - device) < sizeof(device) - 1)
4921 *q++ = *p;
4922 p++;
4924 *q = '\0';
4925 if (*p == ',')
4926 p++;
4927 vlan_id = 0;
4928 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4929 vlan_id = strtol(buf, NULL, 0);
4931 vlan = qemu_find_vlan(vlan_id);
4932 if (!vlan) {
4933 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4934 return -1;
4936 if (!strcmp(device, "nic")) {
4937 NICInfo *nd;
4938 uint8_t *macaddr;
4940 if (nb_nics >= MAX_NICS) {
4941 fprintf(stderr, "Too Many NICs\n");
4942 return -1;
4944 nd = &nd_table[nb_nics];
4945 macaddr = nd->macaddr;
4946 macaddr[0] = 0x52;
4947 macaddr[1] = 0x54;
4948 macaddr[2] = 0x00;
4949 macaddr[3] = 0x12;
4950 macaddr[4] = 0x34;
4951 macaddr[5] = 0x56 + nb_nics;
4953 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4954 if (parse_macaddr(macaddr, buf) < 0) {
4955 fprintf(stderr, "invalid syntax for ethernet address\n");
4956 return -1;
4959 if (get_param_value(buf, sizeof(buf), "model", p)) {
4960 nd->model = strdup(buf);
4962 nd->vlan = vlan;
4963 nb_nics++;
4964 vlan->nb_guest_devs++;
4965 ret = 0;
4966 } else
4967 if (!strcmp(device, "none")) {
4968 /* does nothing. It is needed to signal that no network cards
4969 are wanted */
4970 ret = 0;
4971 } else
4972 #ifdef CONFIG_SLIRP
4973 if (!strcmp(device, "user")) {
4974 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4975 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4977 vlan->nb_host_devs++;
4978 ret = net_slirp_init(vlan);
4979 } else
4980 #endif
4981 #ifdef _WIN32
4982 if (!strcmp(device, "tap")) {
4983 char ifname[64];
4984 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4985 fprintf(stderr, "tap: no interface name\n");
4986 return -1;
4988 vlan->nb_host_devs++;
4989 ret = tap_win32_init(vlan, ifname);
4990 } else
4991 #else
4992 if (!strcmp(device, "tap")) {
4993 char ifname[64];
4994 char setup_script[1024], down_script[1024];
4995 int fd;
4996 vlan->nb_host_devs++;
4997 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4998 fd = strtol(buf, NULL, 0);
4999 fcntl(fd, F_SETFL, O_NONBLOCK);
5000 ret = -1;
5001 if (net_tap_fd_init(vlan, fd))
5002 ret = 0;
5003 } else {
5004 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5005 ifname[0] = '\0';
5007 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5008 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5010 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5011 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5013 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5015 } else
5016 #endif
5017 if (!strcmp(device, "socket")) {
5018 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5019 int fd;
5020 fd = strtol(buf, NULL, 0);
5021 ret = -1;
5022 if (net_socket_fd_init(vlan, fd, 1))
5023 ret = 0;
5024 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5025 ret = net_socket_listen_init(vlan, buf);
5026 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5027 ret = net_socket_connect_init(vlan, buf);
5028 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5029 ret = net_socket_mcast_init(vlan, buf);
5030 } else {
5031 fprintf(stderr, "Unknown socket options: %s\n", p);
5032 return -1;
5034 vlan->nb_host_devs++;
5035 } else
5037 fprintf(stderr, "Unknown network device: %s\n", device);
5038 return -1;
5040 if (ret < 0) {
5041 fprintf(stderr, "Could not initialize device '%s'\n", device);
5044 return ret;
5047 void do_info_network(void)
5049 VLANState *vlan;
5050 VLANClientState *vc;
5052 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5053 term_printf("VLAN %d devices:\n", vlan->id);
5054 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5055 term_printf(" %s\n", vc->info_str);
5059 #define HD_ALIAS "index=%d,media=disk"
5060 #ifdef TARGET_PPC
5061 #define CDROM_ALIAS "index=1,media=cdrom"
5062 #else
5063 #define CDROM_ALIAS "index=2,media=cdrom"
5064 #endif
5065 #define FD_ALIAS "index=%d,if=floppy"
5066 #define PFLASH_ALIAS "if=pflash"
5067 #define MTD_ALIAS "if=mtd"
5068 #define SD_ALIAS "index=0,if=sd"
5070 static int drive_add(const char *file, const char *fmt, ...)
5072 va_list ap;
5074 if (nb_drives_opt >= MAX_DRIVES) {
5075 fprintf(stderr, "qemu: too many drives\n");
5076 exit(1);
5079 drives_opt[nb_drives_opt].file = file;
5080 va_start(ap, fmt);
5081 vsnprintf(drives_opt[nb_drives_opt].opt,
5082 sizeof(drives_opt[0].opt), fmt, ap);
5083 va_end(ap);
5085 return nb_drives_opt++;
5088 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5090 int index;
5092 /* seek interface, bus and unit */
5094 for (index = 0; index < nb_drives; index++)
5095 if (drives_table[index].type == type &&
5096 drives_table[index].bus == bus &&
5097 drives_table[index].unit == unit)
5098 return index;
5100 return -1;
5103 int drive_get_max_bus(BlockInterfaceType type)
5105 int max_bus;
5106 int index;
5108 max_bus = -1;
5109 for (index = 0; index < nb_drives; index++) {
5110 if(drives_table[index].type == type &&
5111 drives_table[index].bus > max_bus)
5112 max_bus = drives_table[index].bus;
5114 return max_bus;
5117 static void bdrv_format_print(void *opaque, const char *name)
5119 fprintf(stderr, " %s", name);
5122 static int drive_init(struct drive_opt *arg, int snapshot,
5123 QEMUMachine *machine)
5125 char buf[128];
5126 char file[1024];
5127 char devname[128];
5128 const char *mediastr = "";
5129 BlockInterfaceType type;
5130 enum { MEDIA_DISK, MEDIA_CDROM } media;
5131 int bus_id, unit_id;
5132 int cyls, heads, secs, translation;
5133 BlockDriverState *bdrv;
5134 BlockDriver *drv = NULL;
5135 int max_devs;
5136 int index;
5137 int cache;
5138 int bdrv_flags;
5139 char *str = arg->opt;
5140 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5141 "secs", "trans", "media", "snapshot", "file",
5142 "cache", "format", NULL };
5144 if (check_params(buf, sizeof(buf), params, str) < 0) {
5145 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5146 buf, str);
5147 return -1;
5150 file[0] = 0;
5151 cyls = heads = secs = 0;
5152 bus_id = 0;
5153 unit_id = -1;
5154 translation = BIOS_ATA_TRANSLATION_AUTO;
5155 index = -1;
5156 cache = 1;
5158 if (!strcmp(machine->name, "realview") ||
5159 !strcmp(machine->name, "SS-5") ||
5160 !strcmp(machine->name, "SS-10") ||
5161 !strcmp(machine->name, "SS-600MP") ||
5162 !strcmp(machine->name, "versatilepb") ||
5163 !strcmp(machine->name, "versatileab")) {
5164 type = IF_SCSI;
5165 max_devs = MAX_SCSI_DEVS;
5166 strcpy(devname, "scsi");
5167 } else {
5168 type = IF_IDE;
5169 max_devs = MAX_IDE_DEVS;
5170 strcpy(devname, "ide");
5172 media = MEDIA_DISK;
5174 /* extract parameters */
5176 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5177 bus_id = strtol(buf, NULL, 0);
5178 if (bus_id < 0) {
5179 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5180 return -1;
5184 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5185 unit_id = strtol(buf, NULL, 0);
5186 if (unit_id < 0) {
5187 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5188 return -1;
5192 if (get_param_value(buf, sizeof(buf), "if", str)) {
5193 pstrcpy(devname, sizeof(devname), buf);
5194 if (!strcmp(buf, "ide")) {
5195 type = IF_IDE;
5196 max_devs = MAX_IDE_DEVS;
5197 } else if (!strcmp(buf, "scsi")) {
5198 type = IF_SCSI;
5199 max_devs = MAX_SCSI_DEVS;
5200 } else if (!strcmp(buf, "floppy")) {
5201 type = IF_FLOPPY;
5202 max_devs = 0;
5203 } else if (!strcmp(buf, "pflash")) {
5204 type = IF_PFLASH;
5205 max_devs = 0;
5206 } else if (!strcmp(buf, "mtd")) {
5207 type = IF_MTD;
5208 max_devs = 0;
5209 } else if (!strcmp(buf, "sd")) {
5210 type = IF_SD;
5211 max_devs = 0;
5212 } else {
5213 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5214 return -1;
5218 if (get_param_value(buf, sizeof(buf), "index", str)) {
5219 index = strtol(buf, NULL, 0);
5220 if (index < 0) {
5221 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5222 return -1;
5226 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5227 cyls = strtol(buf, NULL, 0);
5230 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5231 heads = strtol(buf, NULL, 0);
5234 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5235 secs = strtol(buf, NULL, 0);
5238 if (cyls || heads || secs) {
5239 if (cyls < 1 || cyls > 16383) {
5240 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5241 return -1;
5243 if (heads < 1 || heads > 16) {
5244 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5245 return -1;
5247 if (secs < 1 || secs > 63) {
5248 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5249 return -1;
5253 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5254 if (!cyls) {
5255 fprintf(stderr,
5256 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5257 str);
5258 return -1;
5260 if (!strcmp(buf, "none"))
5261 translation = BIOS_ATA_TRANSLATION_NONE;
5262 else if (!strcmp(buf, "lba"))
5263 translation = BIOS_ATA_TRANSLATION_LBA;
5264 else if (!strcmp(buf, "auto"))
5265 translation = BIOS_ATA_TRANSLATION_AUTO;
5266 else {
5267 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5268 return -1;
5272 if (get_param_value(buf, sizeof(buf), "media", str)) {
5273 if (!strcmp(buf, "disk")) {
5274 media = MEDIA_DISK;
5275 } else if (!strcmp(buf, "cdrom")) {
5276 if (cyls || secs || heads) {
5277 fprintf(stderr,
5278 "qemu: '%s' invalid physical CHS format\n", str);
5279 return -1;
5281 media = MEDIA_CDROM;
5282 } else {
5283 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5284 return -1;
5288 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5289 if (!strcmp(buf, "on"))
5290 snapshot = 1;
5291 else if (!strcmp(buf, "off"))
5292 snapshot = 0;
5293 else {
5294 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5295 return -1;
5299 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5300 if (!strcmp(buf, "off"))
5301 cache = 0;
5302 else if (!strcmp(buf, "on"))
5303 cache = 1;
5304 else {
5305 fprintf(stderr, "qemu: invalid cache option\n");
5306 return -1;
5310 if (get_param_value(buf, sizeof(buf), "format", str)) {
5311 if (strcmp(buf, "?") == 0) {
5312 fprintf(stderr, "qemu: Supported formats:");
5313 bdrv_iterate_format(bdrv_format_print, NULL);
5314 fprintf(stderr, "\n");
5315 return -1;
5317 drv = bdrv_find_format(buf);
5318 if (!drv) {
5319 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5320 return -1;
5324 if (arg->file == NULL)
5325 get_param_value(file, sizeof(file), "file", str);
5326 else
5327 pstrcpy(file, sizeof(file), arg->file);
5329 /* compute bus and unit according index */
5331 if (index != -1) {
5332 if (bus_id != 0 || unit_id != -1) {
5333 fprintf(stderr,
5334 "qemu: '%s' index cannot be used with bus and unit\n", str);
5335 return -1;
5337 if (max_devs == 0)
5339 unit_id = index;
5340 bus_id = 0;
5341 } else {
5342 unit_id = index % max_devs;
5343 bus_id = index / max_devs;
5347 /* if user doesn't specify a unit_id,
5348 * try to find the first free
5351 if (unit_id == -1) {
5352 unit_id = 0;
5353 while (drive_get_index(type, bus_id, unit_id) != -1) {
5354 unit_id++;
5355 if (max_devs && unit_id >= max_devs) {
5356 unit_id -= max_devs;
5357 bus_id++;
5362 /* check unit id */
5364 if (max_devs && unit_id >= max_devs) {
5365 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5366 str, unit_id, max_devs - 1);
5367 return -1;
5371 * ignore multiple definitions
5374 if (drive_get_index(type, bus_id, unit_id) != -1)
5375 return 0;
5377 /* init */
5379 if (type == IF_IDE || type == IF_SCSI)
5380 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5381 if (max_devs)
5382 snprintf(buf, sizeof(buf), "%s%i%s%i",
5383 devname, bus_id, mediastr, unit_id);
5384 else
5385 snprintf(buf, sizeof(buf), "%s%s%i",
5386 devname, mediastr, unit_id);
5387 bdrv = bdrv_new(buf);
5388 drives_table[nb_drives].bdrv = bdrv;
5389 drives_table[nb_drives].type = type;
5390 drives_table[nb_drives].bus = bus_id;
5391 drives_table[nb_drives].unit = unit_id;
5392 nb_drives++;
5394 switch(type) {
5395 case IF_IDE:
5396 case IF_SCSI:
5397 switch(media) {
5398 case MEDIA_DISK:
5399 if (cyls != 0) {
5400 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5401 bdrv_set_translation_hint(bdrv, translation);
5403 break;
5404 case MEDIA_CDROM:
5405 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5406 break;
5408 break;
5409 case IF_SD:
5410 /* FIXME: This isn't really a floppy, but it's a reasonable
5411 approximation. */
5412 case IF_FLOPPY:
5413 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5414 break;
5415 case IF_PFLASH:
5416 case IF_MTD:
5417 break;
5419 if (!file[0])
5420 return 0;
5421 bdrv_flags = 0;
5422 if (snapshot)
5423 bdrv_flags |= BDRV_O_SNAPSHOT;
5424 if (!cache)
5425 bdrv_flags |= BDRV_O_DIRECT;
5426 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5427 fprintf(stderr, "qemu: could not open disk image %s\n",
5428 file);
5429 return -1;
5431 return 0;
5434 /***********************************************************/
5435 /* USB devices */
5437 static USBPort *used_usb_ports;
5438 static USBPort *free_usb_ports;
5440 /* ??? Maybe change this to register a hub to keep track of the topology. */
5441 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5442 usb_attachfn attach)
5444 port->opaque = opaque;
5445 port->index = index;
5446 port->attach = attach;
5447 port->next = free_usb_ports;
5448 free_usb_ports = port;
5451 static int usb_device_add(const char *devname)
5453 const char *p;
5454 USBDevice *dev;
5455 USBPort *port;
5457 if (!free_usb_ports)
5458 return -1;
5460 if (strstart(devname, "host:", &p)) {
5461 dev = usb_host_device_open(p);
5462 } else if (!strcmp(devname, "mouse")) {
5463 dev = usb_mouse_init();
5464 } else if (!strcmp(devname, "tablet")) {
5465 dev = usb_tablet_init();
5466 } else if (!strcmp(devname, "keyboard")) {
5467 dev = usb_keyboard_init();
5468 } else if (strstart(devname, "disk:", &p)) {
5469 dev = usb_msd_init(p);
5470 } else if (!strcmp(devname, "wacom-tablet")) {
5471 dev = usb_wacom_init();
5472 } else if (strstart(devname, "serial:", &p)) {
5473 dev = usb_serial_init(p);
5474 #ifdef CONFIG_BRLAPI
5475 } else if (!strcmp(devname, "braille")) {
5476 dev = usb_baum_init();
5477 #endif
5478 } else {
5479 return -1;
5481 if (!dev)
5482 return -1;
5484 /* Find a USB port to add the device to. */
5485 port = free_usb_ports;
5486 if (!port->next) {
5487 USBDevice *hub;
5489 /* Create a new hub and chain it on. */
5490 free_usb_ports = NULL;
5491 port->next = used_usb_ports;
5492 used_usb_ports = port;
5494 hub = usb_hub_init(VM_USB_HUB_SIZE);
5495 usb_attach(port, hub);
5496 port = free_usb_ports;
5499 free_usb_ports = port->next;
5500 port->next = used_usb_ports;
5501 used_usb_ports = port;
5502 usb_attach(port, dev);
5503 return 0;
5506 static int usb_device_del(const char *devname)
5508 USBPort *port;
5509 USBPort **lastp;
5510 USBDevice *dev;
5511 int bus_num, addr;
5512 const char *p;
5514 if (!used_usb_ports)
5515 return -1;
5517 p = strchr(devname, '.');
5518 if (!p)
5519 return -1;
5520 bus_num = strtoul(devname, NULL, 0);
5521 addr = strtoul(p + 1, NULL, 0);
5522 if (bus_num != 0)
5523 return -1;
5525 lastp = &used_usb_ports;
5526 port = used_usb_ports;
5527 while (port && port->dev->addr != addr) {
5528 lastp = &port->next;
5529 port = port->next;
5532 if (!port)
5533 return -1;
5535 dev = port->dev;
5536 *lastp = port->next;
5537 usb_attach(port, NULL);
5538 dev->handle_destroy(dev);
5539 port->next = free_usb_ports;
5540 free_usb_ports = port;
5541 return 0;
5544 void do_usb_add(const char *devname)
5546 int ret;
5547 ret = usb_device_add(devname);
5548 if (ret < 0)
5549 term_printf("Could not add USB device '%s'\n", devname);
5552 void do_usb_del(const char *devname)
5554 int ret;
5555 ret = usb_device_del(devname);
5556 if (ret < 0)
5557 term_printf("Could not remove USB device '%s'\n", devname);
5560 void usb_info(void)
5562 USBDevice *dev;
5563 USBPort *port;
5564 const char *speed_str;
5566 if (!usb_enabled) {
5567 term_printf("USB support not enabled\n");
5568 return;
5571 for (port = used_usb_ports; port; port = port->next) {
5572 dev = port->dev;
5573 if (!dev)
5574 continue;
5575 switch(dev->speed) {
5576 case USB_SPEED_LOW:
5577 speed_str = "1.5";
5578 break;
5579 case USB_SPEED_FULL:
5580 speed_str = "12";
5581 break;
5582 case USB_SPEED_HIGH:
5583 speed_str = "480";
5584 break;
5585 default:
5586 speed_str = "?";
5587 break;
5589 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5590 0, dev->addr, speed_str, dev->devname);
5594 /***********************************************************/
5595 /* PCMCIA/Cardbus */
5597 static struct pcmcia_socket_entry_s {
5598 struct pcmcia_socket_s *socket;
5599 struct pcmcia_socket_entry_s *next;
5600 } *pcmcia_sockets = 0;
5602 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5604 struct pcmcia_socket_entry_s *entry;
5606 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5607 entry->socket = socket;
5608 entry->next = pcmcia_sockets;
5609 pcmcia_sockets = entry;
5612 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5614 struct pcmcia_socket_entry_s *entry, **ptr;
5616 ptr = &pcmcia_sockets;
5617 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5618 if (entry->socket == socket) {
5619 *ptr = entry->next;
5620 qemu_free(entry);
5624 void pcmcia_info(void)
5626 struct pcmcia_socket_entry_s *iter;
5627 if (!pcmcia_sockets)
5628 term_printf("No PCMCIA sockets\n");
5630 for (iter = pcmcia_sockets; iter; iter = iter->next)
5631 term_printf("%s: %s\n", iter->socket->slot_string,
5632 iter->socket->attached ? iter->socket->card_string :
5633 "Empty");
5636 /***********************************************************/
5637 /* dumb display */
5639 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5643 static void dumb_resize(DisplayState *ds, int w, int h)
5647 static void dumb_refresh(DisplayState *ds)
5649 #if defined(CONFIG_SDL)
5650 vga_hw_update();
5651 #endif
5654 static void dumb_display_init(DisplayState *ds)
5656 ds->data = NULL;
5657 ds->linesize = 0;
5658 ds->depth = 0;
5659 ds->dpy_update = dumb_update;
5660 ds->dpy_resize = dumb_resize;
5661 ds->dpy_refresh = dumb_refresh;
5664 /***********************************************************/
5665 /* I/O handling */
5667 #define MAX_IO_HANDLERS 64
5669 typedef struct IOHandlerRecord {
5670 int fd;
5671 IOCanRWHandler *fd_read_poll;
5672 IOHandler *fd_read;
5673 IOHandler *fd_write;
5674 int deleted;
5675 void *opaque;
5676 /* temporary data */
5677 struct pollfd *ufd;
5678 struct IOHandlerRecord *next;
5679 } IOHandlerRecord;
5681 static IOHandlerRecord *first_io_handler;
5683 /* XXX: fd_read_poll should be suppressed, but an API change is
5684 necessary in the character devices to suppress fd_can_read(). */
5685 int qemu_set_fd_handler2(int fd,
5686 IOCanRWHandler *fd_read_poll,
5687 IOHandler *fd_read,
5688 IOHandler *fd_write,
5689 void *opaque)
5691 IOHandlerRecord **pioh, *ioh;
5693 if (!fd_read && !fd_write) {
5694 pioh = &first_io_handler;
5695 for(;;) {
5696 ioh = *pioh;
5697 if (ioh == NULL)
5698 break;
5699 if (ioh->fd == fd) {
5700 ioh->deleted = 1;
5701 break;
5703 pioh = &ioh->next;
5705 } else {
5706 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5707 if (ioh->fd == fd)
5708 goto found;
5710 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5711 if (!ioh)
5712 return -1;
5713 ioh->next = first_io_handler;
5714 first_io_handler = ioh;
5715 found:
5716 ioh->fd = fd;
5717 ioh->fd_read_poll = fd_read_poll;
5718 ioh->fd_read = fd_read;
5719 ioh->fd_write = fd_write;
5720 ioh->opaque = opaque;
5721 ioh->deleted = 0;
5723 return 0;
5726 int qemu_set_fd_handler(int fd,
5727 IOHandler *fd_read,
5728 IOHandler *fd_write,
5729 void *opaque)
5731 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5734 /***********************************************************/
5735 /* Polling handling */
5737 typedef struct PollingEntry {
5738 PollingFunc *func;
5739 void *opaque;
5740 struct PollingEntry *next;
5741 } PollingEntry;
5743 static PollingEntry *first_polling_entry;
5745 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5747 PollingEntry **ppe, *pe;
5748 pe = qemu_mallocz(sizeof(PollingEntry));
5749 if (!pe)
5750 return -1;
5751 pe->func = func;
5752 pe->opaque = opaque;
5753 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5754 *ppe = pe;
5755 return 0;
5758 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5760 PollingEntry **ppe, *pe;
5761 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5762 pe = *ppe;
5763 if (pe->func == func && pe->opaque == opaque) {
5764 *ppe = pe->next;
5765 qemu_free(pe);
5766 break;
5771 #ifdef _WIN32
5772 /***********************************************************/
5773 /* Wait objects support */
5774 typedef struct WaitObjects {
5775 int num;
5776 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5777 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5778 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5779 } WaitObjects;
5781 static WaitObjects wait_objects = {0};
5783 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5785 WaitObjects *w = &wait_objects;
5787 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5788 return -1;
5789 w->events[w->num] = handle;
5790 w->func[w->num] = func;
5791 w->opaque[w->num] = opaque;
5792 w->num++;
5793 return 0;
5796 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5798 int i, found;
5799 WaitObjects *w = &wait_objects;
5801 found = 0;
5802 for (i = 0; i < w->num; i++) {
5803 if (w->events[i] == handle)
5804 found = 1;
5805 if (found) {
5806 w->events[i] = w->events[i + 1];
5807 w->func[i] = w->func[i + 1];
5808 w->opaque[i] = w->opaque[i + 1];
5811 if (found)
5812 w->num--;
5814 #endif
5816 /***********************************************************/
5817 /* savevm/loadvm support */
5819 #define IO_BUF_SIZE 32768
5821 struct QEMUFile {
5822 FILE *outfile;
5823 BlockDriverState *bs;
5824 int is_file;
5825 int is_writable;
5826 int64_t base_offset;
5827 int64_t buf_offset; /* start of buffer when writing, end of buffer
5828 when reading */
5829 int buf_index;
5830 int buf_size; /* 0 when writing */
5831 uint8_t buf[IO_BUF_SIZE];
5834 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5836 QEMUFile *f;
5838 f = qemu_mallocz(sizeof(QEMUFile));
5839 if (!f)
5840 return NULL;
5841 if (!strcmp(mode, "wb")) {
5842 f->is_writable = 1;
5843 } else if (!strcmp(mode, "rb")) {
5844 f->is_writable = 0;
5845 } else {
5846 goto fail;
5848 f->outfile = fopen(filename, mode);
5849 if (!f->outfile)
5850 goto fail;
5851 f->is_file = 1;
5852 return f;
5853 fail:
5854 if (f->outfile)
5855 fclose(f->outfile);
5856 qemu_free(f);
5857 return NULL;
5860 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5862 QEMUFile *f;
5864 f = qemu_mallocz(sizeof(QEMUFile));
5865 if (!f)
5866 return NULL;
5867 f->is_file = 0;
5868 f->bs = bs;
5869 f->is_writable = is_writable;
5870 f->base_offset = offset;
5871 return f;
5874 void qemu_fflush(QEMUFile *f)
5876 if (!f->is_writable)
5877 return;
5878 if (f->buf_index > 0) {
5879 if (f->is_file) {
5880 fseek(f->outfile, f->buf_offset, SEEK_SET);
5881 fwrite(f->buf, 1, f->buf_index, f->outfile);
5882 } else {
5883 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5884 f->buf, f->buf_index);
5886 f->buf_offset += f->buf_index;
5887 f->buf_index = 0;
5891 static void qemu_fill_buffer(QEMUFile *f)
5893 int len;
5895 if (f->is_writable)
5896 return;
5897 if (f->is_file) {
5898 fseek(f->outfile, f->buf_offset, SEEK_SET);
5899 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5900 if (len < 0)
5901 len = 0;
5902 } else {
5903 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5904 f->buf, IO_BUF_SIZE);
5905 if (len < 0)
5906 len = 0;
5908 f->buf_index = 0;
5909 f->buf_size = len;
5910 f->buf_offset += len;
5913 void qemu_fclose(QEMUFile *f)
5915 if (f->is_writable)
5916 qemu_fflush(f);
5917 if (f->is_file) {
5918 fclose(f->outfile);
5920 qemu_free(f);
5923 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5925 int l;
5926 while (size > 0) {
5927 l = IO_BUF_SIZE - f->buf_index;
5928 if (l > size)
5929 l = size;
5930 memcpy(f->buf + f->buf_index, buf, l);
5931 f->buf_index += l;
5932 buf += l;
5933 size -= l;
5934 if (f->buf_index >= IO_BUF_SIZE)
5935 qemu_fflush(f);
5939 void qemu_put_byte(QEMUFile *f, int v)
5941 f->buf[f->buf_index++] = v;
5942 if (f->buf_index >= IO_BUF_SIZE)
5943 qemu_fflush(f);
5946 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5948 int size, l;
5950 size = size1;
5951 while (size > 0) {
5952 l = f->buf_size - f->buf_index;
5953 if (l == 0) {
5954 qemu_fill_buffer(f);
5955 l = f->buf_size - f->buf_index;
5956 if (l == 0)
5957 break;
5959 if (l > size)
5960 l = size;
5961 memcpy(buf, f->buf + f->buf_index, l);
5962 f->buf_index += l;
5963 buf += l;
5964 size -= l;
5966 return size1 - size;
5969 int qemu_get_byte(QEMUFile *f)
5971 if (f->buf_index >= f->buf_size) {
5972 qemu_fill_buffer(f);
5973 if (f->buf_index >= f->buf_size)
5974 return 0;
5976 return f->buf[f->buf_index++];
5979 int64_t qemu_ftell(QEMUFile *f)
5981 return f->buf_offset - f->buf_size + f->buf_index;
5984 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5986 if (whence == SEEK_SET) {
5987 /* nothing to do */
5988 } else if (whence == SEEK_CUR) {
5989 pos += qemu_ftell(f);
5990 } else {
5991 /* SEEK_END not supported */
5992 return -1;
5994 if (f->is_writable) {
5995 qemu_fflush(f);
5996 f->buf_offset = pos;
5997 } else {
5998 f->buf_offset = pos;
5999 f->buf_index = 0;
6000 f->buf_size = 0;
6002 return pos;
6005 void qemu_put_be16(QEMUFile *f, unsigned int v)
6007 qemu_put_byte(f, v >> 8);
6008 qemu_put_byte(f, v);
6011 void qemu_put_be32(QEMUFile *f, unsigned int v)
6013 qemu_put_byte(f, v >> 24);
6014 qemu_put_byte(f, v >> 16);
6015 qemu_put_byte(f, v >> 8);
6016 qemu_put_byte(f, v);
6019 void qemu_put_be64(QEMUFile *f, uint64_t v)
6021 qemu_put_be32(f, v >> 32);
6022 qemu_put_be32(f, v);
6025 unsigned int qemu_get_be16(QEMUFile *f)
6027 unsigned int v;
6028 v = qemu_get_byte(f) << 8;
6029 v |= qemu_get_byte(f);
6030 return v;
6033 unsigned int qemu_get_be32(QEMUFile *f)
6035 unsigned int v;
6036 v = qemu_get_byte(f) << 24;
6037 v |= qemu_get_byte(f) << 16;
6038 v |= qemu_get_byte(f) << 8;
6039 v |= qemu_get_byte(f);
6040 return v;
6043 uint64_t qemu_get_be64(QEMUFile *f)
6045 uint64_t v;
6046 v = (uint64_t)qemu_get_be32(f) << 32;
6047 v |= qemu_get_be32(f);
6048 return v;
6051 typedef struct SaveStateEntry {
6052 char idstr[256];
6053 int instance_id;
6054 int version_id;
6055 SaveStateHandler *save_state;
6056 LoadStateHandler *load_state;
6057 void *opaque;
6058 struct SaveStateEntry *next;
6059 } SaveStateEntry;
6061 static SaveStateEntry *first_se;
6063 /* TODO: Individual devices generally have very little idea about the rest
6064 of the system, so instance_id should be removed/replaced. */
6065 int register_savevm(const char *idstr,
6066 int instance_id,
6067 int version_id,
6068 SaveStateHandler *save_state,
6069 LoadStateHandler *load_state,
6070 void *opaque)
6072 SaveStateEntry *se, **pse;
6074 se = qemu_malloc(sizeof(SaveStateEntry));
6075 if (!se)
6076 return -1;
6077 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6078 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6079 se->version_id = version_id;
6080 se->save_state = save_state;
6081 se->load_state = load_state;
6082 se->opaque = opaque;
6083 se->next = NULL;
6085 /* add at the end of list */
6086 pse = &first_se;
6087 while (*pse != NULL) {
6088 if (instance_id == -1
6089 && strcmp(se->idstr, (*pse)->idstr) == 0
6090 && se->instance_id <= (*pse)->instance_id)
6091 se->instance_id = (*pse)->instance_id + 1;
6092 pse = &(*pse)->next;
6094 *pse = se;
6095 return 0;
6098 #define QEMU_VM_FILE_MAGIC 0x5145564d
6099 #define QEMU_VM_FILE_VERSION 0x00000002
6101 static int qemu_savevm_state(QEMUFile *f)
6103 SaveStateEntry *se;
6104 int len, ret;
6105 int64_t cur_pos, len_pos, total_len_pos;
6107 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6108 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6109 total_len_pos = qemu_ftell(f);
6110 qemu_put_be64(f, 0); /* total size */
6112 for(se = first_se; se != NULL; se = se->next) {
6113 if (se->save_state == NULL)
6114 /* this one has a loader only, for backwards compatibility */
6115 continue;
6117 /* ID string */
6118 len = strlen(se->idstr);
6119 qemu_put_byte(f, len);
6120 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6122 qemu_put_be32(f, se->instance_id);
6123 qemu_put_be32(f, se->version_id);
6125 /* record size: filled later */
6126 len_pos = qemu_ftell(f);
6127 qemu_put_be32(f, 0);
6128 se->save_state(f, se->opaque);
6130 /* fill record size */
6131 cur_pos = qemu_ftell(f);
6132 len = cur_pos - len_pos - 4;
6133 qemu_fseek(f, len_pos, SEEK_SET);
6134 qemu_put_be32(f, len);
6135 qemu_fseek(f, cur_pos, SEEK_SET);
6137 cur_pos = qemu_ftell(f);
6138 qemu_fseek(f, total_len_pos, SEEK_SET);
6139 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6140 qemu_fseek(f, cur_pos, SEEK_SET);
6142 ret = 0;
6143 return ret;
6146 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6148 SaveStateEntry *se;
6150 for(se = first_se; se != NULL; se = se->next) {
6151 if (!strcmp(se->idstr, idstr) &&
6152 instance_id == se->instance_id)
6153 return se;
6155 return NULL;
6158 static int qemu_loadvm_state(QEMUFile *f)
6160 SaveStateEntry *se;
6161 int len, ret, instance_id, record_len, version_id;
6162 int64_t total_len, end_pos, cur_pos;
6163 unsigned int v;
6164 char idstr[256];
6166 v = qemu_get_be32(f);
6167 if (v != QEMU_VM_FILE_MAGIC)
6168 goto fail;
6169 v = qemu_get_be32(f);
6170 if (v != QEMU_VM_FILE_VERSION) {
6171 fail:
6172 ret = -1;
6173 goto the_end;
6175 total_len = qemu_get_be64(f);
6176 end_pos = total_len + qemu_ftell(f);
6177 for(;;) {
6178 if (qemu_ftell(f) >= end_pos)
6179 break;
6180 len = qemu_get_byte(f);
6181 qemu_get_buffer(f, (uint8_t *)idstr, len);
6182 idstr[len] = '\0';
6183 instance_id = qemu_get_be32(f);
6184 version_id = qemu_get_be32(f);
6185 record_len = qemu_get_be32(f);
6186 #if 0
6187 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6188 idstr, instance_id, version_id, record_len);
6189 #endif
6190 cur_pos = qemu_ftell(f);
6191 se = find_se(idstr, instance_id);
6192 if (!se) {
6193 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6194 instance_id, idstr);
6195 } else {
6196 ret = se->load_state(f, se->opaque, version_id);
6197 if (ret < 0) {
6198 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6199 instance_id, idstr);
6202 /* always seek to exact end of record */
6203 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6205 ret = 0;
6206 the_end:
6207 return ret;
6210 /* device can contain snapshots */
6211 static int bdrv_can_snapshot(BlockDriverState *bs)
6213 return (bs &&
6214 !bdrv_is_removable(bs) &&
6215 !bdrv_is_read_only(bs));
6218 /* device must be snapshots in order to have a reliable snapshot */
6219 static int bdrv_has_snapshot(BlockDriverState *bs)
6221 return (bs &&
6222 !bdrv_is_removable(bs) &&
6223 !bdrv_is_read_only(bs));
6226 static BlockDriverState *get_bs_snapshots(void)
6228 BlockDriverState *bs;
6229 int i;
6231 if (bs_snapshots)
6232 return bs_snapshots;
6233 for(i = 0; i <= nb_drives; i++) {
6234 bs = drives_table[i].bdrv;
6235 if (bdrv_can_snapshot(bs))
6236 goto ok;
6238 return NULL;
6240 bs_snapshots = bs;
6241 return bs;
6244 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6245 const char *name)
6247 QEMUSnapshotInfo *sn_tab, *sn;
6248 int nb_sns, i, ret;
6250 ret = -ENOENT;
6251 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6252 if (nb_sns < 0)
6253 return ret;
6254 for(i = 0; i < nb_sns; i++) {
6255 sn = &sn_tab[i];
6256 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6257 *sn_info = *sn;
6258 ret = 0;
6259 break;
6262 qemu_free(sn_tab);
6263 return ret;
6266 void do_savevm(const char *name)
6268 BlockDriverState *bs, *bs1;
6269 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6270 int must_delete, ret, i;
6271 BlockDriverInfo bdi1, *bdi = &bdi1;
6272 QEMUFile *f;
6273 int saved_vm_running;
6274 #ifdef _WIN32
6275 struct _timeb tb;
6276 #else
6277 struct timeval tv;
6278 #endif
6280 bs = get_bs_snapshots();
6281 if (!bs) {
6282 term_printf("No block device can accept snapshots\n");
6283 return;
6286 /* ??? Should this occur after vm_stop? */
6287 qemu_aio_flush();
6289 saved_vm_running = vm_running;
6290 vm_stop(0);
6292 must_delete = 0;
6293 if (name) {
6294 ret = bdrv_snapshot_find(bs, old_sn, name);
6295 if (ret >= 0) {
6296 must_delete = 1;
6299 memset(sn, 0, sizeof(*sn));
6300 if (must_delete) {
6301 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6302 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6303 } else {
6304 if (name)
6305 pstrcpy(sn->name, sizeof(sn->name), name);
6308 /* fill auxiliary fields */
6309 #ifdef _WIN32
6310 _ftime(&tb);
6311 sn->date_sec = tb.time;
6312 sn->date_nsec = tb.millitm * 1000000;
6313 #else
6314 gettimeofday(&tv, NULL);
6315 sn->date_sec = tv.tv_sec;
6316 sn->date_nsec = tv.tv_usec * 1000;
6317 #endif
6318 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6320 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6321 term_printf("Device %s does not support VM state snapshots\n",
6322 bdrv_get_device_name(bs));
6323 goto the_end;
6326 /* save the VM state */
6327 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6328 if (!f) {
6329 term_printf("Could not open VM state file\n");
6330 goto the_end;
6332 ret = qemu_savevm_state(f);
6333 sn->vm_state_size = qemu_ftell(f);
6334 qemu_fclose(f);
6335 if (ret < 0) {
6336 term_printf("Error %d while writing VM\n", ret);
6337 goto the_end;
6340 /* create the snapshots */
6342 for(i = 0; i < nb_drives; i++) {
6343 bs1 = drives_table[i].bdrv;
6344 if (bdrv_has_snapshot(bs1)) {
6345 if (must_delete) {
6346 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6347 if (ret < 0) {
6348 term_printf("Error while deleting snapshot on '%s'\n",
6349 bdrv_get_device_name(bs1));
6352 ret = bdrv_snapshot_create(bs1, sn);
6353 if (ret < 0) {
6354 term_printf("Error while creating snapshot on '%s'\n",
6355 bdrv_get_device_name(bs1));
6360 the_end:
6361 if (saved_vm_running)
6362 vm_start();
6365 void do_loadvm(const char *name)
6367 BlockDriverState *bs, *bs1;
6368 BlockDriverInfo bdi1, *bdi = &bdi1;
6369 QEMUFile *f;
6370 int i, ret;
6371 int saved_vm_running;
6373 bs = get_bs_snapshots();
6374 if (!bs) {
6375 term_printf("No block device supports snapshots\n");
6376 return;
6379 /* Flush all IO requests so they don't interfere with the new state. */
6380 qemu_aio_flush();
6382 saved_vm_running = vm_running;
6383 vm_stop(0);
6385 for(i = 0; i <= nb_drives; i++) {
6386 bs1 = drives_table[i].bdrv;
6387 if (bdrv_has_snapshot(bs1)) {
6388 ret = bdrv_snapshot_goto(bs1, name);
6389 if (ret < 0) {
6390 if (bs != bs1)
6391 term_printf("Warning: ");
6392 switch(ret) {
6393 case -ENOTSUP:
6394 term_printf("Snapshots not supported on device '%s'\n",
6395 bdrv_get_device_name(bs1));
6396 break;
6397 case -ENOENT:
6398 term_printf("Could not find snapshot '%s' on device '%s'\n",
6399 name, bdrv_get_device_name(bs1));
6400 break;
6401 default:
6402 term_printf("Error %d while activating snapshot on '%s'\n",
6403 ret, bdrv_get_device_name(bs1));
6404 break;
6406 /* fatal on snapshot block device */
6407 if (bs == bs1)
6408 goto the_end;
6413 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6414 term_printf("Device %s does not support VM state snapshots\n",
6415 bdrv_get_device_name(bs));
6416 return;
6419 /* restore the VM state */
6420 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6421 if (!f) {
6422 term_printf("Could not open VM state file\n");
6423 goto the_end;
6425 ret = qemu_loadvm_state(f);
6426 qemu_fclose(f);
6427 if (ret < 0) {
6428 term_printf("Error %d while loading VM state\n", ret);
6430 the_end:
6431 if (saved_vm_running)
6432 vm_start();
6435 void do_delvm(const char *name)
6437 BlockDriverState *bs, *bs1;
6438 int i, ret;
6440 bs = get_bs_snapshots();
6441 if (!bs) {
6442 term_printf("No block device supports snapshots\n");
6443 return;
6446 for(i = 0; i <= nb_drives; i++) {
6447 bs1 = drives_table[i].bdrv;
6448 if (bdrv_has_snapshot(bs1)) {
6449 ret = bdrv_snapshot_delete(bs1, name);
6450 if (ret < 0) {
6451 if (ret == -ENOTSUP)
6452 term_printf("Snapshots not supported on device '%s'\n",
6453 bdrv_get_device_name(bs1));
6454 else
6455 term_printf("Error %d while deleting snapshot on '%s'\n",
6456 ret, bdrv_get_device_name(bs1));
6462 void do_info_snapshots(void)
6464 BlockDriverState *bs, *bs1;
6465 QEMUSnapshotInfo *sn_tab, *sn;
6466 int nb_sns, i;
6467 char buf[256];
6469 bs = get_bs_snapshots();
6470 if (!bs) {
6471 term_printf("No available block device supports snapshots\n");
6472 return;
6474 term_printf("Snapshot devices:");
6475 for(i = 0; i <= nb_drives; i++) {
6476 bs1 = drives_table[i].bdrv;
6477 if (bdrv_has_snapshot(bs1)) {
6478 if (bs == bs1)
6479 term_printf(" %s", bdrv_get_device_name(bs1));
6482 term_printf("\n");
6484 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6485 if (nb_sns < 0) {
6486 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6487 return;
6489 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6490 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6491 for(i = 0; i < nb_sns; i++) {
6492 sn = &sn_tab[i];
6493 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6495 qemu_free(sn_tab);
6498 /***********************************************************/
6499 /* ram save/restore */
6501 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6503 int v;
6505 v = qemu_get_byte(f);
6506 switch(v) {
6507 case 0:
6508 if (qemu_get_buffer(f, buf, len) != len)
6509 return -EIO;
6510 break;
6511 case 1:
6512 v = qemu_get_byte(f);
6513 memset(buf, v, len);
6514 break;
6515 default:
6516 return -EINVAL;
6518 return 0;
6521 static int ram_load_v1(QEMUFile *f, void *opaque)
6523 int ret;
6524 ram_addr_t i;
6526 if (qemu_get_be32(f) != phys_ram_size)
6527 return -EINVAL;
6528 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6529 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6530 if (ret)
6531 return ret;
6533 return 0;
6536 #define BDRV_HASH_BLOCK_SIZE 1024
6537 #define IOBUF_SIZE 4096
6538 #define RAM_CBLOCK_MAGIC 0xfabe
6540 typedef struct RamCompressState {
6541 z_stream zstream;
6542 QEMUFile *f;
6543 uint8_t buf[IOBUF_SIZE];
6544 } RamCompressState;
6546 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6548 int ret;
6549 memset(s, 0, sizeof(*s));
6550 s->f = f;
6551 ret = deflateInit2(&s->zstream, 1,
6552 Z_DEFLATED, 15,
6553 9, Z_DEFAULT_STRATEGY);
6554 if (ret != Z_OK)
6555 return -1;
6556 s->zstream.avail_out = IOBUF_SIZE;
6557 s->zstream.next_out = s->buf;
6558 return 0;
6561 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6563 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6564 qemu_put_be16(s->f, len);
6565 qemu_put_buffer(s->f, buf, len);
6568 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6570 int ret;
6572 s->zstream.avail_in = len;
6573 s->zstream.next_in = (uint8_t *)buf;
6574 while (s->zstream.avail_in > 0) {
6575 ret = deflate(&s->zstream, Z_NO_FLUSH);
6576 if (ret != Z_OK)
6577 return -1;
6578 if (s->zstream.avail_out == 0) {
6579 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6580 s->zstream.avail_out = IOBUF_SIZE;
6581 s->zstream.next_out = s->buf;
6584 return 0;
6587 static void ram_compress_close(RamCompressState *s)
6589 int len, ret;
6591 /* compress last bytes */
6592 for(;;) {
6593 ret = deflate(&s->zstream, Z_FINISH);
6594 if (ret == Z_OK || ret == Z_STREAM_END) {
6595 len = IOBUF_SIZE - s->zstream.avail_out;
6596 if (len > 0) {
6597 ram_put_cblock(s, s->buf, len);
6599 s->zstream.avail_out = IOBUF_SIZE;
6600 s->zstream.next_out = s->buf;
6601 if (ret == Z_STREAM_END)
6602 break;
6603 } else {
6604 goto fail;
6607 fail:
6608 deflateEnd(&s->zstream);
6611 typedef struct RamDecompressState {
6612 z_stream zstream;
6613 QEMUFile *f;
6614 uint8_t buf[IOBUF_SIZE];
6615 } RamDecompressState;
6617 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6619 int ret;
6620 memset(s, 0, sizeof(*s));
6621 s->f = f;
6622 ret = inflateInit(&s->zstream);
6623 if (ret != Z_OK)
6624 return -1;
6625 return 0;
6628 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6630 int ret, clen;
6632 s->zstream.avail_out = len;
6633 s->zstream.next_out = buf;
6634 while (s->zstream.avail_out > 0) {
6635 if (s->zstream.avail_in == 0) {
6636 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6637 return -1;
6638 clen = qemu_get_be16(s->f);
6639 if (clen > IOBUF_SIZE)
6640 return -1;
6641 qemu_get_buffer(s->f, s->buf, clen);
6642 s->zstream.avail_in = clen;
6643 s->zstream.next_in = s->buf;
6645 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6646 if (ret != Z_OK && ret != Z_STREAM_END) {
6647 return -1;
6650 return 0;
6653 static void ram_decompress_close(RamDecompressState *s)
6655 inflateEnd(&s->zstream);
6658 static void ram_save(QEMUFile *f, void *opaque)
6660 ram_addr_t i;
6661 RamCompressState s1, *s = &s1;
6662 uint8_t buf[10];
6664 qemu_put_be32(f, phys_ram_size);
6665 if (ram_compress_open(s, f) < 0)
6666 return;
6667 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6668 #if 0
6669 if (tight_savevm_enabled) {
6670 int64_t sector_num;
6671 int j;
6673 /* find if the memory block is available on a virtual
6674 block device */
6675 sector_num = -1;
6676 for(j = 0; j < nb_drives; j++) {
6677 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6678 phys_ram_base + i,
6679 BDRV_HASH_BLOCK_SIZE);
6680 if (sector_num >= 0)
6681 break;
6683 if (j == nb_drives)
6684 goto normal_compress;
6685 buf[0] = 1;
6686 buf[1] = j;
6687 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6688 ram_compress_buf(s, buf, 10);
6689 } else
6690 #endif
6692 // normal_compress:
6693 buf[0] = 0;
6694 ram_compress_buf(s, buf, 1);
6695 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6698 ram_compress_close(s);
6701 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6703 RamDecompressState s1, *s = &s1;
6704 uint8_t buf[10];
6705 ram_addr_t i;
6707 if (version_id == 1)
6708 return ram_load_v1(f, opaque);
6709 if (version_id != 2)
6710 return -EINVAL;
6711 if (qemu_get_be32(f) != phys_ram_size)
6712 return -EINVAL;
6713 if (ram_decompress_open(s, f) < 0)
6714 return -EINVAL;
6715 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6716 if (ram_decompress_buf(s, buf, 1) < 0) {
6717 fprintf(stderr, "Error while reading ram block header\n");
6718 goto error;
6720 if (buf[0] == 0) {
6721 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6722 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
6723 goto error;
6725 } else
6726 #if 0
6727 if (buf[0] == 1) {
6728 int bs_index;
6729 int64_t sector_num;
6731 ram_decompress_buf(s, buf + 1, 9);
6732 bs_index = buf[1];
6733 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6734 if (bs_index >= nb_drives) {
6735 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6736 goto error;
6738 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6739 phys_ram_base + i,
6740 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6741 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6742 bs_index, sector_num);
6743 goto error;
6745 } else
6746 #endif
6748 error:
6749 printf("Error block header\n");
6750 return -EINVAL;
6753 ram_decompress_close(s);
6754 return 0;
6757 /***********************************************************/
6758 /* bottom halves (can be seen as timers which expire ASAP) */
6760 struct QEMUBH {
6761 QEMUBHFunc *cb;
6762 void *opaque;
6763 int scheduled;
6764 QEMUBH *next;
6767 static QEMUBH *first_bh = NULL;
6769 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6771 QEMUBH *bh;
6772 bh = qemu_mallocz(sizeof(QEMUBH));
6773 if (!bh)
6774 return NULL;
6775 bh->cb = cb;
6776 bh->opaque = opaque;
6777 return bh;
6780 int qemu_bh_poll(void)
6782 QEMUBH *bh, **pbh;
6783 int ret;
6785 ret = 0;
6786 for(;;) {
6787 pbh = &first_bh;
6788 bh = *pbh;
6789 if (!bh)
6790 break;
6791 ret = 1;
6792 *pbh = bh->next;
6793 bh->scheduled = 0;
6794 bh->cb(bh->opaque);
6796 return ret;
6799 void qemu_bh_schedule(QEMUBH *bh)
6801 CPUState *env = cpu_single_env;
6802 if (bh->scheduled)
6803 return;
6804 bh->scheduled = 1;
6805 bh->next = first_bh;
6806 first_bh = bh;
6808 /* stop the currently executing CPU to execute the BH ASAP */
6809 if (env) {
6810 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6814 void qemu_bh_cancel(QEMUBH *bh)
6816 QEMUBH **pbh;
6817 if (bh->scheduled) {
6818 pbh = &first_bh;
6819 while (*pbh != bh)
6820 pbh = &(*pbh)->next;
6821 *pbh = bh->next;
6822 bh->scheduled = 0;
6826 void qemu_bh_delete(QEMUBH *bh)
6828 qemu_bh_cancel(bh);
6829 qemu_free(bh);
6832 /***********************************************************/
6833 /* machine registration */
6835 QEMUMachine *first_machine = NULL;
6837 int qemu_register_machine(QEMUMachine *m)
6839 QEMUMachine **pm;
6840 pm = &first_machine;
6841 while (*pm != NULL)
6842 pm = &(*pm)->next;
6843 m->next = NULL;
6844 *pm = m;
6845 return 0;
6848 static QEMUMachine *find_machine(const char *name)
6850 QEMUMachine *m;
6852 for(m = first_machine; m != NULL; m = m->next) {
6853 if (!strcmp(m->name, name))
6854 return m;
6856 return NULL;
6859 /***********************************************************/
6860 /* main execution loop */
6862 static void gui_update(void *opaque)
6864 DisplayState *ds = opaque;
6865 ds->dpy_refresh(ds);
6866 qemu_mod_timer(ds->gui_timer,
6867 (ds->gui_timer_interval ?
6868 ds->gui_timer_interval :
6869 GUI_REFRESH_INTERVAL)
6870 + qemu_get_clock(rt_clock));
6873 struct vm_change_state_entry {
6874 VMChangeStateHandler *cb;
6875 void *opaque;
6876 LIST_ENTRY (vm_change_state_entry) entries;
6879 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6881 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6882 void *opaque)
6884 VMChangeStateEntry *e;
6886 e = qemu_mallocz(sizeof (*e));
6887 if (!e)
6888 return NULL;
6890 e->cb = cb;
6891 e->opaque = opaque;
6892 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6893 return e;
6896 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6898 LIST_REMOVE (e, entries);
6899 qemu_free (e);
6902 static void vm_state_notify(int running)
6904 VMChangeStateEntry *e;
6906 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6907 e->cb(e->opaque, running);
6911 /* XXX: support several handlers */
6912 static VMStopHandler *vm_stop_cb;
6913 static void *vm_stop_opaque;
6915 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6917 vm_stop_cb = cb;
6918 vm_stop_opaque = opaque;
6919 return 0;
6922 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6924 vm_stop_cb = NULL;
6927 void vm_start(void)
6929 if (!vm_running) {
6930 cpu_enable_ticks();
6931 vm_running = 1;
6932 vm_state_notify(1);
6933 qemu_rearm_alarm_timer(alarm_timer);
6937 void vm_stop(int reason)
6939 if (vm_running) {
6940 cpu_disable_ticks();
6941 vm_running = 0;
6942 if (reason != 0) {
6943 if (vm_stop_cb) {
6944 vm_stop_cb(vm_stop_opaque, reason);
6947 vm_state_notify(0);
6951 /* reset/shutdown handler */
6953 typedef struct QEMUResetEntry {
6954 QEMUResetHandler *func;
6955 void *opaque;
6956 struct QEMUResetEntry *next;
6957 } QEMUResetEntry;
6959 static QEMUResetEntry *first_reset_entry;
6960 static int reset_requested;
6961 static int shutdown_requested;
6962 static int powerdown_requested;
6964 int qemu_shutdown_requested(void)
6966 int r = shutdown_requested;
6967 shutdown_requested = 0;
6968 return r;
6971 int qemu_reset_requested(void)
6973 int r = reset_requested;
6974 reset_requested = 0;
6975 return r;
6978 int qemu_powerdown_requested(void)
6980 int r = powerdown_requested;
6981 powerdown_requested = 0;
6982 return r;
6985 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6987 QEMUResetEntry **pre, *re;
6989 pre = &first_reset_entry;
6990 while (*pre != NULL)
6991 pre = &(*pre)->next;
6992 re = qemu_mallocz(sizeof(QEMUResetEntry));
6993 re->func = func;
6994 re->opaque = opaque;
6995 re->next = NULL;
6996 *pre = re;
6999 void qemu_system_reset(void)
7001 QEMUResetEntry *re;
7003 /* reset all devices */
7004 for(re = first_reset_entry; re != NULL; re = re->next) {
7005 re->func(re->opaque);
7009 void qemu_system_reset_request(void)
7011 if (no_reboot) {
7012 shutdown_requested = 1;
7013 } else {
7014 reset_requested = 1;
7016 if (cpu_single_env)
7017 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7020 void qemu_system_shutdown_request(void)
7022 shutdown_requested = 1;
7023 if (cpu_single_env)
7024 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7027 void qemu_system_powerdown_request(void)
7029 powerdown_requested = 1;
7030 if (cpu_single_env)
7031 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7034 void main_loop_wait(int timeout)
7036 IOHandlerRecord *ioh;
7037 fd_set rfds, wfds, xfds;
7038 int ret, nfds;
7039 #ifdef _WIN32
7040 int ret2, i;
7041 #endif
7042 struct timeval tv;
7043 PollingEntry *pe;
7046 /* XXX: need to suppress polling by better using win32 events */
7047 ret = 0;
7048 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7049 ret |= pe->func(pe->opaque);
7051 #ifdef _WIN32
7052 if (ret == 0) {
7053 int err;
7054 WaitObjects *w = &wait_objects;
7056 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7057 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7058 if (w->func[ret - WAIT_OBJECT_0])
7059 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7061 /* Check for additional signaled events */
7062 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7064 /* Check if event is signaled */
7065 ret2 = WaitForSingleObject(w->events[i], 0);
7066 if(ret2 == WAIT_OBJECT_0) {
7067 if (w->func[i])
7068 w->func[i](w->opaque[i]);
7069 } else if (ret2 == WAIT_TIMEOUT) {
7070 } else {
7071 err = GetLastError();
7072 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7075 } else if (ret == WAIT_TIMEOUT) {
7076 } else {
7077 err = GetLastError();
7078 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7081 #endif
7082 /* poll any events */
7083 /* XXX: separate device handlers from system ones */
7084 nfds = -1;
7085 FD_ZERO(&rfds);
7086 FD_ZERO(&wfds);
7087 FD_ZERO(&xfds);
7088 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7089 if (ioh->deleted)
7090 continue;
7091 if (ioh->fd_read &&
7092 (!ioh->fd_read_poll ||
7093 ioh->fd_read_poll(ioh->opaque) != 0)) {
7094 FD_SET(ioh->fd, &rfds);
7095 if (ioh->fd > nfds)
7096 nfds = ioh->fd;
7098 if (ioh->fd_write) {
7099 FD_SET(ioh->fd, &wfds);
7100 if (ioh->fd > nfds)
7101 nfds = ioh->fd;
7105 tv.tv_sec = 0;
7106 #ifdef _WIN32
7107 tv.tv_usec = 0;
7108 #else
7109 tv.tv_usec = timeout * 1000;
7110 #endif
7111 #if defined(CONFIG_SLIRP)
7112 if (slirp_inited) {
7113 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7115 #endif
7116 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7117 if (ret > 0) {
7118 IOHandlerRecord **pioh;
7120 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7121 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7122 ioh->fd_read(ioh->opaque);
7124 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7125 ioh->fd_write(ioh->opaque);
7129 /* remove deleted IO handlers */
7130 pioh = &first_io_handler;
7131 while (*pioh) {
7132 ioh = *pioh;
7133 if (ioh->deleted) {
7134 *pioh = ioh->next;
7135 qemu_free(ioh);
7136 } else
7137 pioh = &ioh->next;
7140 #if defined(CONFIG_SLIRP)
7141 if (slirp_inited) {
7142 if (ret < 0) {
7143 FD_ZERO(&rfds);
7144 FD_ZERO(&wfds);
7145 FD_ZERO(&xfds);
7147 slirp_select_poll(&rfds, &wfds, &xfds);
7149 #endif
7150 qemu_aio_poll();
7152 if (vm_running) {
7153 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7154 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7155 qemu_get_clock(vm_clock));
7156 /* run dma transfers, if any */
7157 DMA_run();
7160 /* real time timers */
7161 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7162 qemu_get_clock(rt_clock));
7164 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7165 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7166 qemu_rearm_alarm_timer(alarm_timer);
7169 /* Check bottom-halves last in case any of the earlier events triggered
7170 them. */
7171 qemu_bh_poll();
7175 static int main_loop(void)
7177 int ret, timeout;
7178 #ifdef CONFIG_PROFILER
7179 int64_t ti;
7180 #endif
7181 CPUState *env;
7183 cur_cpu = first_cpu;
7184 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7185 for(;;) {
7186 if (vm_running) {
7188 for(;;) {
7189 /* get next cpu */
7190 env = next_cpu;
7191 #ifdef CONFIG_PROFILER
7192 ti = profile_getclock();
7193 #endif
7194 if (use_icount) {
7195 int64_t count;
7196 int decr;
7197 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7198 env->icount_decr.u16.low = 0;
7199 env->icount_extra = 0;
7200 count = qemu_next_deadline();
7201 count = (count + (1 << icount_time_shift) - 1)
7202 >> icount_time_shift;
7203 qemu_icount += count;
7204 decr = (count > 0xffff) ? 0xffff : count;
7205 count -= decr;
7206 env->icount_decr.u16.low = decr;
7207 env->icount_extra = count;
7209 ret = cpu_exec(env);
7210 #ifdef CONFIG_PROFILER
7211 qemu_time += profile_getclock() - ti;
7212 #endif
7213 if (use_icount) {
7214 /* Fold pending instructions back into the
7215 instruction counter, and clear the interrupt flag. */
7216 qemu_icount -= (env->icount_decr.u16.low
7217 + env->icount_extra);
7218 env->icount_decr.u32 = 0;
7219 env->icount_extra = 0;
7221 next_cpu = env->next_cpu ?: first_cpu;
7222 if (event_pending && likely(ret != EXCP_DEBUG)) {
7223 ret = EXCP_INTERRUPT;
7224 event_pending = 0;
7225 break;
7227 if (ret == EXCP_HLT) {
7228 /* Give the next CPU a chance to run. */
7229 cur_cpu = env;
7230 continue;
7232 if (ret != EXCP_HALTED)
7233 break;
7234 /* all CPUs are halted ? */
7235 if (env == cur_cpu)
7236 break;
7238 cur_cpu = env;
7240 if (shutdown_requested) {
7241 ret = EXCP_INTERRUPT;
7242 if (no_shutdown) {
7243 vm_stop(0);
7244 no_shutdown = 0;
7246 else
7247 break;
7249 if (reset_requested) {
7250 reset_requested = 0;
7251 qemu_system_reset();
7252 ret = EXCP_INTERRUPT;
7254 if (powerdown_requested) {
7255 powerdown_requested = 0;
7256 qemu_system_powerdown();
7257 ret = EXCP_INTERRUPT;
7259 if (unlikely(ret == EXCP_DEBUG)) {
7260 vm_stop(EXCP_DEBUG);
7262 /* If all cpus are halted then wait until the next IRQ */
7263 /* XXX: use timeout computed from timers */
7264 if (ret == EXCP_HALTED) {
7265 if (use_icount) {
7266 int64_t add;
7267 int64_t delta;
7268 /* Advance virtual time to the next event. */
7269 if (use_icount == 1) {
7270 /* When not using an adaptive execution frequency
7271 we tend to get badly out of sync with real time,
7272 so just delay for a reasonable amount of time. */
7273 delta = 0;
7274 } else {
7275 delta = cpu_get_icount() - cpu_get_clock();
7277 if (delta > 0) {
7278 /* If virtual time is ahead of real time then just
7279 wait for IO. */
7280 timeout = (delta / 1000000) + 1;
7281 } else {
7282 /* Wait for either IO to occur or the next
7283 timer event. */
7284 add = qemu_next_deadline();
7285 /* We advance the timer before checking for IO.
7286 Limit the amount we advance so that early IO
7287 activity won't get the guest too far ahead. */
7288 if (add > 10000000)
7289 add = 10000000;
7290 delta += add;
7291 add = (add + (1 << icount_time_shift) - 1)
7292 >> icount_time_shift;
7293 qemu_icount += add;
7294 timeout = delta / 1000000;
7295 if (timeout < 0)
7296 timeout = 0;
7298 } else {
7299 timeout = 10;
7301 } else {
7302 timeout = 0;
7304 } else {
7305 timeout = 10;
7307 #ifdef CONFIG_PROFILER
7308 ti = profile_getclock();
7309 #endif
7310 main_loop_wait(timeout);
7311 #ifdef CONFIG_PROFILER
7312 dev_time += profile_getclock() - ti;
7313 #endif
7315 cpu_disable_ticks();
7316 return ret;
7319 static void help(int exitcode)
7321 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7322 "usage: %s [options] [disk_image]\n"
7323 "\n"
7324 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7325 "\n"
7326 "Standard options:\n"
7327 "-M machine select emulated machine (-M ? for list)\n"
7328 "-cpu cpu select CPU (-cpu ? for list)\n"
7329 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7330 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7331 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7332 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7333 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7334 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7335 " [,cache=on|off][,format=f]\n"
7336 " use 'file' as a drive image\n"
7337 "-mtdblock file use 'file' as on-board Flash memory image\n"
7338 "-sd file use 'file' as SecureDigital card image\n"
7339 "-pflash file use 'file' as a parallel flash image\n"
7340 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7341 "-snapshot write to temporary files instead of disk image files\n"
7342 #ifdef CONFIG_SDL
7343 "-no-frame open SDL window without a frame and window decorations\n"
7344 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7345 "-no-quit disable SDL window close capability\n"
7346 #endif
7347 #ifdef TARGET_I386
7348 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7349 #endif
7350 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7351 "-smp n set the number of CPUs to 'n' [default=1]\n"
7352 "-nographic disable graphical output and redirect serial I/Os to console\n"
7353 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7354 #ifndef _WIN32
7355 "-k language use keyboard layout (for example \"fr\" for French)\n"
7356 #endif
7357 #ifdef HAS_AUDIO
7358 "-audio-help print list of audio drivers and their options\n"
7359 "-soundhw c1,... enable audio support\n"
7360 " and only specified sound cards (comma separated list)\n"
7361 " use -soundhw ? to get the list of supported cards\n"
7362 " use -soundhw all to enable all of them\n"
7363 #endif
7364 "-localtime set the real time clock to local time [default=utc]\n"
7365 "-full-screen start in full screen\n"
7366 #ifdef TARGET_I386
7367 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7368 #endif
7369 "-usb enable the USB driver (will be the default soon)\n"
7370 "-usbdevice name add the host or guest USB device 'name'\n"
7371 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7372 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7373 #endif
7374 "-name string set the name of the guest\n"
7375 "\n"
7376 "Network options:\n"
7377 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7378 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7379 #ifdef CONFIG_SLIRP
7380 "-net user[,vlan=n][,hostname=host]\n"
7381 " connect the user mode network stack to VLAN 'n' and send\n"
7382 " hostname 'host' to DHCP clients\n"
7383 #endif
7384 #ifdef _WIN32
7385 "-net tap[,vlan=n],ifname=name\n"
7386 " connect the host TAP network interface to VLAN 'n'\n"
7387 #else
7388 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7389 " connect the host TAP network interface to VLAN 'n' and use the\n"
7390 " network scripts 'file' (default=%s)\n"
7391 " and 'dfile' (default=%s);\n"
7392 " use '[down]script=no' to disable script execution;\n"
7393 " use 'fd=h' to connect to an already opened TAP interface\n"
7394 #endif
7395 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7396 " connect the vlan 'n' to another VLAN using a socket connection\n"
7397 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7398 " connect the vlan 'n' to multicast maddr and port\n"
7399 "-net none use it alone to have zero network devices; if no -net option\n"
7400 " is provided, the default is '-net nic -net user'\n"
7401 "\n"
7402 #ifdef CONFIG_SLIRP
7403 "-tftp dir allow tftp access to files in dir [-net user]\n"
7404 "-bootp file advertise file in BOOTP replies\n"
7405 #ifndef _WIN32
7406 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7407 #endif
7408 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7409 " redirect TCP or UDP connections from host to guest [-net user]\n"
7410 #endif
7411 "\n"
7412 "Linux boot specific:\n"
7413 "-kernel bzImage use 'bzImage' as kernel image\n"
7414 "-append cmdline use 'cmdline' as kernel command line\n"
7415 "-initrd file use 'file' as initial ram disk\n"
7416 "\n"
7417 "Debug/Expert options:\n"
7418 "-monitor dev redirect the monitor to char device 'dev'\n"
7419 "-serial dev redirect the serial port to char device 'dev'\n"
7420 "-parallel dev redirect the parallel port to char device 'dev'\n"
7421 "-pidfile file Write PID to 'file'\n"
7422 "-S freeze CPU at startup (use 'c' to start execution)\n"
7423 "-s wait gdb connection to port\n"
7424 "-p port set gdb connection port [default=%s]\n"
7425 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7426 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7427 " translation (t=none or lba) (usually qemu can guess them)\n"
7428 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7429 #ifdef USE_KQEMU
7430 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7431 "-no-kqemu disable KQEMU kernel module usage\n"
7432 #endif
7433 #ifdef TARGET_I386
7434 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7435 " (default is CL-GD5446 PCI VGA)\n"
7436 "-no-acpi disable ACPI\n"
7437 #endif
7438 #ifdef CONFIG_CURSES
7439 "-curses use a curses/ncurses interface instead of SDL\n"
7440 #endif
7441 "-no-reboot exit instead of rebooting\n"
7442 "-no-shutdown stop before shutdown\n"
7443 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7444 "-vnc display start a VNC server on display\n"
7445 #ifndef _WIN32
7446 "-daemonize daemonize QEMU after initializing\n"
7447 #endif
7448 "-option-rom rom load a file, rom, into the option ROM space\n"
7449 #ifdef TARGET_SPARC
7450 "-prom-env variable=value set OpenBIOS nvram variables\n"
7451 #endif
7452 "-clock force the use of the given methods for timer alarm.\n"
7453 " To see what timers are available use -clock ?\n"
7454 "-startdate select initial date of the clock\n"
7455 "-icount [N|auto]\n"
7456 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7457 "\n"
7458 "During emulation, the following keys are useful:\n"
7459 "ctrl-alt-f toggle full screen\n"
7460 "ctrl-alt-n switch to virtual console 'n'\n"
7461 "ctrl-alt toggle mouse and keyboard grab\n"
7462 "\n"
7463 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7465 "qemu",
7466 DEFAULT_RAM_SIZE,
7467 #ifndef _WIN32
7468 DEFAULT_NETWORK_SCRIPT,
7469 DEFAULT_NETWORK_DOWN_SCRIPT,
7470 #endif
7471 DEFAULT_GDBSTUB_PORT,
7472 "/tmp/qemu.log");
7473 exit(exitcode);
7476 #define HAS_ARG 0x0001
7478 enum {
7479 QEMU_OPTION_h,
7481 QEMU_OPTION_M,
7482 QEMU_OPTION_cpu,
7483 QEMU_OPTION_fda,
7484 QEMU_OPTION_fdb,
7485 QEMU_OPTION_hda,
7486 QEMU_OPTION_hdb,
7487 QEMU_OPTION_hdc,
7488 QEMU_OPTION_hdd,
7489 QEMU_OPTION_drive,
7490 QEMU_OPTION_cdrom,
7491 QEMU_OPTION_mtdblock,
7492 QEMU_OPTION_sd,
7493 QEMU_OPTION_pflash,
7494 QEMU_OPTION_boot,
7495 QEMU_OPTION_snapshot,
7496 #ifdef TARGET_I386
7497 QEMU_OPTION_no_fd_bootchk,
7498 #endif
7499 QEMU_OPTION_m,
7500 QEMU_OPTION_nographic,
7501 QEMU_OPTION_portrait,
7502 #ifdef HAS_AUDIO
7503 QEMU_OPTION_audio_help,
7504 QEMU_OPTION_soundhw,
7505 #endif
7507 QEMU_OPTION_net,
7508 QEMU_OPTION_tftp,
7509 QEMU_OPTION_bootp,
7510 QEMU_OPTION_smb,
7511 QEMU_OPTION_redir,
7513 QEMU_OPTION_kernel,
7514 QEMU_OPTION_append,
7515 QEMU_OPTION_initrd,
7517 QEMU_OPTION_S,
7518 QEMU_OPTION_s,
7519 QEMU_OPTION_p,
7520 QEMU_OPTION_d,
7521 QEMU_OPTION_hdachs,
7522 QEMU_OPTION_L,
7523 QEMU_OPTION_bios,
7524 QEMU_OPTION_k,
7525 QEMU_OPTION_localtime,
7526 QEMU_OPTION_cirrusvga,
7527 QEMU_OPTION_vmsvga,
7528 QEMU_OPTION_g,
7529 QEMU_OPTION_std_vga,
7530 QEMU_OPTION_echr,
7531 QEMU_OPTION_monitor,
7532 QEMU_OPTION_serial,
7533 QEMU_OPTION_parallel,
7534 QEMU_OPTION_loadvm,
7535 QEMU_OPTION_full_screen,
7536 QEMU_OPTION_no_frame,
7537 QEMU_OPTION_alt_grab,
7538 QEMU_OPTION_no_quit,
7539 QEMU_OPTION_pidfile,
7540 QEMU_OPTION_no_kqemu,
7541 QEMU_OPTION_kernel_kqemu,
7542 QEMU_OPTION_win2k_hack,
7543 QEMU_OPTION_usb,
7544 QEMU_OPTION_usbdevice,
7545 QEMU_OPTION_smp,
7546 QEMU_OPTION_vnc,
7547 QEMU_OPTION_no_acpi,
7548 QEMU_OPTION_curses,
7549 QEMU_OPTION_no_reboot,
7550 QEMU_OPTION_no_shutdown,
7551 QEMU_OPTION_show_cursor,
7552 QEMU_OPTION_daemonize,
7553 QEMU_OPTION_option_rom,
7554 QEMU_OPTION_semihosting,
7555 QEMU_OPTION_name,
7556 QEMU_OPTION_prom_env,
7557 QEMU_OPTION_old_param,
7558 QEMU_OPTION_clock,
7559 QEMU_OPTION_startdate,
7560 QEMU_OPTION_tb_size,
7561 QEMU_OPTION_icount,
7564 typedef struct QEMUOption {
7565 const char *name;
7566 int flags;
7567 int index;
7568 } QEMUOption;
7570 const QEMUOption qemu_options[] = {
7571 { "h", 0, QEMU_OPTION_h },
7572 { "help", 0, QEMU_OPTION_h },
7574 { "M", HAS_ARG, QEMU_OPTION_M },
7575 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7576 { "fda", HAS_ARG, QEMU_OPTION_fda },
7577 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7578 { "hda", HAS_ARG, QEMU_OPTION_hda },
7579 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7580 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7581 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7582 { "drive", HAS_ARG, QEMU_OPTION_drive },
7583 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7584 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7585 { "sd", HAS_ARG, QEMU_OPTION_sd },
7586 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7587 { "boot", HAS_ARG, QEMU_OPTION_boot },
7588 { "snapshot", 0, QEMU_OPTION_snapshot },
7589 #ifdef TARGET_I386
7590 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7591 #endif
7592 { "m", HAS_ARG, QEMU_OPTION_m },
7593 { "nographic", 0, QEMU_OPTION_nographic },
7594 { "portrait", 0, QEMU_OPTION_portrait },
7595 { "k", HAS_ARG, QEMU_OPTION_k },
7596 #ifdef HAS_AUDIO
7597 { "audio-help", 0, QEMU_OPTION_audio_help },
7598 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7599 #endif
7601 { "net", HAS_ARG, QEMU_OPTION_net},
7602 #ifdef CONFIG_SLIRP
7603 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7604 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7605 #ifndef _WIN32
7606 { "smb", HAS_ARG, QEMU_OPTION_smb },
7607 #endif
7608 { "redir", HAS_ARG, QEMU_OPTION_redir },
7609 #endif
7611 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7612 { "append", HAS_ARG, QEMU_OPTION_append },
7613 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7615 { "S", 0, QEMU_OPTION_S },
7616 { "s", 0, QEMU_OPTION_s },
7617 { "p", HAS_ARG, QEMU_OPTION_p },
7618 { "d", HAS_ARG, QEMU_OPTION_d },
7619 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7620 { "L", HAS_ARG, QEMU_OPTION_L },
7621 { "bios", HAS_ARG, QEMU_OPTION_bios },
7622 #ifdef USE_KQEMU
7623 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7624 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7625 #endif
7626 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7627 { "g", 1, QEMU_OPTION_g },
7628 #endif
7629 { "localtime", 0, QEMU_OPTION_localtime },
7630 { "std-vga", 0, QEMU_OPTION_std_vga },
7631 { "echr", HAS_ARG, QEMU_OPTION_echr },
7632 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7633 { "serial", HAS_ARG, QEMU_OPTION_serial },
7634 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7635 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7636 { "full-screen", 0, QEMU_OPTION_full_screen },
7637 #ifdef CONFIG_SDL
7638 { "no-frame", 0, QEMU_OPTION_no_frame },
7639 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7640 { "no-quit", 0, QEMU_OPTION_no_quit },
7641 #endif
7642 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7643 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7644 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7645 { "smp", HAS_ARG, QEMU_OPTION_smp },
7646 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7647 #ifdef CONFIG_CURSES
7648 { "curses", 0, QEMU_OPTION_curses },
7649 #endif
7651 /* temporary options */
7652 { "usb", 0, QEMU_OPTION_usb },
7653 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7654 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7655 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7656 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7657 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7658 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7659 { "daemonize", 0, QEMU_OPTION_daemonize },
7660 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7661 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7662 { "semihosting", 0, QEMU_OPTION_semihosting },
7663 #endif
7664 { "name", HAS_ARG, QEMU_OPTION_name },
7665 #if defined(TARGET_SPARC)
7666 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7667 #endif
7668 #if defined(TARGET_ARM)
7669 { "old-param", 0, QEMU_OPTION_old_param },
7670 #endif
7671 { "clock", HAS_ARG, QEMU_OPTION_clock },
7672 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7673 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
7674 { "icount", HAS_ARG, QEMU_OPTION_icount },
7675 { NULL },
7678 /* password input */
7680 int qemu_key_check(BlockDriverState *bs, const char *name)
7682 char password[256];
7683 int i;
7685 if (!bdrv_is_encrypted(bs))
7686 return 0;
7688 term_printf("%s is encrypted.\n", name);
7689 for(i = 0; i < 3; i++) {
7690 monitor_readline("Password: ", 1, password, sizeof(password));
7691 if (bdrv_set_key(bs, password) == 0)
7692 return 0;
7693 term_printf("invalid password\n");
7695 return -EPERM;
7698 static BlockDriverState *get_bdrv(int index)
7700 if (index > nb_drives)
7701 return NULL;
7702 return drives_table[index].bdrv;
7705 static void read_passwords(void)
7707 BlockDriverState *bs;
7708 int i;
7710 for(i = 0; i < 6; i++) {
7711 bs = get_bdrv(i);
7712 if (bs)
7713 qemu_key_check(bs, bdrv_get_device_name(bs));
7717 #ifdef HAS_AUDIO
7718 struct soundhw soundhw[] = {
7719 #ifdef HAS_AUDIO_CHOICE
7720 #if defined(TARGET_I386) || defined(TARGET_MIPS)
7722 "pcspk",
7723 "PC speaker",
7726 { .init_isa = pcspk_audio_init }
7728 #endif
7730 "sb16",
7731 "Creative Sound Blaster 16",
7734 { .init_isa = SB16_init }
7737 #ifdef CONFIG_CS4231A
7739 "cs4231a",
7740 "CS4231A",
7743 { .init_isa = cs4231a_init }
7745 #endif
7747 #ifdef CONFIG_ADLIB
7749 "adlib",
7750 #ifdef HAS_YMF262
7751 "Yamaha YMF262 (OPL3)",
7752 #else
7753 "Yamaha YM3812 (OPL2)",
7754 #endif
7757 { .init_isa = Adlib_init }
7759 #endif
7761 #ifdef CONFIG_GUS
7763 "gus",
7764 "Gravis Ultrasound GF1",
7767 { .init_isa = GUS_init }
7769 #endif
7771 #ifdef CONFIG_AC97
7773 "ac97",
7774 "Intel 82801AA AC97 Audio",
7777 { .init_pci = ac97_init }
7779 #endif
7782 "es1370",
7783 "ENSONIQ AudioPCI ES1370",
7786 { .init_pci = es1370_init }
7788 #endif
7790 { NULL, NULL, 0, 0, { NULL } }
7793 static void select_soundhw (const char *optarg)
7795 struct soundhw *c;
7797 if (*optarg == '?') {
7798 show_valid_cards:
7800 printf ("Valid sound card names (comma separated):\n");
7801 for (c = soundhw; c->name; ++c) {
7802 printf ("%-11s %s\n", c->name, c->descr);
7804 printf ("\n-soundhw all will enable all of the above\n");
7805 exit (*optarg != '?');
7807 else {
7808 size_t l;
7809 const char *p;
7810 char *e;
7811 int bad_card = 0;
7813 if (!strcmp (optarg, "all")) {
7814 for (c = soundhw; c->name; ++c) {
7815 c->enabled = 1;
7817 return;
7820 p = optarg;
7821 while (*p) {
7822 e = strchr (p, ',');
7823 l = !e ? strlen (p) : (size_t) (e - p);
7825 for (c = soundhw; c->name; ++c) {
7826 if (!strncmp (c->name, p, l)) {
7827 c->enabled = 1;
7828 break;
7832 if (!c->name) {
7833 if (l > 80) {
7834 fprintf (stderr,
7835 "Unknown sound card name (too big to show)\n");
7837 else {
7838 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7839 (int) l, p);
7841 bad_card = 1;
7843 p += l + (e != NULL);
7846 if (bad_card)
7847 goto show_valid_cards;
7850 #endif
7852 #ifdef _WIN32
7853 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7855 exit(STATUS_CONTROL_C_EXIT);
7856 return TRUE;
7858 #endif
7860 #define MAX_NET_CLIENTS 32
7862 int main(int argc, char **argv)
7864 #ifdef CONFIG_GDBSTUB
7865 int use_gdbstub;
7866 const char *gdbstub_port;
7867 #endif
7868 uint32_t boot_devices_bitmap = 0;
7869 int i;
7870 int snapshot, linux_boot, net_boot;
7871 const char *initrd_filename;
7872 const char *kernel_filename, *kernel_cmdline;
7873 const char *boot_devices = "";
7874 DisplayState *ds = &display_state;
7875 int cyls, heads, secs, translation;
7876 const char *net_clients[MAX_NET_CLIENTS];
7877 int nb_net_clients;
7878 int hda_index;
7879 int optind;
7880 const char *r, *optarg;
7881 CharDriverState *monitor_hd;
7882 const char *monitor_device;
7883 const char *serial_devices[MAX_SERIAL_PORTS];
7884 int serial_device_index;
7885 const char *parallel_devices[MAX_PARALLEL_PORTS];
7886 int parallel_device_index;
7887 const char *loadvm = NULL;
7888 QEMUMachine *machine;
7889 const char *cpu_model;
7890 const char *usb_devices[MAX_USB_CMDLINE];
7891 int usb_devices_index;
7892 int fds[2];
7893 int tb_size;
7894 const char *pid_file = NULL;
7895 VLANState *vlan;
7897 LIST_INIT (&vm_change_state_head);
7898 #ifndef _WIN32
7900 struct sigaction act;
7901 sigfillset(&act.sa_mask);
7902 act.sa_flags = 0;
7903 act.sa_handler = SIG_IGN;
7904 sigaction(SIGPIPE, &act, NULL);
7906 #else
7907 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7908 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7909 QEMU to run on a single CPU */
7911 HANDLE h;
7912 DWORD mask, smask;
7913 int i;
7914 h = GetCurrentProcess();
7915 if (GetProcessAffinityMask(h, &mask, &smask)) {
7916 for(i = 0; i < 32; i++) {
7917 if (mask & (1 << i))
7918 break;
7920 if (i != 32) {
7921 mask = 1 << i;
7922 SetProcessAffinityMask(h, mask);
7926 #endif
7928 register_machines();
7929 machine = first_machine;
7930 cpu_model = NULL;
7931 initrd_filename = NULL;
7932 ram_size = 0;
7933 vga_ram_size = VGA_RAM_SIZE;
7934 #ifdef CONFIG_GDBSTUB
7935 use_gdbstub = 0;
7936 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7937 #endif
7938 snapshot = 0;
7939 nographic = 0;
7940 curses = 0;
7941 kernel_filename = NULL;
7942 kernel_cmdline = "";
7943 cyls = heads = secs = 0;
7944 translation = BIOS_ATA_TRANSLATION_AUTO;
7945 monitor_device = "vc";
7947 serial_devices[0] = "vc:80Cx24C";
7948 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7949 serial_devices[i] = NULL;
7950 serial_device_index = 0;
7952 parallel_devices[0] = "vc:640x480";
7953 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7954 parallel_devices[i] = NULL;
7955 parallel_device_index = 0;
7957 usb_devices_index = 0;
7959 nb_net_clients = 0;
7960 nb_drives = 0;
7961 nb_drives_opt = 0;
7962 hda_index = -1;
7964 nb_nics = 0;
7966 tb_size = 0;
7968 optind = 1;
7969 for(;;) {
7970 if (optind >= argc)
7971 break;
7972 r = argv[optind];
7973 if (r[0] != '-') {
7974 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
7975 } else {
7976 const QEMUOption *popt;
7978 optind++;
7979 /* Treat --foo the same as -foo. */
7980 if (r[1] == '-')
7981 r++;
7982 popt = qemu_options;
7983 for(;;) {
7984 if (!popt->name) {
7985 fprintf(stderr, "%s: invalid option -- '%s'\n",
7986 argv[0], r);
7987 exit(1);
7989 if (!strcmp(popt->name, r + 1))
7990 break;
7991 popt++;
7993 if (popt->flags & HAS_ARG) {
7994 if (optind >= argc) {
7995 fprintf(stderr, "%s: option '%s' requires an argument\n",
7996 argv[0], r);
7997 exit(1);
7999 optarg = argv[optind++];
8000 } else {
8001 optarg = NULL;
8004 switch(popt->index) {
8005 case QEMU_OPTION_M:
8006 machine = find_machine(optarg);
8007 if (!machine) {
8008 QEMUMachine *m;
8009 printf("Supported machines are:\n");
8010 for(m = first_machine; m != NULL; m = m->next) {
8011 printf("%-10s %s%s\n",
8012 m->name, m->desc,
8013 m == first_machine ? " (default)" : "");
8015 exit(*optarg != '?');
8017 break;
8018 case QEMU_OPTION_cpu:
8019 /* hw initialization will check this */
8020 if (*optarg == '?') {
8021 /* XXX: implement xxx_cpu_list for targets that still miss it */
8022 #if defined(cpu_list)
8023 cpu_list(stdout, &fprintf);
8024 #endif
8025 exit(0);
8026 } else {
8027 cpu_model = optarg;
8029 break;
8030 case QEMU_OPTION_initrd:
8031 initrd_filename = optarg;
8032 break;
8033 case QEMU_OPTION_hda:
8034 if (cyls == 0)
8035 hda_index = drive_add(optarg, HD_ALIAS, 0);
8036 else
8037 hda_index = drive_add(optarg, HD_ALIAS
8038 ",cyls=%d,heads=%d,secs=%d%s",
8039 0, cyls, heads, secs,
8040 translation == BIOS_ATA_TRANSLATION_LBA ?
8041 ",trans=lba" :
8042 translation == BIOS_ATA_TRANSLATION_NONE ?
8043 ",trans=none" : "");
8044 break;
8045 case QEMU_OPTION_hdb:
8046 case QEMU_OPTION_hdc:
8047 case QEMU_OPTION_hdd:
8048 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8049 break;
8050 case QEMU_OPTION_drive:
8051 drive_add(NULL, "%s", optarg);
8052 break;
8053 case QEMU_OPTION_mtdblock:
8054 drive_add(optarg, MTD_ALIAS);
8055 break;
8056 case QEMU_OPTION_sd:
8057 drive_add(optarg, SD_ALIAS);
8058 break;
8059 case QEMU_OPTION_pflash:
8060 drive_add(optarg, PFLASH_ALIAS);
8061 break;
8062 case QEMU_OPTION_snapshot:
8063 snapshot = 1;
8064 break;
8065 case QEMU_OPTION_hdachs:
8067 const char *p;
8068 p = optarg;
8069 cyls = strtol(p, (char **)&p, 0);
8070 if (cyls < 1 || cyls > 16383)
8071 goto chs_fail;
8072 if (*p != ',')
8073 goto chs_fail;
8074 p++;
8075 heads = strtol(p, (char **)&p, 0);
8076 if (heads < 1 || heads > 16)
8077 goto chs_fail;
8078 if (*p != ',')
8079 goto chs_fail;
8080 p++;
8081 secs = strtol(p, (char **)&p, 0);
8082 if (secs < 1 || secs > 63)
8083 goto chs_fail;
8084 if (*p == ',') {
8085 p++;
8086 if (!strcmp(p, "none"))
8087 translation = BIOS_ATA_TRANSLATION_NONE;
8088 else if (!strcmp(p, "lba"))
8089 translation = BIOS_ATA_TRANSLATION_LBA;
8090 else if (!strcmp(p, "auto"))
8091 translation = BIOS_ATA_TRANSLATION_AUTO;
8092 else
8093 goto chs_fail;
8094 } else if (*p != '\0') {
8095 chs_fail:
8096 fprintf(stderr, "qemu: invalid physical CHS format\n");
8097 exit(1);
8099 if (hda_index != -1)
8100 snprintf(drives_opt[hda_index].opt,
8101 sizeof(drives_opt[hda_index].opt),
8102 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8103 0, cyls, heads, secs,
8104 translation == BIOS_ATA_TRANSLATION_LBA ?
8105 ",trans=lba" :
8106 translation == BIOS_ATA_TRANSLATION_NONE ?
8107 ",trans=none" : "");
8109 break;
8110 case QEMU_OPTION_nographic:
8111 serial_devices[0] = "stdio";
8112 parallel_devices[0] = "null";
8113 monitor_device = "stdio";
8114 nographic = 1;
8115 break;
8116 #ifdef CONFIG_CURSES
8117 case QEMU_OPTION_curses:
8118 curses = 1;
8119 break;
8120 #endif
8121 case QEMU_OPTION_portrait:
8122 graphic_rotate = 1;
8123 break;
8124 case QEMU_OPTION_kernel:
8125 kernel_filename = optarg;
8126 break;
8127 case QEMU_OPTION_append:
8128 kernel_cmdline = optarg;
8129 break;
8130 case QEMU_OPTION_cdrom:
8131 drive_add(optarg, CDROM_ALIAS);
8132 break;
8133 case QEMU_OPTION_boot:
8134 boot_devices = optarg;
8135 /* We just do some generic consistency checks */
8137 /* Could easily be extended to 64 devices if needed */
8138 const char *p;
8140 boot_devices_bitmap = 0;
8141 for (p = boot_devices; *p != '\0'; p++) {
8142 /* Allowed boot devices are:
8143 * a b : floppy disk drives
8144 * c ... f : IDE disk drives
8145 * g ... m : machine implementation dependant drives
8146 * n ... p : network devices
8147 * It's up to each machine implementation to check
8148 * if the given boot devices match the actual hardware
8149 * implementation and firmware features.
8151 if (*p < 'a' || *p > 'q') {
8152 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8153 exit(1);
8155 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8156 fprintf(stderr,
8157 "Boot device '%c' was given twice\n",*p);
8158 exit(1);
8160 boot_devices_bitmap |= 1 << (*p - 'a');
8163 break;
8164 case QEMU_OPTION_fda:
8165 case QEMU_OPTION_fdb:
8166 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8167 break;
8168 #ifdef TARGET_I386
8169 case QEMU_OPTION_no_fd_bootchk:
8170 fd_bootchk = 0;
8171 break;
8172 #endif
8173 case QEMU_OPTION_net:
8174 if (nb_net_clients >= MAX_NET_CLIENTS) {
8175 fprintf(stderr, "qemu: too many network clients\n");
8176 exit(1);
8178 net_clients[nb_net_clients] = optarg;
8179 nb_net_clients++;
8180 break;
8181 #ifdef CONFIG_SLIRP
8182 case QEMU_OPTION_tftp:
8183 tftp_prefix = optarg;
8184 break;
8185 case QEMU_OPTION_bootp:
8186 bootp_filename = optarg;
8187 break;
8188 #ifndef _WIN32
8189 case QEMU_OPTION_smb:
8190 net_slirp_smb(optarg);
8191 break;
8192 #endif
8193 case QEMU_OPTION_redir:
8194 net_slirp_redir(optarg);
8195 break;
8196 #endif
8197 #ifdef HAS_AUDIO
8198 case QEMU_OPTION_audio_help:
8199 AUD_help ();
8200 exit (0);
8201 break;
8202 case QEMU_OPTION_soundhw:
8203 select_soundhw (optarg);
8204 break;
8205 #endif
8206 case QEMU_OPTION_h:
8207 help(0);
8208 break;
8209 case QEMU_OPTION_m: {
8210 uint64_t value;
8211 char *ptr;
8213 value = strtoul(optarg, &ptr, 10);
8214 switch (*ptr) {
8215 case 0: case 'M': case 'm':
8216 value <<= 20;
8217 break;
8218 case 'G': case 'g':
8219 value <<= 30;
8220 break;
8221 default:
8222 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8223 exit(1);
8226 /* On 32-bit hosts, QEMU is limited by virtual address space */
8227 if (value > (2047 << 20)
8228 #ifndef USE_KQEMU
8229 && HOST_LONG_BITS == 32
8230 #endif
8232 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8233 exit(1);
8235 if (value != (uint64_t)(ram_addr_t)value) {
8236 fprintf(stderr, "qemu: ram size too large\n");
8237 exit(1);
8239 ram_size = value;
8240 break;
8242 case QEMU_OPTION_d:
8244 int mask;
8245 CPULogItem *item;
8247 mask = cpu_str_to_log_mask(optarg);
8248 if (!mask) {
8249 printf("Log items (comma separated):\n");
8250 for(item = cpu_log_items; item->mask != 0; item++) {
8251 printf("%-10s %s\n", item->name, item->help);
8253 exit(1);
8255 cpu_set_log(mask);
8257 break;
8258 #ifdef CONFIG_GDBSTUB
8259 case QEMU_OPTION_s:
8260 use_gdbstub = 1;
8261 break;
8262 case QEMU_OPTION_p:
8263 gdbstub_port = optarg;
8264 break;
8265 #endif
8266 case QEMU_OPTION_L:
8267 bios_dir = optarg;
8268 break;
8269 case QEMU_OPTION_bios:
8270 bios_name = optarg;
8271 break;
8272 case QEMU_OPTION_S:
8273 autostart = 0;
8274 break;
8275 case QEMU_OPTION_k:
8276 keyboard_layout = optarg;
8277 break;
8278 case QEMU_OPTION_localtime:
8279 rtc_utc = 0;
8280 break;
8281 case QEMU_OPTION_cirrusvga:
8282 cirrus_vga_enabled = 1;
8283 vmsvga_enabled = 0;
8284 break;
8285 case QEMU_OPTION_vmsvga:
8286 cirrus_vga_enabled = 0;
8287 vmsvga_enabled = 1;
8288 break;
8289 case QEMU_OPTION_std_vga:
8290 cirrus_vga_enabled = 0;
8291 vmsvga_enabled = 0;
8292 break;
8293 case QEMU_OPTION_g:
8295 const char *p;
8296 int w, h, depth;
8297 p = optarg;
8298 w = strtol(p, (char **)&p, 10);
8299 if (w <= 0) {
8300 graphic_error:
8301 fprintf(stderr, "qemu: invalid resolution or depth\n");
8302 exit(1);
8304 if (*p != 'x')
8305 goto graphic_error;
8306 p++;
8307 h = strtol(p, (char **)&p, 10);
8308 if (h <= 0)
8309 goto graphic_error;
8310 if (*p == 'x') {
8311 p++;
8312 depth = strtol(p, (char **)&p, 10);
8313 if (depth != 8 && depth != 15 && depth != 16 &&
8314 depth != 24 && depth != 32)
8315 goto graphic_error;
8316 } else if (*p == '\0') {
8317 depth = graphic_depth;
8318 } else {
8319 goto graphic_error;
8322 graphic_width = w;
8323 graphic_height = h;
8324 graphic_depth = depth;
8326 break;
8327 case QEMU_OPTION_echr:
8329 char *r;
8330 term_escape_char = strtol(optarg, &r, 0);
8331 if (r == optarg)
8332 printf("Bad argument to echr\n");
8333 break;
8335 case QEMU_OPTION_monitor:
8336 monitor_device = optarg;
8337 break;
8338 case QEMU_OPTION_serial:
8339 if (serial_device_index >= MAX_SERIAL_PORTS) {
8340 fprintf(stderr, "qemu: too many serial ports\n");
8341 exit(1);
8343 serial_devices[serial_device_index] = optarg;
8344 serial_device_index++;
8345 break;
8346 case QEMU_OPTION_parallel:
8347 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8348 fprintf(stderr, "qemu: too many parallel ports\n");
8349 exit(1);
8351 parallel_devices[parallel_device_index] = optarg;
8352 parallel_device_index++;
8353 break;
8354 case QEMU_OPTION_loadvm:
8355 loadvm = optarg;
8356 break;
8357 case QEMU_OPTION_full_screen:
8358 full_screen = 1;
8359 break;
8360 #ifdef CONFIG_SDL
8361 case QEMU_OPTION_no_frame:
8362 no_frame = 1;
8363 break;
8364 case QEMU_OPTION_alt_grab:
8365 alt_grab = 1;
8366 break;
8367 case QEMU_OPTION_no_quit:
8368 no_quit = 1;
8369 break;
8370 #endif
8371 case QEMU_OPTION_pidfile:
8372 pid_file = optarg;
8373 break;
8374 #ifdef TARGET_I386
8375 case QEMU_OPTION_win2k_hack:
8376 win2k_install_hack = 1;
8377 break;
8378 #endif
8379 #ifdef USE_KQEMU
8380 case QEMU_OPTION_no_kqemu:
8381 kqemu_allowed = 0;
8382 break;
8383 case QEMU_OPTION_kernel_kqemu:
8384 kqemu_allowed = 2;
8385 break;
8386 #endif
8387 case QEMU_OPTION_usb:
8388 usb_enabled = 1;
8389 break;
8390 case QEMU_OPTION_usbdevice:
8391 usb_enabled = 1;
8392 if (usb_devices_index >= MAX_USB_CMDLINE) {
8393 fprintf(stderr, "Too many USB devices\n");
8394 exit(1);
8396 usb_devices[usb_devices_index] = optarg;
8397 usb_devices_index++;
8398 break;
8399 case QEMU_OPTION_smp:
8400 smp_cpus = atoi(optarg);
8401 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8402 fprintf(stderr, "Invalid number of CPUs\n");
8403 exit(1);
8405 break;
8406 case QEMU_OPTION_vnc:
8407 vnc_display = optarg;
8408 break;
8409 case QEMU_OPTION_no_acpi:
8410 acpi_enabled = 0;
8411 break;
8412 case QEMU_OPTION_no_reboot:
8413 no_reboot = 1;
8414 break;
8415 case QEMU_OPTION_no_shutdown:
8416 no_shutdown = 1;
8417 break;
8418 case QEMU_OPTION_show_cursor:
8419 cursor_hide = 0;
8420 break;
8421 case QEMU_OPTION_daemonize:
8422 daemonize = 1;
8423 break;
8424 case QEMU_OPTION_option_rom:
8425 if (nb_option_roms >= MAX_OPTION_ROMS) {
8426 fprintf(stderr, "Too many option ROMs\n");
8427 exit(1);
8429 option_rom[nb_option_roms] = optarg;
8430 nb_option_roms++;
8431 break;
8432 case QEMU_OPTION_semihosting:
8433 semihosting_enabled = 1;
8434 break;
8435 case QEMU_OPTION_name:
8436 qemu_name = optarg;
8437 break;
8438 #ifdef TARGET_SPARC
8439 case QEMU_OPTION_prom_env:
8440 if (nb_prom_envs >= MAX_PROM_ENVS) {
8441 fprintf(stderr, "Too many prom variables\n");
8442 exit(1);
8444 prom_envs[nb_prom_envs] = optarg;
8445 nb_prom_envs++;
8446 break;
8447 #endif
8448 #ifdef TARGET_ARM
8449 case QEMU_OPTION_old_param:
8450 old_param = 1;
8451 break;
8452 #endif
8453 case QEMU_OPTION_clock:
8454 configure_alarms(optarg);
8455 break;
8456 case QEMU_OPTION_startdate:
8458 struct tm tm;
8459 time_t rtc_start_date;
8460 if (!strcmp(optarg, "now")) {
8461 rtc_date_offset = -1;
8462 } else {
8463 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8464 &tm.tm_year,
8465 &tm.tm_mon,
8466 &tm.tm_mday,
8467 &tm.tm_hour,
8468 &tm.tm_min,
8469 &tm.tm_sec) == 6) {
8470 /* OK */
8471 } else if (sscanf(optarg, "%d-%d-%d",
8472 &tm.tm_year,
8473 &tm.tm_mon,
8474 &tm.tm_mday) == 3) {
8475 tm.tm_hour = 0;
8476 tm.tm_min = 0;
8477 tm.tm_sec = 0;
8478 } else {
8479 goto date_fail;
8481 tm.tm_year -= 1900;
8482 tm.tm_mon--;
8483 rtc_start_date = mktimegm(&tm);
8484 if (rtc_start_date == -1) {
8485 date_fail:
8486 fprintf(stderr, "Invalid date format. Valid format are:\n"
8487 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8488 exit(1);
8490 rtc_date_offset = time(NULL) - rtc_start_date;
8493 break;
8494 case QEMU_OPTION_tb_size:
8495 tb_size = strtol(optarg, NULL, 0);
8496 if (tb_size < 0)
8497 tb_size = 0;
8498 break;
8499 case QEMU_OPTION_icount:
8500 use_icount = 1;
8501 if (strcmp(optarg, "auto") == 0) {
8502 icount_time_shift = -1;
8503 } else {
8504 icount_time_shift = strtol(optarg, NULL, 0);
8506 break;
8511 #ifndef _WIN32
8512 if (daemonize && !nographic && vnc_display == NULL) {
8513 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8514 daemonize = 0;
8517 if (daemonize) {
8518 pid_t pid;
8520 if (pipe(fds) == -1)
8521 exit(1);
8523 pid = fork();
8524 if (pid > 0) {
8525 uint8_t status;
8526 ssize_t len;
8528 close(fds[1]);
8530 again:
8531 len = read(fds[0], &status, 1);
8532 if (len == -1 && (errno == EINTR))
8533 goto again;
8535 if (len != 1)
8536 exit(1);
8537 else if (status == 1) {
8538 fprintf(stderr, "Could not acquire pidfile\n");
8539 exit(1);
8540 } else
8541 exit(0);
8542 } else if (pid < 0)
8543 exit(1);
8545 setsid();
8547 pid = fork();
8548 if (pid > 0)
8549 exit(0);
8550 else if (pid < 0)
8551 exit(1);
8553 umask(027);
8554 chdir("/");
8556 signal(SIGTSTP, SIG_IGN);
8557 signal(SIGTTOU, SIG_IGN);
8558 signal(SIGTTIN, SIG_IGN);
8560 #endif
8562 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8563 if (daemonize) {
8564 uint8_t status = 1;
8565 write(fds[1], &status, 1);
8566 } else
8567 fprintf(stderr, "Could not acquire pid file\n");
8568 exit(1);
8571 #ifdef USE_KQEMU
8572 if (smp_cpus > 1)
8573 kqemu_allowed = 0;
8574 #endif
8575 linux_boot = (kernel_filename != NULL);
8576 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8578 /* XXX: this should not be: some embedded targets just have flash */
8579 if (!linux_boot && net_boot == 0 &&
8580 nb_drives_opt == 0)
8581 help(1);
8583 if (!linux_boot && *kernel_cmdline != '\0') {
8584 fprintf(stderr, "-append only allowed with -kernel option\n");
8585 exit(1);
8588 if (!linux_boot && initrd_filename != NULL) {
8589 fprintf(stderr, "-initrd only allowed with -kernel option\n");
8590 exit(1);
8593 /* boot to floppy or the default cd if no hard disk defined yet */
8594 if (!boot_devices[0]) {
8595 boot_devices = "cad";
8597 setvbuf(stdout, NULL, _IOLBF, 0);
8599 init_timers();
8600 init_timer_alarm();
8601 qemu_aio_init();
8602 if (use_icount && icount_time_shift < 0) {
8603 use_icount = 2;
8604 /* 125MIPS seems a reasonable initial guess at the guest speed.
8605 It will be corrected fairly quickly anyway. */
8606 icount_time_shift = 3;
8607 init_icount_adjust();
8610 #ifdef _WIN32
8611 socket_init();
8612 #endif
8614 /* init network clients */
8615 if (nb_net_clients == 0) {
8616 /* if no clients, we use a default config */
8617 net_clients[0] = "nic";
8618 net_clients[1] = "user";
8619 nb_net_clients = 2;
8622 for(i = 0;i < nb_net_clients; i++) {
8623 if (net_client_init(net_clients[i]) < 0)
8624 exit(1);
8626 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8627 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8628 continue;
8629 if (vlan->nb_guest_devs == 0) {
8630 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8631 exit(1);
8633 if (vlan->nb_host_devs == 0)
8634 fprintf(stderr,
8635 "Warning: vlan %d is not connected to host network\n",
8636 vlan->id);
8639 #ifdef TARGET_I386
8640 /* XXX: this should be moved in the PC machine instantiation code */
8641 if (net_boot != 0) {
8642 int netroms = 0;
8643 for (i = 0; i < nb_nics && i < 4; i++) {
8644 const char *model = nd_table[i].model;
8645 char buf[1024];
8646 if (net_boot & (1 << i)) {
8647 if (model == NULL)
8648 model = "ne2k_pci";
8649 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8650 if (get_image_size(buf) > 0) {
8651 if (nb_option_roms >= MAX_OPTION_ROMS) {
8652 fprintf(stderr, "Too many option ROMs\n");
8653 exit(1);
8655 option_rom[nb_option_roms] = strdup(buf);
8656 nb_option_roms++;
8657 netroms++;
8661 if (netroms == 0) {
8662 fprintf(stderr, "No valid PXE rom found for network device\n");
8663 exit(1);
8666 #endif
8668 /* init the memory */
8669 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8671 if (machine->ram_require & RAMSIZE_FIXED) {
8672 if (ram_size > 0) {
8673 if (ram_size < phys_ram_size) {
8674 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8675 machine->name, (unsigned long long) phys_ram_size);
8676 exit(-1);
8679 phys_ram_size = ram_size;
8680 } else
8681 ram_size = phys_ram_size;
8682 } else {
8683 if (ram_size == 0)
8684 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8686 phys_ram_size += ram_size;
8689 phys_ram_base = qemu_vmalloc(phys_ram_size);
8690 if (!phys_ram_base) {
8691 fprintf(stderr, "Could not allocate physical memory\n");
8692 exit(1);
8695 /* init the dynamic translator */
8696 cpu_exec_init_all(tb_size * 1024 * 1024);
8698 bdrv_init();
8700 /* we always create the cdrom drive, even if no disk is there */
8702 if (nb_drives_opt < MAX_DRIVES)
8703 drive_add(NULL, CDROM_ALIAS);
8705 /* we always create at least one floppy */
8707 if (nb_drives_opt < MAX_DRIVES)
8708 drive_add(NULL, FD_ALIAS, 0);
8710 /* we always create one sd slot, even if no card is in it */
8712 if (nb_drives_opt < MAX_DRIVES)
8713 drive_add(NULL, SD_ALIAS);
8715 /* open the virtual block devices */
8717 for(i = 0; i < nb_drives_opt; i++)
8718 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8719 exit(1);
8721 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8722 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8724 init_ioports();
8726 /* terminal init */
8727 memset(&display_state, 0, sizeof(display_state));
8728 if (nographic) {
8729 if (curses) {
8730 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8731 exit(1);
8733 /* nearly nothing to do */
8734 dumb_display_init(ds);
8735 } else if (vnc_display != NULL) {
8736 vnc_display_init(ds);
8737 if (vnc_display_open(ds, vnc_display) < 0)
8738 exit(1);
8739 } else
8740 #if defined(CONFIG_CURSES)
8741 if (curses) {
8742 curses_display_init(ds, full_screen);
8743 } else
8744 #endif
8746 #if defined(CONFIG_SDL)
8747 sdl_display_init(ds, full_screen, no_frame);
8748 #elif defined(CONFIG_COCOA)
8749 cocoa_display_init(ds, full_screen);
8750 #else
8751 dumb_display_init(ds);
8752 #endif
8755 /* Maintain compatibility with multiple stdio monitors */
8756 if (!strcmp(monitor_device,"stdio")) {
8757 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8758 const char *devname = serial_devices[i];
8759 if (devname && !strcmp(devname,"mon:stdio")) {
8760 monitor_device = NULL;
8761 break;
8762 } else if (devname && !strcmp(devname,"stdio")) {
8763 monitor_device = NULL;
8764 serial_devices[i] = "mon:stdio";
8765 break;
8769 if (monitor_device) {
8770 monitor_hd = qemu_chr_open(monitor_device);
8771 if (!monitor_hd) {
8772 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8773 exit(1);
8775 monitor_init(monitor_hd, !nographic);
8778 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8779 const char *devname = serial_devices[i];
8780 if (devname && strcmp(devname, "none")) {
8781 serial_hds[i] = qemu_chr_open(devname);
8782 if (!serial_hds[i]) {
8783 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8784 devname);
8785 exit(1);
8787 if (strstart(devname, "vc", 0))
8788 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8792 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8793 const char *devname = parallel_devices[i];
8794 if (devname && strcmp(devname, "none")) {
8795 parallel_hds[i] = qemu_chr_open(devname);
8796 if (!parallel_hds[i]) {
8797 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8798 devname);
8799 exit(1);
8801 if (strstart(devname, "vc", 0))
8802 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8806 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8807 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8809 /* init USB devices */
8810 if (usb_enabled) {
8811 for(i = 0; i < usb_devices_index; i++) {
8812 if (usb_device_add(usb_devices[i]) < 0) {
8813 fprintf(stderr, "Warning: could not add USB device %s\n",
8814 usb_devices[i]);
8819 if (display_state.dpy_refresh) {
8820 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8821 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8824 #ifdef CONFIG_GDBSTUB
8825 if (use_gdbstub) {
8826 /* XXX: use standard host:port notation and modify options
8827 accordingly. */
8828 if (gdbserver_start(gdbstub_port) < 0) {
8829 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8830 gdbstub_port);
8831 exit(1);
8834 #endif
8836 if (loadvm)
8837 do_loadvm(loadvm);
8840 /* XXX: simplify init */
8841 read_passwords();
8842 if (autostart) {
8843 vm_start();
8847 if (daemonize) {
8848 uint8_t status = 0;
8849 ssize_t len;
8850 int fd;
8852 again1:
8853 len = write(fds[1], &status, 1);
8854 if (len == -1 && (errno == EINTR))
8855 goto again1;
8857 if (len != 1)
8858 exit(1);
8860 TFR(fd = open("/dev/null", O_RDWR));
8861 if (fd == -1)
8862 exit(1);
8864 dup2(fd, 0);
8865 dup2(fd, 1);
8866 dup2(fd, 2);
8868 close(fd);
8871 main_loop();
8872 quit_timers();
8874 #if !defined(_WIN32)
8875 /* close network clients */
8876 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8877 VLANClientState *vc;
8879 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8880 if (vc->fd_read == tap_receive) {
8881 char ifname[64];
8882 TAPState *s = vc->opaque;
8884 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8885 s->down_script[0])
8886 launch_script(s->down_script, ifname, s->fd);
8890 #endif
8891 return 0;