kvm: external module: preempt emulation miscompile fix
[qemu-kvm/fedora.git] / vl.c
blob5e14c1a55f1d3815f349d5d07c3b7b1d35c8f417
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/fdc.h"
30 #include "hw/audiodev.h"
31 #include "hw/isa.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"
40 #include "migration.h"
41 #include "qemu-kvm.h"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/poll.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifndef __APPLE__
67 #include <libutil.h>
68 #endif
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
71 #else
72 #ifndef __sun__
73 #include <linux/if.h>
74 #include <linux/if_tun.h>
75 #include <pty.h>
76 #include <malloc.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
82 #include "hpet.h"
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
86 #else
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #else
103 #include <winsock2.h>
104 int inet_aton(const char *cp, struct in_addr *ia);
105 #endif
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #ifdef _WIN32
112 #include <malloc.h>
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
117 #endif
119 #include "qemu_socket.h"
121 #ifdef CONFIG_SDL
122 #ifdef __APPLE__
123 #include <SDL/SDL.h>
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "disas.h"
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140 #ifdef __sun__
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142 #else
143 #define SMBD_COMMAND "/usr/sbin/smbd"
144 #endif
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
149 #if HOST_LONG_BITS < 64
150 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
151 #else
152 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
153 #endif
155 #ifdef TARGET_PPC
156 #define DEFAULT_RAM_SIZE 144
157 #else
158 #define DEFAULT_RAM_SIZE 128
159 #endif
160 /* in ms */
161 #define GUI_REFRESH_INTERVAL 30
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 void *ioport_opaque[MAX_IOPORTS];
172 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 int extboot_drive = -1;
179 /* point to the block driver where the snapshots are managed */
180 BlockDriverState *bs_snapshots;
181 int vga_ram_size;
182 static DisplayState display_state;
183 int nographic;
184 const char* keyboard_layout = NULL;
185 int64_t ticks_per_sec;
186 int64_t ram_size;
187 int pit_min_timer_count = 0;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int rtc_utc = 1;
192 int rtc_start_date = -1; /* -1 means now */
193 int cirrus_vga_enabled = 1;
194 int vmsvga_enabled = 0;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 int full_screen = 0;
205 int no_frame = 0;
206 int no_quit = 0;
207 int balloon_used = 0;
208 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 #endif
214 int usb_enabled = 0;
215 static VLANState *first_vlan;
216 int smp_cpus = 1;
217 const char *vnc_display;
218 #if defined(TARGET_SPARC)
219 #define MAX_CPUS 16
220 #elif defined(TARGET_I386)
221 #define MAX_CPUS 255
222 #elif defined(TARGET_IA64)
223 #define MAX_CPUS 4
224 #else
225 #define MAX_CPUS 1
226 #endif
227 int acpi_enabled = 1;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *incoming;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 int autostart = 1;
238 int time_drift_fix = 0;
239 unsigned int kvm_shadow_memory = 0;
240 const char *cpu_vendor_string;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 #ifdef TARGET_SPARC
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int nb_drives_opt;
251 struct drive_opt {
252 const char *file;
253 char opt[1024];
254 } drives_opt[MAX_DRIVES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int event_pending = 1;
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 void decorate_application_name(char *appname, int max_len)
264 if (kvm_enabled())
266 int remain = max_len - strlen(appname) - 1;
268 if (remain > 0)
269 strncat(appname, "/KVM", remain);
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
277 PicState2 *isa_pic;
279 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
281 #ifdef DEBUG_UNUSED_IOPORT
282 fprintf(stderr, "unused inb: port=0x%04x\n", address);
283 #endif
284 return 0xff;
287 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
289 #ifdef DEBUG_UNUSED_IOPORT
290 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
291 #endif
294 /* default is to make two byte accesses */
295 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
297 uint32_t data;
298 data = ioport_read_table[0][address](ioport_opaque[address], address);
299 address = (address + 1) & (MAX_IOPORTS - 1);
300 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
301 return data;
304 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
306 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
307 address = (address + 1) & (MAX_IOPORTS - 1);
308 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
311 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
313 #ifdef DEBUG_UNUSED_IOPORT
314 fprintf(stderr, "unused inl: port=0x%04x\n", address);
315 #endif
316 return 0xffffffff;
319 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
323 #endif
326 static void init_ioports(void)
328 int i;
330 for(i = 0; i < MAX_IOPORTS; i++) {
331 ioport_read_table[0][i] = default_ioport_readb;
332 ioport_write_table[0][i] = default_ioport_writeb;
333 ioport_read_table[1][i] = default_ioport_readw;
334 ioport_write_table[1][i] = default_ioport_writew;
335 ioport_read_table[2][i] = default_ioport_readl;
336 ioport_write_table[2][i] = default_ioport_writel;
340 /* size is the word size in byte */
341 int register_ioport_read(int start, int length, int size,
342 IOPortReadFunc *func, void *opaque)
344 int i, bsize;
346 if (size == 1) {
347 bsize = 0;
348 } else if (size == 2) {
349 bsize = 1;
350 } else if (size == 4) {
351 bsize = 2;
352 } else {
353 hw_error("register_ioport_read: invalid size");
354 return -1;
356 for(i = start; i < start + length; i += size) {
357 ioport_read_table[bsize][i] = func;
358 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
359 hw_error("register_ioport_read: invalid opaque");
360 ioport_opaque[i] = opaque;
362 return 0;
365 /* size is the word size in byte */
366 int register_ioport_write(int start, int length, int size,
367 IOPortWriteFunc *func, void *opaque)
369 int i, bsize;
371 if (size == 1) {
372 bsize = 0;
373 } else if (size == 2) {
374 bsize = 1;
375 } else if (size == 4) {
376 bsize = 2;
377 } else {
378 hw_error("register_ioport_write: invalid size");
379 return -1;
381 for(i = start; i < start + length; i += size) {
382 ioport_write_table[bsize][i] = func;
383 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
384 hw_error("register_ioport_write: invalid opaque");
385 ioport_opaque[i] = opaque;
387 return 0;
390 void isa_unassign_ioport(int start, int length)
392 int i;
394 for(i = start; i < start + length; i++) {
395 ioport_read_table[0][i] = default_ioport_readb;
396 ioport_read_table[1][i] = default_ioport_readw;
397 ioport_read_table[2][i] = default_ioport_readl;
399 ioport_write_table[0][i] = default_ioport_writeb;
400 ioport_write_table[1][i] = default_ioport_writew;
401 ioport_write_table[2][i] = default_ioport_writel;
405 /***********************************************************/
407 void cpu_outb(CPUState *env, int addr, int val)
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "outb: %04x %02x\n", addr, val);
412 #endif
413 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
420 void cpu_outw(CPUState *env, int addr, int val)
422 #ifdef DEBUG_IOPORT
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "outw: %04x %04x\n", addr, val);
425 #endif
426 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
433 void cpu_outl(CPUState *env, int addr, int val)
435 #ifdef DEBUG_IOPORT
436 if (loglevel & CPU_LOG_IOPORT)
437 fprintf(logfile, "outl: %04x %08x\n", addr, val);
438 #endif
439 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
440 #ifdef USE_KQEMU
441 if (env)
442 env->last_io_time = cpu_get_time_fast();
443 #endif
446 int cpu_inb(CPUState *env, int addr)
448 int val;
449 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
450 #ifdef DEBUG_IOPORT
451 if (loglevel & CPU_LOG_IOPORT)
452 fprintf(logfile, "inb : %04x %02x\n", addr, val);
453 #endif
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
458 return val;
461 int cpu_inw(CPUState *env, int addr)
463 int val;
464 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
465 #ifdef DEBUG_IOPORT
466 if (loglevel & CPU_LOG_IOPORT)
467 fprintf(logfile, "inw : %04x %04x\n", addr, val);
468 #endif
469 #ifdef USE_KQEMU
470 if (env)
471 env->last_io_time = cpu_get_time_fast();
472 #endif
473 return val;
476 int cpu_inl(CPUState *env, int addr)
478 int val;
479 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
480 #ifdef DEBUG_IOPORT
481 if (loglevel & CPU_LOG_IOPORT)
482 fprintf(logfile, "inl : %04x %08x\n", addr, val);
483 #endif
484 #ifdef USE_KQEMU
485 if (env)
486 env->last_io_time = cpu_get_time_fast();
487 #endif
488 return val;
491 /***********************************************************/
492 void hw_error(const char *fmt, ...)
494 va_list ap;
495 CPUState *env;
497 va_start(ap, fmt);
498 fprintf(stderr, "qemu: hardware error: ");
499 vfprintf(stderr, fmt, ap);
500 fprintf(stderr, "\n");
501 for(env = first_cpu; env != NULL; env = env->next_cpu) {
502 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
503 #ifdef TARGET_I386
504 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
505 #else
506 cpu_dump_state(env, stderr, fprintf, 0);
507 #endif
509 va_end(ap);
510 abort();
513 /***********************************************************/
514 /* keyboard/mouse */
516 static QEMUPutKBDEvent *qemu_put_kbd_event;
517 static void *qemu_put_kbd_event_opaque;
518 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
519 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
521 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
523 qemu_put_kbd_event_opaque = opaque;
524 qemu_put_kbd_event = func;
527 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
528 void *opaque, int absolute,
529 const char *name)
531 QEMUPutMouseEntry *s, *cursor;
533 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
534 if (!s)
535 return NULL;
537 s->qemu_put_mouse_event = func;
538 s->qemu_put_mouse_event_opaque = opaque;
539 s->qemu_put_mouse_event_absolute = absolute;
540 s->qemu_put_mouse_event_name = qemu_strdup(name);
541 s->next = NULL;
543 if (!qemu_put_mouse_event_head) {
544 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
545 return s;
548 cursor = qemu_put_mouse_event_head;
549 while (cursor->next != NULL)
550 cursor = cursor->next;
552 cursor->next = s;
553 qemu_put_mouse_event_current = s;
555 return s;
558 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
560 QEMUPutMouseEntry *prev = NULL, *cursor;
562 if (!qemu_put_mouse_event_head || entry == NULL)
563 return;
565 cursor = qemu_put_mouse_event_head;
566 while (cursor != NULL && cursor != entry) {
567 prev = cursor;
568 cursor = cursor->next;
571 if (cursor == NULL) // does not exist or list empty
572 return;
573 else if (prev == NULL) { // entry is head
574 qemu_put_mouse_event_head = cursor->next;
575 if (qemu_put_mouse_event_current == entry)
576 qemu_put_mouse_event_current = cursor->next;
577 qemu_free(entry->qemu_put_mouse_event_name);
578 qemu_free(entry);
579 return;
582 prev->next = entry->next;
584 if (qemu_put_mouse_event_current == entry)
585 qemu_put_mouse_event_current = prev;
587 qemu_free(entry->qemu_put_mouse_event_name);
588 qemu_free(entry);
591 void kbd_put_keycode(int keycode)
593 if (qemu_put_kbd_event) {
594 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
598 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
600 QEMUPutMouseEvent *mouse_event;
601 void *mouse_event_opaque;
602 int width;
604 if (!qemu_put_mouse_event_current) {
605 return;
608 mouse_event =
609 qemu_put_mouse_event_current->qemu_put_mouse_event;
610 mouse_event_opaque =
611 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
613 if (mouse_event) {
614 if (graphic_rotate) {
615 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
616 width = 0x7fff;
617 else
618 width = graphic_width;
619 mouse_event(mouse_event_opaque,
620 width - dy, dx, dz, buttons_state);
621 } else
622 mouse_event(mouse_event_opaque,
623 dx, dy, dz, buttons_state);
627 int kbd_mouse_is_absolute(void)
629 if (!qemu_put_mouse_event_current)
630 return 0;
632 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
635 void do_info_mice(void)
637 QEMUPutMouseEntry *cursor;
638 int index = 0;
640 if (!qemu_put_mouse_event_head) {
641 term_printf("No mouse devices connected\n");
642 return;
645 term_printf("Mouse devices available:\n");
646 cursor = qemu_put_mouse_event_head;
647 while (cursor != NULL) {
648 term_printf("%c Mouse #%d: %s\n",
649 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
650 index, cursor->qemu_put_mouse_event_name);
651 index++;
652 cursor = cursor->next;
656 void do_mouse_set(int index)
658 QEMUPutMouseEntry *cursor;
659 int i = 0;
661 if (!qemu_put_mouse_event_head) {
662 term_printf("No mouse devices connected\n");
663 return;
666 cursor = qemu_put_mouse_event_head;
667 while (cursor != NULL && index != i) {
668 i++;
669 cursor = cursor->next;
672 if (cursor != NULL)
673 qemu_put_mouse_event_current = cursor;
674 else
675 term_printf("Mouse at given index not found\n");
678 /* compute with 96 bit intermediate result: (a*b)/c */
679 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
681 union {
682 uint64_t ll;
683 struct {
684 #ifdef WORDS_BIGENDIAN
685 uint32_t high, low;
686 #else
687 uint32_t low, high;
688 #endif
689 } l;
690 } u, res;
691 uint64_t rl, rh;
693 u.ll = a;
694 rl = (uint64_t)u.l.low * (uint64_t)b;
695 rh = (uint64_t)u.l.high * (uint64_t)b;
696 rh += (rl >> 32);
697 res.l.high = rh / c;
698 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
699 return res.ll;
702 /***********************************************************/
703 /* real time host monotonic timer */
705 #define QEMU_TIMER_BASE 1000000000LL
707 #ifdef WIN32
709 static int64_t clock_freq;
711 static void init_get_clock(void)
713 LARGE_INTEGER freq;
714 int ret;
715 ret = QueryPerformanceFrequency(&freq);
716 if (ret == 0) {
717 fprintf(stderr, "Could not calibrate ticks\n");
718 exit(1);
720 clock_freq = freq.QuadPart;
723 static int64_t get_clock(void)
725 LARGE_INTEGER ti;
726 QueryPerformanceCounter(&ti);
727 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
730 #else
732 static int use_rt_clock;
734 static void init_get_clock(void)
736 use_rt_clock = 0;
737 #if defined(__linux__)
739 struct timespec ts;
740 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
741 use_rt_clock = 1;
744 #endif
747 static int64_t get_clock(void)
749 #if defined(__linux__)
750 if (use_rt_clock) {
751 struct timespec ts;
752 clock_gettime(CLOCK_MONOTONIC, &ts);
753 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
754 } else
755 #endif
757 /* XXX: using gettimeofday leads to problems if the date
758 changes, so it should be avoided. */
759 struct timeval tv;
760 gettimeofday(&tv, NULL);
761 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
765 #endif
767 /***********************************************************/
768 /* guest cycle counter */
770 static int64_t cpu_ticks_prev;
771 static int64_t cpu_ticks_offset;
772 static int64_t cpu_clock_offset;
773 static int cpu_ticks_enabled;
775 /* return the host CPU cycle counter and handle stop/restart */
776 int64_t cpu_get_ticks(void)
778 if (!cpu_ticks_enabled) {
779 return cpu_ticks_offset;
780 } else {
781 int64_t ticks;
782 ticks = cpu_get_real_ticks();
783 if (cpu_ticks_prev > ticks) {
784 /* Note: non increasing ticks may happen if the host uses
785 software suspend */
786 cpu_ticks_offset += cpu_ticks_prev - ticks;
788 cpu_ticks_prev = ticks;
789 return ticks + cpu_ticks_offset;
793 /* return the host CPU monotonic timer and handle stop/restart */
794 static int64_t cpu_get_clock(void)
796 int64_t ti;
797 if (!cpu_ticks_enabled) {
798 return cpu_clock_offset;
799 } else {
800 ti = get_clock();
801 return ti + cpu_clock_offset;
805 /* enable cpu_get_ticks() */
806 void cpu_enable_ticks(void)
808 if (!cpu_ticks_enabled) {
809 cpu_ticks_offset -= cpu_get_real_ticks();
810 cpu_clock_offset -= get_clock();
811 cpu_ticks_enabled = 1;
815 /* disable cpu_get_ticks() : the clock is stopped. You must not call
816 cpu_get_ticks() after that. */
817 void cpu_disable_ticks(void)
819 if (cpu_ticks_enabled) {
820 cpu_ticks_offset = cpu_get_ticks();
821 cpu_clock_offset = cpu_get_clock();
822 cpu_ticks_enabled = 0;
826 /***********************************************************/
827 /* timers */
829 #define QEMU_TIMER_REALTIME 0
830 #define QEMU_TIMER_VIRTUAL 1
832 struct QEMUClock {
833 int type;
834 /* XXX: add frequency */
837 struct QEMUTimer {
838 QEMUClock *clock;
839 int64_t expire_time;
840 QEMUTimerCB *cb;
841 void *opaque;
842 struct QEMUTimer *next;
845 struct qemu_alarm_timer {
846 char const *name;
847 unsigned int flags;
849 int (*start)(struct qemu_alarm_timer *t);
850 void (*stop)(struct qemu_alarm_timer *t);
851 void (*rearm)(struct qemu_alarm_timer *t);
852 void *priv;
855 #define ALARM_FLAG_DYNTICKS 0x1
856 #define ALARM_FLAG_EXPIRED 0x2
858 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
860 return t->flags & ALARM_FLAG_DYNTICKS;
863 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
865 if (!alarm_has_dynticks(t))
866 return;
868 t->rearm(t);
871 /* TODO: MIN_TIMER_REARM_US should be optimized */
872 #define MIN_TIMER_REARM_US 250
874 static struct qemu_alarm_timer *alarm_timer;
876 #ifdef _WIN32
878 struct qemu_alarm_win32 {
879 MMRESULT timerId;
880 HANDLE host_alarm;
881 unsigned int period;
882 } alarm_win32_data = {0, NULL, -1};
884 static int win32_start_timer(struct qemu_alarm_timer *t);
885 static void win32_stop_timer(struct qemu_alarm_timer *t);
886 static void win32_rearm_timer(struct qemu_alarm_timer *t);
888 #else
890 static int unix_start_timer(struct qemu_alarm_timer *t);
891 static void unix_stop_timer(struct qemu_alarm_timer *t);
893 #ifdef __linux__
895 static int dynticks_start_timer(struct qemu_alarm_timer *t);
896 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
897 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
899 static int hpet_start_timer(struct qemu_alarm_timer *t);
900 static void hpet_stop_timer(struct qemu_alarm_timer *t);
902 static int rtc_start_timer(struct qemu_alarm_timer *t);
903 static void rtc_stop_timer(struct qemu_alarm_timer *t);
905 #endif /* __linux__ */
907 #endif /* _WIN32 */
909 static struct qemu_alarm_timer alarm_timers[] = {
910 #ifndef _WIN32
911 #ifdef __linux__
912 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
913 dynticks_stop_timer, dynticks_rearm_timer, NULL},
914 /* HPET - if available - is preferred */
915 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
916 /* ...otherwise try RTC */
917 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
918 #endif
919 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
920 #else
921 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
922 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
923 {"win32", 0, win32_start_timer,
924 win32_stop_timer, NULL, &alarm_win32_data},
925 #endif
926 {NULL, }
929 static void show_available_alarms()
931 int i;
933 printf("Available alarm timers, in order of precedence:\n");
934 for (i = 0; alarm_timers[i].name; i++)
935 printf("%s\n", alarm_timers[i].name);
938 static void configure_alarms(char const *opt)
940 int i;
941 int cur = 0;
942 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
943 char *arg;
944 char *name;
946 if (!strcmp(opt, "help")) {
947 show_available_alarms();
948 exit(0);
951 arg = strdup(opt);
953 /* Reorder the array */
954 name = strtok(arg, ",");
955 while (name) {
956 struct qemu_alarm_timer tmp;
958 for (i = 0; i < count && alarm_timers[i].name; i++) {
959 if (!strcmp(alarm_timers[i].name, name))
960 break;
963 if (i == count) {
964 fprintf(stderr, "Unknown clock %s\n", name);
965 goto next;
968 if (i < cur)
969 /* Ignore */
970 goto next;
972 /* Swap */
973 tmp = alarm_timers[i];
974 alarm_timers[i] = alarm_timers[cur];
975 alarm_timers[cur] = tmp;
977 cur++;
978 next:
979 name = strtok(NULL, ",");
982 free(arg);
984 if (cur) {
985 /* Disable remaining timers */
986 for (i = cur; i < count; i++)
987 alarm_timers[i].name = NULL;
990 /* debug */
991 show_available_alarms();
994 QEMUClock *rt_clock;
995 QEMUClock *vm_clock;
997 static QEMUTimer *active_timers[2];
999 static QEMUClock *qemu_new_clock(int type)
1001 QEMUClock *clock;
1002 clock = qemu_mallocz(sizeof(QEMUClock));
1003 if (!clock)
1004 return NULL;
1005 clock->type = type;
1006 return clock;
1009 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1011 QEMUTimer *ts;
1013 ts = qemu_mallocz(sizeof(QEMUTimer));
1014 ts->clock = clock;
1015 ts->cb = cb;
1016 ts->opaque = opaque;
1017 return ts;
1020 void qemu_free_timer(QEMUTimer *ts)
1022 qemu_free(ts);
1025 /* stop a timer, but do not dealloc it */
1026 void qemu_del_timer(QEMUTimer *ts)
1028 QEMUTimer **pt, *t;
1030 /* NOTE: this code must be signal safe because
1031 qemu_timer_expired() can be called from a signal. */
1032 pt = &active_timers[ts->clock->type];
1033 for(;;) {
1034 t = *pt;
1035 if (!t)
1036 break;
1037 if (t == ts) {
1038 *pt = t->next;
1039 break;
1041 pt = &t->next;
1045 /* modify the current timer so that it will be fired when current_time
1046 >= expire_time. The corresponding callback will be called. */
1047 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1049 QEMUTimer **pt, *t;
1051 qemu_del_timer(ts);
1053 /* add the timer in the sorted list */
1054 /* NOTE: this code must be signal safe because
1055 qemu_timer_expired() can be called from a signal. */
1056 pt = &active_timers[ts->clock->type];
1057 for(;;) {
1058 t = *pt;
1059 if (!t)
1060 break;
1061 if (t->expire_time > expire_time)
1062 break;
1063 pt = &t->next;
1065 ts->expire_time = expire_time;
1066 ts->next = *pt;
1067 *pt = ts;
1069 /* Rearm if necessary */
1070 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1071 pt == &active_timers[ts->clock->type])
1072 qemu_rearm_alarm_timer(alarm_timer);
1075 int qemu_timer_pending(QEMUTimer *ts)
1077 QEMUTimer *t;
1078 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1079 if (t == ts)
1080 return 1;
1082 return 0;
1085 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1087 if (!timer_head)
1088 return 0;
1089 return (timer_head->expire_time <= current_time);
1092 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1094 QEMUTimer *ts;
1096 for(;;) {
1097 ts = *ptimer_head;
1098 if (!ts || ts->expire_time > current_time)
1099 break;
1100 /* remove timer from the list before calling the callback */
1101 *ptimer_head = ts->next;
1102 ts->next = NULL;
1104 /* run the callback (the timer list can be modified) */
1105 ts->cb(ts->opaque);
1109 int64_t qemu_get_clock(QEMUClock *clock)
1111 switch(clock->type) {
1112 case QEMU_TIMER_REALTIME:
1113 return get_clock() / 1000000;
1114 default:
1115 case QEMU_TIMER_VIRTUAL:
1116 return cpu_get_clock();
1120 static void init_timers(void)
1122 init_get_clock();
1123 ticks_per_sec = QEMU_TIMER_BASE;
1124 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1125 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1128 /* save a timer */
1129 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1131 uint64_t expire_time;
1133 if (qemu_timer_pending(ts)) {
1134 expire_time = ts->expire_time;
1135 } else {
1136 expire_time = -1;
1138 qemu_put_be64(f, expire_time);
1141 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1143 uint64_t expire_time;
1145 expire_time = qemu_get_be64(f);
1146 if (expire_time != -1) {
1147 qemu_mod_timer(ts, expire_time);
1148 } else {
1149 qemu_del_timer(ts);
1153 static void timer_save(QEMUFile *f, void *opaque)
1155 if (cpu_ticks_enabled) {
1156 hw_error("cannot save state if virtual timers are running");
1158 qemu_put_be64(f, cpu_ticks_offset);
1159 qemu_put_be64(f, ticks_per_sec);
1160 qemu_put_be64(f, cpu_clock_offset);
1163 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1165 if (version_id != 1 && version_id != 2)
1166 return -EINVAL;
1167 if (cpu_ticks_enabled) {
1168 return -EINVAL;
1170 cpu_ticks_offset=qemu_get_be64(f);
1171 ticks_per_sec=qemu_get_be64(f);
1172 if (version_id == 2) {
1173 cpu_clock_offset=qemu_get_be64(f);
1175 return 0;
1178 #ifdef _WIN32
1179 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1180 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1181 #else
1182 static void host_alarm_handler(int host_signum)
1183 #endif
1185 #if 0
1186 #define DISP_FREQ 1000
1188 static int64_t delta_min = INT64_MAX;
1189 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1190 static int count;
1191 ti = qemu_get_clock(vm_clock);
1192 if (last_clock != 0) {
1193 delta = ti - last_clock;
1194 if (delta < delta_min)
1195 delta_min = delta;
1196 if (delta > delta_max)
1197 delta_max = delta;
1198 delta_cum += delta;
1199 if (++count == DISP_FREQ) {
1200 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1201 muldiv64(delta_min, 1000000, ticks_per_sec),
1202 muldiv64(delta_max, 1000000, ticks_per_sec),
1203 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1204 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1205 count = 0;
1206 delta_min = INT64_MAX;
1207 delta_max = 0;
1208 delta_cum = 0;
1211 last_clock = ti;
1213 #endif
1214 if (1 ||
1215 alarm_has_dynticks(alarm_timer) ||
1216 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1217 qemu_get_clock(vm_clock)) ||
1218 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1219 qemu_get_clock(rt_clock))) {
1220 #ifdef _WIN32
1221 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1222 SetEvent(data->host_alarm);
1223 #endif
1224 CPUState *env = next_cpu;
1226 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1228 if (env) {
1229 /* stop the currently executing cpu because a timer occured */
1230 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1231 #ifdef USE_KQEMU
1232 if (env->kqemu_enabled) {
1233 kqemu_cpu_interrupt(env);
1235 #endif
1237 event_pending = 1;
1241 static uint64_t qemu_next_deadline(void)
1243 int64_t nearest_delta_us = INT64_MAX;
1244 int64_t vmdelta_us;
1246 if (active_timers[QEMU_TIMER_REALTIME])
1247 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1248 qemu_get_clock(rt_clock))*1000;
1250 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1251 /* round up */
1252 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1253 qemu_get_clock(vm_clock)+999)/1000;
1254 if (vmdelta_us < nearest_delta_us)
1255 nearest_delta_us = vmdelta_us;
1258 /* Avoid arming the timer to negative, zero, or too low values */
1259 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1260 nearest_delta_us = MIN_TIMER_REARM_US;
1262 return nearest_delta_us;
1265 #ifndef _WIN32
1267 #if defined(__linux__)
1269 #define RTC_FREQ 1024
1271 static void enable_sigio_timer(int fd)
1273 struct sigaction act;
1275 /* timer signal */
1276 sigfillset(&act.sa_mask);
1277 act.sa_flags = 0;
1278 act.sa_handler = host_alarm_handler;
1280 sigaction(SIGIO, &act, NULL);
1281 fcntl(fd, F_SETFL, O_ASYNC);
1282 fcntl(fd, F_SETOWN, getpid());
1285 static int hpet_start_timer(struct qemu_alarm_timer *t)
1287 struct hpet_info info;
1288 int r, fd;
1290 fd = open("/dev/hpet", O_RDONLY);
1291 if (fd < 0)
1292 return -1;
1294 /* Set frequency */
1295 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1296 if (r < 0) {
1297 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1298 "error, but for better emulation accuracy type:\n"
1299 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1300 goto fail;
1303 /* Check capabilities */
1304 r = ioctl(fd, HPET_INFO, &info);
1305 if (r < 0)
1306 goto fail;
1308 /* Enable periodic mode */
1309 r = ioctl(fd, HPET_EPI, 0);
1310 if (info.hi_flags && (r < 0))
1311 goto fail;
1313 /* Enable interrupt */
1314 r = ioctl(fd, HPET_IE_ON, 0);
1315 if (r < 0)
1316 goto fail;
1318 enable_sigio_timer(fd);
1319 t->priv = (void *)(long)fd;
1321 return 0;
1322 fail:
1323 close(fd);
1324 return -1;
1327 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1329 int fd = (long)t->priv;
1331 close(fd);
1334 static int rtc_start_timer(struct qemu_alarm_timer *t)
1336 int rtc_fd;
1337 unsigned long current_rtc_freq = 0;
1339 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1340 if (rtc_fd < 0)
1341 return -1;
1342 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1343 if (current_rtc_freq != RTC_FREQ &&
1344 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1345 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1346 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1347 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1348 goto fail;
1350 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1351 fail:
1352 close(rtc_fd);
1353 return -1;
1356 enable_sigio_timer(rtc_fd);
1358 t->priv = (void *)(long)rtc_fd;
1360 return 0;
1363 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1365 int rtc_fd = (long)t->priv;
1367 close(rtc_fd);
1370 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1372 struct sigevent ev;
1373 timer_t host_timer;
1374 struct sigaction act;
1376 sigfillset(&act.sa_mask);
1377 act.sa_flags = 0;
1378 act.sa_handler = host_alarm_handler;
1380 sigaction(SIGALRM, &act, NULL);
1382 ev.sigev_value.sival_int = 0;
1383 ev.sigev_notify = SIGEV_SIGNAL;
1384 ev.sigev_signo = SIGALRM;
1386 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1387 perror("timer_create");
1389 /* disable dynticks */
1390 fprintf(stderr, "Dynamic Ticks disabled\n");
1392 return -1;
1395 t->priv = (void *)host_timer;
1397 return 0;
1400 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1402 timer_t host_timer = (timer_t)t->priv;
1404 timer_delete(host_timer);
1407 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1409 timer_t host_timer = (timer_t)t->priv;
1410 struct itimerspec timeout;
1411 int64_t nearest_delta_us = INT64_MAX;
1412 int64_t current_us;
1414 if (!active_timers[QEMU_TIMER_REALTIME] &&
1415 !active_timers[QEMU_TIMER_VIRTUAL])
1416 return;
1418 nearest_delta_us = qemu_next_deadline();
1420 /* check whether a timer is already running */
1421 if (timer_gettime(host_timer, &timeout)) {
1422 perror("gettime");
1423 fprintf(stderr, "Internal timer error: aborting\n");
1424 exit(1);
1426 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1427 if (current_us && current_us <= nearest_delta_us)
1428 return;
1430 timeout.it_interval.tv_sec = 0;
1431 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1432 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1433 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1434 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1435 perror("settime");
1436 fprintf(stderr, "Internal timer error: aborting\n");
1437 exit(1);
1441 #endif /* defined(__linux__) */
1443 static int unix_start_timer(struct qemu_alarm_timer *t)
1445 struct sigaction act;
1446 struct itimerval itv;
1447 int err;
1449 /* timer signal */
1450 sigfillset(&act.sa_mask);
1451 act.sa_flags = 0;
1452 act.sa_handler = host_alarm_handler;
1454 sigaction(SIGALRM, &act, NULL);
1456 itv.it_interval.tv_sec = 0;
1457 /* for i386 kernel 2.6 to get 1 ms */
1458 itv.it_interval.tv_usec = 999;
1459 itv.it_value.tv_sec = 0;
1460 itv.it_value.tv_usec = 10 * 1000;
1462 err = setitimer(ITIMER_REAL, &itv, NULL);
1463 if (err)
1464 return -1;
1466 return 0;
1469 static void unix_stop_timer(struct qemu_alarm_timer *t)
1471 struct itimerval itv;
1473 memset(&itv, 0, sizeof(itv));
1474 setitimer(ITIMER_REAL, &itv, NULL);
1477 #endif /* !defined(_WIN32) */
1479 #ifdef _WIN32
1481 static int win32_start_timer(struct qemu_alarm_timer *t)
1483 TIMECAPS tc;
1484 struct qemu_alarm_win32 *data = t->priv;
1485 UINT flags;
1487 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1488 if (!data->host_alarm) {
1489 perror("Failed CreateEvent");
1490 return -1;
1493 memset(&tc, 0, sizeof(tc));
1494 timeGetDevCaps(&tc, sizeof(tc));
1496 if (data->period < tc.wPeriodMin)
1497 data->period = tc.wPeriodMin;
1499 timeBeginPeriod(data->period);
1501 flags = TIME_CALLBACK_FUNCTION;
1502 if (alarm_has_dynticks(t))
1503 flags |= TIME_ONESHOT;
1504 else
1505 flags |= TIME_PERIODIC;
1507 data->timerId = timeSetEvent(1, // interval (ms)
1508 data->period, // resolution
1509 host_alarm_handler, // function
1510 (DWORD)t, // parameter
1511 flags);
1513 if (!data->timerId) {
1514 perror("Failed to initialize win32 alarm timer");
1516 timeEndPeriod(data->period);
1517 CloseHandle(data->host_alarm);
1518 return -1;
1521 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1523 return 0;
1526 static void win32_stop_timer(struct qemu_alarm_timer *t)
1528 struct qemu_alarm_win32 *data = t->priv;
1530 timeKillEvent(data->timerId);
1531 timeEndPeriod(data->period);
1533 CloseHandle(data->host_alarm);
1536 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1538 struct qemu_alarm_win32 *data = t->priv;
1539 uint64_t nearest_delta_us;
1541 if (!active_timers[QEMU_TIMER_REALTIME] &&
1542 !active_timers[QEMU_TIMER_VIRTUAL])
1543 return;
1545 nearest_delta_us = qemu_next_deadline();
1546 nearest_delta_us /= 1000;
1548 timeKillEvent(data->timerId);
1550 data->timerId = timeSetEvent(1,
1551 data->period,
1552 host_alarm_handler,
1553 (DWORD)t,
1554 TIME_ONESHOT | TIME_PERIODIC);
1556 if (!data->timerId) {
1557 perror("Failed to re-arm win32 alarm timer");
1559 timeEndPeriod(data->period);
1560 CloseHandle(data->host_alarm);
1561 exit(1);
1565 #endif /* _WIN32 */
1567 static void init_timer_alarm(void)
1569 struct qemu_alarm_timer *t;
1570 int i, err = -1;
1572 for (i = 0; alarm_timers[i].name; i++) {
1573 t = &alarm_timers[i];
1575 err = t->start(t);
1576 if (!err)
1577 break;
1580 if (err) {
1581 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1582 fprintf(stderr, "Terminating\n");
1583 exit(1);
1586 alarm_timer = t;
1589 static void quit_timers(void)
1591 alarm_timer->stop(alarm_timer);
1592 alarm_timer = NULL;
1595 /***********************************************************/
1596 /* character device */
1598 static void qemu_chr_event(CharDriverState *s, int event)
1600 if (!s->chr_event)
1601 return;
1602 s->chr_event(s->handler_opaque, event);
1605 static void qemu_chr_reset_bh(void *opaque)
1607 CharDriverState *s = opaque;
1608 qemu_chr_event(s, CHR_EVENT_RESET);
1609 qemu_bh_delete(s->bh);
1610 s->bh = NULL;
1613 void qemu_chr_reset(CharDriverState *s)
1615 if (s->bh == NULL) {
1616 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1617 qemu_bh_schedule(s->bh);
1621 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1623 return s->chr_write(s, buf, len);
1626 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1628 if (!s->chr_ioctl)
1629 return -ENOTSUP;
1630 return s->chr_ioctl(s, cmd, arg);
1633 int qemu_chr_can_read(CharDriverState *s)
1635 if (!s->chr_can_read)
1636 return 0;
1637 return s->chr_can_read(s->handler_opaque);
1640 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1642 s->chr_read(s->handler_opaque, buf, len);
1645 void qemu_chr_accept_input(CharDriverState *s)
1647 if (s->chr_accept_input)
1648 s->chr_accept_input(s);
1651 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1653 char buf[4096];
1654 va_list ap;
1655 va_start(ap, fmt);
1656 vsnprintf(buf, sizeof(buf), fmt, ap);
1657 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1658 va_end(ap);
1661 void qemu_chr_send_event(CharDriverState *s, int event)
1663 if (s->chr_send_event)
1664 s->chr_send_event(s, event);
1667 void qemu_chr_add_handlers(CharDriverState *s,
1668 IOCanRWHandler *fd_can_read,
1669 IOReadHandler *fd_read,
1670 IOEventHandler *fd_event,
1671 void *opaque)
1673 s->chr_can_read = fd_can_read;
1674 s->chr_read = fd_read;
1675 s->chr_event = fd_event;
1676 s->handler_opaque = opaque;
1677 if (s->chr_update_read_handler)
1678 s->chr_update_read_handler(s);
1681 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1683 return len;
1686 static CharDriverState *qemu_chr_open_null(void)
1688 CharDriverState *chr;
1690 chr = qemu_mallocz(sizeof(CharDriverState));
1691 if (!chr)
1692 return NULL;
1693 chr->chr_write = null_chr_write;
1694 return chr;
1697 /* MUX driver for serial I/O splitting */
1698 static int term_timestamps;
1699 static int64_t term_timestamps_start;
1700 #define MAX_MUX 4
1701 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1702 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1703 typedef struct {
1704 IOCanRWHandler *chr_can_read[MAX_MUX];
1705 IOReadHandler *chr_read[MAX_MUX];
1706 IOEventHandler *chr_event[MAX_MUX];
1707 void *ext_opaque[MAX_MUX];
1708 CharDriverState *drv;
1709 unsigned char buffer[MUX_BUFFER_SIZE];
1710 int prod;
1711 int cons;
1712 int mux_cnt;
1713 int term_got_escape;
1714 int max_size;
1715 } MuxDriver;
1718 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1720 MuxDriver *d = chr->opaque;
1721 int ret;
1722 if (!term_timestamps) {
1723 ret = d->drv->chr_write(d->drv, buf, len);
1724 } else {
1725 int i;
1727 ret = 0;
1728 for(i = 0; i < len; i++) {
1729 ret += d->drv->chr_write(d->drv, buf+i, 1);
1730 if (buf[i] == '\n') {
1731 char buf1[64];
1732 int64_t ti;
1733 int secs;
1735 ti = get_clock();
1736 if (term_timestamps_start == -1)
1737 term_timestamps_start = ti;
1738 ti -= term_timestamps_start;
1739 secs = ti / 1000000000;
1740 snprintf(buf1, sizeof(buf1),
1741 "[%02d:%02d:%02d.%03d] ",
1742 secs / 3600,
1743 (secs / 60) % 60,
1744 secs % 60,
1745 (int)((ti / 1000000) % 1000));
1746 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1750 return ret;
1753 static char *mux_help[] = {
1754 "% h print this help\n\r",
1755 "% x exit emulator\n\r",
1756 "% s save disk data back to file (if -snapshot)\n\r",
1757 "% t toggle console timestamps\n\r"
1758 "% b send break (magic sysrq)\n\r",
1759 "% c switch between console and monitor\n\r",
1760 "% % sends %\n\r",
1761 NULL
1764 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1765 static void mux_print_help(CharDriverState *chr)
1767 int i, j;
1768 char ebuf[15] = "Escape-Char";
1769 char cbuf[50] = "\n\r";
1771 if (term_escape_char > 0 && term_escape_char < 26) {
1772 sprintf(cbuf,"\n\r");
1773 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1774 } else {
1775 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1776 term_escape_char);
1778 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1779 for (i = 0; mux_help[i] != NULL; i++) {
1780 for (j=0; mux_help[i][j] != '\0'; j++) {
1781 if (mux_help[i][j] == '%')
1782 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1783 else
1784 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1789 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1791 if (d->term_got_escape) {
1792 d->term_got_escape = 0;
1793 if (ch == term_escape_char)
1794 goto send_char;
1795 switch(ch) {
1796 case '?':
1797 case 'h':
1798 mux_print_help(chr);
1799 break;
1800 case 'x':
1802 char *term = "QEMU: Terminated\n\r";
1803 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1804 exit(0);
1805 break;
1807 case 's':
1809 int i;
1810 for (i = 0; i < nb_drives; i++) {
1811 bdrv_commit(drives_table[i].bdrv);
1814 break;
1815 case 'b':
1816 qemu_chr_event(chr, CHR_EVENT_BREAK);
1817 break;
1818 case 'c':
1819 /* Switch to the next registered device */
1820 chr->focus++;
1821 if (chr->focus >= d->mux_cnt)
1822 chr->focus = 0;
1823 break;
1824 case 't':
1825 term_timestamps = !term_timestamps;
1826 term_timestamps_start = -1;
1827 break;
1829 } else if (ch == term_escape_char) {
1830 d->term_got_escape = 1;
1831 } else {
1832 send_char:
1833 return 1;
1835 return 0;
1838 static void mux_chr_accept_input(CharDriverState *chr)
1840 int m = chr->focus;
1841 MuxDriver *d = chr->opaque;
1843 while (d->prod != d->cons &&
1844 d->chr_can_read[m] &&
1845 d->chr_can_read[m](d->ext_opaque[m])) {
1846 d->chr_read[m](d->ext_opaque[m],
1847 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1851 static int mux_chr_can_read(void *opaque)
1853 CharDriverState *chr = opaque;
1854 MuxDriver *d = chr->opaque;
1856 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1857 return 1;
1858 if (d->chr_can_read[chr->focus])
1859 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1860 return 0;
1863 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1865 CharDriverState *chr = opaque;
1866 MuxDriver *d = chr->opaque;
1867 int m = chr->focus;
1868 int i;
1870 mux_chr_accept_input (opaque);
1872 for(i = 0; i < size; i++)
1873 if (mux_proc_byte(chr, d, buf[i])) {
1874 if (d->prod == d->cons &&
1875 d->chr_can_read[m] &&
1876 d->chr_can_read[m](d->ext_opaque[m]))
1877 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1878 else
1879 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1883 static void mux_chr_event(void *opaque, int event)
1885 CharDriverState *chr = opaque;
1886 MuxDriver *d = chr->opaque;
1887 int i;
1889 /* Send the event to all registered listeners */
1890 for (i = 0; i < d->mux_cnt; i++)
1891 if (d->chr_event[i])
1892 d->chr_event[i](d->ext_opaque[i], event);
1895 static void mux_chr_update_read_handler(CharDriverState *chr)
1897 MuxDriver *d = chr->opaque;
1899 if (d->mux_cnt >= MAX_MUX) {
1900 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1901 return;
1903 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1904 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1905 d->chr_read[d->mux_cnt] = chr->chr_read;
1906 d->chr_event[d->mux_cnt] = chr->chr_event;
1907 /* Fix up the real driver with mux routines */
1908 if (d->mux_cnt == 0) {
1909 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1910 mux_chr_event, chr);
1912 chr->focus = d->mux_cnt;
1913 d->mux_cnt++;
1916 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1918 CharDriverState *chr;
1919 MuxDriver *d;
1921 chr = qemu_mallocz(sizeof(CharDriverState));
1922 if (!chr)
1923 return NULL;
1924 d = qemu_mallocz(sizeof(MuxDriver));
1925 if (!d) {
1926 free(chr);
1927 return NULL;
1930 chr->opaque = d;
1931 d->drv = drv;
1932 chr->focus = -1;
1933 chr->chr_write = mux_chr_write;
1934 chr->chr_update_read_handler = mux_chr_update_read_handler;
1935 chr->chr_accept_input = mux_chr_accept_input;
1936 return chr;
1940 #ifdef _WIN32
1942 static void socket_cleanup(void)
1944 WSACleanup();
1947 static int socket_init(void)
1949 WSADATA Data;
1950 int ret, err;
1952 ret = WSAStartup(MAKEWORD(2,2), &Data);
1953 if (ret != 0) {
1954 err = WSAGetLastError();
1955 fprintf(stderr, "WSAStartup: %d\n", err);
1956 return -1;
1958 atexit(socket_cleanup);
1959 return 0;
1962 static int send_all(int fd, const uint8_t *buf, int len1)
1964 int ret, len;
1966 len = len1;
1967 while (len > 0) {
1968 ret = send(fd, buf, len, 0);
1969 if (ret < 0) {
1970 int errno;
1971 errno = WSAGetLastError();
1972 if (errno != WSAEWOULDBLOCK) {
1973 return -1;
1975 } else if (ret == 0) {
1976 break;
1977 } else {
1978 buf += ret;
1979 len -= ret;
1982 return len1 - len;
1985 void socket_set_nonblock(int fd)
1987 unsigned long opt = 1;
1988 ioctlsocket(fd, FIONBIO, &opt);
1991 #else
1993 static int unix_write(int fd, const uint8_t *buf, int len1)
1995 int ret, len;
1997 len = len1;
1998 while (len > 0) {
1999 ret = write(fd, buf, len);
2000 if (ret < 0) {
2001 if (errno != EINTR && errno != EAGAIN)
2002 return -1;
2003 } else if (ret == 0) {
2004 break;
2005 } else {
2006 buf += ret;
2007 len -= ret;
2010 return len1 - len;
2013 static inline int send_all(int fd, const uint8_t *buf, int len1)
2015 return unix_write(fd, buf, len1);
2018 void socket_set_nonblock(int fd)
2020 fcntl(fd, F_SETFL, O_NONBLOCK);
2022 #endif /* !_WIN32 */
2024 #ifndef _WIN32
2026 typedef struct {
2027 int fd_in, fd_out;
2028 int max_size;
2029 } FDCharDriver;
2031 #define STDIO_MAX_CLIENTS 1
2032 static int stdio_nb_clients = 0;
2034 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2036 FDCharDriver *s = chr->opaque;
2037 return unix_write(s->fd_out, buf, len);
2040 static int fd_chr_read_poll(void *opaque)
2042 CharDriverState *chr = opaque;
2043 FDCharDriver *s = chr->opaque;
2045 s->max_size = qemu_chr_can_read(chr);
2046 return s->max_size;
2049 static void fd_chr_read(void *opaque)
2051 CharDriverState *chr = opaque;
2052 FDCharDriver *s = chr->opaque;
2053 int size, len;
2054 uint8_t buf[1024];
2056 len = sizeof(buf);
2057 if (len > s->max_size)
2058 len = s->max_size;
2059 if (len == 0)
2060 return;
2061 size = read(s->fd_in, buf, len);
2062 if (size == 0) {
2063 /* FD has been closed. Remove it from the active list. */
2064 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2065 return;
2067 if (size > 0) {
2068 qemu_chr_read(chr, buf, size);
2072 static void fd_chr_update_read_handler(CharDriverState *chr)
2074 FDCharDriver *s = chr->opaque;
2076 if (s->fd_in >= 0) {
2077 if (nographic && s->fd_in == 0) {
2078 } else {
2079 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2080 fd_chr_read, NULL, chr);
2085 static void fd_chr_close(struct CharDriverState *chr)
2087 FDCharDriver *s = chr->opaque;
2089 if (s->fd_in >= 0) {
2090 if (nographic && s->fd_in == 0) {
2091 } else {
2092 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2096 qemu_free(s);
2099 /* open a character device to a unix fd */
2100 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2102 CharDriverState *chr;
2103 FDCharDriver *s;
2105 chr = qemu_mallocz(sizeof(CharDriverState));
2106 if (!chr)
2107 return NULL;
2108 s = qemu_mallocz(sizeof(FDCharDriver));
2109 if (!s) {
2110 free(chr);
2111 return NULL;
2113 s->fd_in = fd_in;
2114 s->fd_out = fd_out;
2115 chr->opaque = s;
2116 chr->chr_write = fd_chr_write;
2117 chr->chr_update_read_handler = fd_chr_update_read_handler;
2118 chr->chr_close = fd_chr_close;
2120 qemu_chr_reset(chr);
2122 return chr;
2125 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2127 int fd_out;
2129 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2130 if (fd_out < 0)
2131 return NULL;
2132 return qemu_chr_open_fd(-1, fd_out);
2135 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2137 int fd_in, fd_out;
2138 char filename_in[256], filename_out[256];
2140 snprintf(filename_in, 256, "%s.in", filename);
2141 snprintf(filename_out, 256, "%s.out", filename);
2142 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2143 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2144 if (fd_in < 0 || fd_out < 0) {
2145 if (fd_in >= 0)
2146 close(fd_in);
2147 if (fd_out >= 0)
2148 close(fd_out);
2149 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2150 if (fd_in < 0)
2151 return NULL;
2153 return qemu_chr_open_fd(fd_in, fd_out);
2157 /* for STDIO, we handle the case where several clients use it
2158 (nographic mode) */
2160 #define TERM_FIFO_MAX_SIZE 1
2162 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2163 static int term_fifo_size;
2165 static int stdio_read_poll(void *opaque)
2167 CharDriverState *chr = opaque;
2169 /* try to flush the queue if needed */
2170 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2171 qemu_chr_read(chr, term_fifo, 1);
2172 term_fifo_size = 0;
2174 /* see if we can absorb more chars */
2175 if (term_fifo_size == 0)
2176 return 1;
2177 else
2178 return 0;
2181 static void stdio_read(void *opaque)
2183 int size;
2184 uint8_t buf[1];
2185 CharDriverState *chr = opaque;
2187 size = read(0, buf, 1);
2188 if (size == 0) {
2189 /* stdin has been closed. Remove it from the active list. */
2190 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2191 return;
2193 if (size > 0) {
2194 if (qemu_chr_can_read(chr) > 0) {
2195 qemu_chr_read(chr, buf, 1);
2196 } else if (term_fifo_size == 0) {
2197 term_fifo[term_fifo_size++] = buf[0];
2202 /* init terminal so that we can grab keys */
2203 static struct termios oldtty;
2204 static int old_fd0_flags;
2205 static int term_atexit_done;
2207 static void term_exit(void)
2209 tcsetattr (0, TCSANOW, &oldtty);
2210 fcntl(0, F_SETFL, old_fd0_flags);
2213 static void term_init(void)
2215 struct termios tty;
2217 tcgetattr (0, &tty);
2218 oldtty = tty;
2219 old_fd0_flags = fcntl(0, F_GETFL);
2221 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2222 |INLCR|IGNCR|ICRNL|IXON);
2223 tty.c_oflag |= OPOST;
2224 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2225 /* if graphical mode, we allow Ctrl-C handling */
2226 if (nographic)
2227 tty.c_lflag &= ~ISIG;
2228 tty.c_cflag &= ~(CSIZE|PARENB);
2229 tty.c_cflag |= CS8;
2230 tty.c_cc[VMIN] = 1;
2231 tty.c_cc[VTIME] = 0;
2233 tcsetattr (0, TCSANOW, &tty);
2235 if (!term_atexit_done++)
2236 atexit(term_exit);
2238 fcntl(0, F_SETFL, O_NONBLOCK);
2241 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2243 term_exit();
2244 stdio_nb_clients--;
2245 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2246 fd_chr_close(chr);
2249 static CharDriverState *qemu_chr_open_stdio(void)
2251 CharDriverState *chr;
2253 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2254 return NULL;
2255 chr = qemu_chr_open_fd(0, 1);
2256 chr->chr_close = qemu_chr_close_stdio;
2257 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2258 stdio_nb_clients++;
2259 term_init();
2261 return chr;
2264 #if defined(__linux__) || defined(__sun__)
2265 static CharDriverState *qemu_chr_open_pty(void)
2267 struct termios tty;
2268 char slave_name[1024];
2269 int master_fd, slave_fd;
2271 #if defined(__linux__)
2272 /* Not satisfying */
2273 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2274 return NULL;
2276 #endif
2278 /* Disabling local echo and line-buffered output */
2279 tcgetattr (master_fd, &tty);
2280 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2281 tty.c_cc[VMIN] = 1;
2282 tty.c_cc[VTIME] = 0;
2283 tcsetattr (master_fd, TCSAFLUSH, &tty);
2285 fprintf(stderr, "char device redirected to %s\n", slave_name);
2286 return qemu_chr_open_fd(master_fd, master_fd);
2289 static void tty_serial_init(int fd, int speed,
2290 int parity, int data_bits, int stop_bits)
2292 struct termios tty;
2293 speed_t spd;
2295 #if 0
2296 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2297 speed, parity, data_bits, stop_bits);
2298 #endif
2299 tcgetattr (fd, &tty);
2301 #define MARGIN 1.1
2302 if (speed <= 50 * MARGIN)
2303 spd = B50;
2304 else if (speed <= 75 * MARGIN)
2305 spd = B75;
2306 else if (speed <= 300 * MARGIN)
2307 spd = B300;
2308 else if (speed <= 600 * MARGIN)
2309 spd = B600;
2310 else if (speed <= 1200 * MARGIN)
2311 spd = B1200;
2312 else if (speed <= 2400 * MARGIN)
2313 spd = B2400;
2314 else if (speed <= 4800 * MARGIN)
2315 spd = B4800;
2316 else if (speed <= 9600 * MARGIN)
2317 spd = B9600;
2318 else if (speed <= 19200 * MARGIN)
2319 spd = B19200;
2320 else if (speed <= 38400 * MARGIN)
2321 spd = B38400;
2322 else if (speed <= 57600 * MARGIN)
2323 spd = B57600;
2324 else if (speed <= 115200 * MARGIN)
2325 spd = B115200;
2326 else
2327 spd = B115200;
2329 cfsetispeed(&tty, spd);
2330 cfsetospeed(&tty, spd);
2332 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2333 |INLCR|IGNCR|ICRNL|IXON);
2334 tty.c_oflag |= OPOST;
2335 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2336 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2337 switch(data_bits) {
2338 default:
2339 case 8:
2340 tty.c_cflag |= CS8;
2341 break;
2342 case 7:
2343 tty.c_cflag |= CS7;
2344 break;
2345 case 6:
2346 tty.c_cflag |= CS6;
2347 break;
2348 case 5:
2349 tty.c_cflag |= CS5;
2350 break;
2352 switch(parity) {
2353 default:
2354 case 'N':
2355 break;
2356 case 'E':
2357 tty.c_cflag |= PARENB;
2358 break;
2359 case 'O':
2360 tty.c_cflag |= PARENB | PARODD;
2361 break;
2363 if (stop_bits == 2)
2364 tty.c_cflag |= CSTOPB;
2366 tcsetattr (fd, TCSANOW, &tty);
2369 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2371 FDCharDriver *s = chr->opaque;
2373 switch(cmd) {
2374 case CHR_IOCTL_SERIAL_SET_PARAMS:
2376 QEMUSerialSetParams *ssp = arg;
2377 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2378 ssp->data_bits, ssp->stop_bits);
2380 break;
2381 case CHR_IOCTL_SERIAL_SET_BREAK:
2383 int enable = *(int *)arg;
2384 if (enable)
2385 tcsendbreak(s->fd_in, 1);
2387 break;
2388 default:
2389 return -ENOTSUP;
2391 return 0;
2394 static CharDriverState *qemu_chr_open_tty(const char *filename)
2396 CharDriverState *chr;
2397 int fd;
2399 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2400 fcntl(fd, F_SETFL, O_NONBLOCK);
2401 tty_serial_init(fd, 115200, 'N', 8, 1);
2402 chr = qemu_chr_open_fd(fd, fd);
2403 if (!chr) {
2404 close(fd);
2405 return NULL;
2407 chr->chr_ioctl = tty_serial_ioctl;
2408 qemu_chr_reset(chr);
2409 return chr;
2411 #else /* ! __linux__ && ! __sun__ */
2412 static CharDriverState *qemu_chr_open_pty(void)
2414 return NULL;
2416 #endif /* __linux__ || __sun__ */
2418 #if defined(__linux__)
2419 typedef struct {
2420 int fd;
2421 int mode;
2422 } ParallelCharDriver;
2424 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2426 if (s->mode != mode) {
2427 int m = mode;
2428 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2429 return 0;
2430 s->mode = mode;
2432 return 1;
2435 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2437 ParallelCharDriver *drv = chr->opaque;
2438 int fd = drv->fd;
2439 uint8_t b;
2441 switch(cmd) {
2442 case CHR_IOCTL_PP_READ_DATA:
2443 if (ioctl(fd, PPRDATA, &b) < 0)
2444 return -ENOTSUP;
2445 *(uint8_t *)arg = b;
2446 break;
2447 case CHR_IOCTL_PP_WRITE_DATA:
2448 b = *(uint8_t *)arg;
2449 if (ioctl(fd, PPWDATA, &b) < 0)
2450 return -ENOTSUP;
2451 break;
2452 case CHR_IOCTL_PP_READ_CONTROL:
2453 if (ioctl(fd, PPRCONTROL, &b) < 0)
2454 return -ENOTSUP;
2455 /* Linux gives only the lowest bits, and no way to know data
2456 direction! For better compatibility set the fixed upper
2457 bits. */
2458 *(uint8_t *)arg = b | 0xc0;
2459 break;
2460 case CHR_IOCTL_PP_WRITE_CONTROL:
2461 b = *(uint8_t *)arg;
2462 if (ioctl(fd, PPWCONTROL, &b) < 0)
2463 return -ENOTSUP;
2464 break;
2465 case CHR_IOCTL_PP_READ_STATUS:
2466 if (ioctl(fd, PPRSTATUS, &b) < 0)
2467 return -ENOTSUP;
2468 *(uint8_t *)arg = b;
2469 break;
2470 case CHR_IOCTL_PP_EPP_READ_ADDR:
2471 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2472 struct ParallelIOArg *parg = arg;
2473 int n = read(fd, parg->buffer, parg->count);
2474 if (n != parg->count) {
2475 return -EIO;
2478 break;
2479 case CHR_IOCTL_PP_EPP_READ:
2480 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2481 struct ParallelIOArg *parg = arg;
2482 int n = read(fd, parg->buffer, parg->count);
2483 if (n != parg->count) {
2484 return -EIO;
2487 break;
2488 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2489 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2490 struct ParallelIOArg *parg = arg;
2491 int n = write(fd, parg->buffer, parg->count);
2492 if (n != parg->count) {
2493 return -EIO;
2496 break;
2497 case CHR_IOCTL_PP_EPP_WRITE:
2498 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2499 struct ParallelIOArg *parg = arg;
2500 int n = write(fd, parg->buffer, parg->count);
2501 if (n != parg->count) {
2502 return -EIO;
2505 break;
2506 default:
2507 return -ENOTSUP;
2509 return 0;
2512 static void pp_close(CharDriverState *chr)
2514 ParallelCharDriver *drv = chr->opaque;
2515 int fd = drv->fd;
2517 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2518 ioctl(fd, PPRELEASE);
2519 close(fd);
2520 qemu_free(drv);
2523 static CharDriverState *qemu_chr_open_pp(const char *filename)
2525 CharDriverState *chr;
2526 ParallelCharDriver *drv;
2527 int fd;
2529 TFR(fd = open(filename, O_RDWR));
2530 if (fd < 0)
2531 return NULL;
2533 if (ioctl(fd, PPCLAIM) < 0) {
2534 close(fd);
2535 return NULL;
2538 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2539 if (!drv) {
2540 close(fd);
2541 return NULL;
2543 drv->fd = fd;
2544 drv->mode = IEEE1284_MODE_COMPAT;
2546 chr = qemu_mallocz(sizeof(CharDriverState));
2547 if (!chr) {
2548 qemu_free(drv);
2549 close(fd);
2550 return NULL;
2552 chr->chr_write = null_chr_write;
2553 chr->chr_ioctl = pp_ioctl;
2554 chr->chr_close = pp_close;
2555 chr->opaque = drv;
2557 qemu_chr_reset(chr);
2559 return chr;
2561 #endif /* __linux__ */
2563 #else /* _WIN32 */
2565 typedef struct {
2566 int max_size;
2567 HANDLE hcom, hrecv, hsend;
2568 OVERLAPPED orecv, osend;
2569 BOOL fpipe;
2570 DWORD len;
2571 } WinCharState;
2573 #define NSENDBUF 2048
2574 #define NRECVBUF 2048
2575 #define MAXCONNECT 1
2576 #define NTIMEOUT 5000
2578 static int win_chr_poll(void *opaque);
2579 static int win_chr_pipe_poll(void *opaque);
2581 static void win_chr_close(CharDriverState *chr)
2583 WinCharState *s = chr->opaque;
2585 if (s->hsend) {
2586 CloseHandle(s->hsend);
2587 s->hsend = NULL;
2589 if (s->hrecv) {
2590 CloseHandle(s->hrecv);
2591 s->hrecv = NULL;
2593 if (s->hcom) {
2594 CloseHandle(s->hcom);
2595 s->hcom = NULL;
2597 if (s->fpipe)
2598 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2599 else
2600 qemu_del_polling_cb(win_chr_poll, chr);
2603 static int win_chr_init(CharDriverState *chr, const char *filename)
2605 WinCharState *s = chr->opaque;
2606 COMMCONFIG comcfg;
2607 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2608 COMSTAT comstat;
2609 DWORD size;
2610 DWORD err;
2612 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2613 if (!s->hsend) {
2614 fprintf(stderr, "Failed CreateEvent\n");
2615 goto fail;
2617 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2618 if (!s->hrecv) {
2619 fprintf(stderr, "Failed CreateEvent\n");
2620 goto fail;
2623 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2624 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2625 if (s->hcom == INVALID_HANDLE_VALUE) {
2626 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2627 s->hcom = NULL;
2628 goto fail;
2631 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2632 fprintf(stderr, "Failed SetupComm\n");
2633 goto fail;
2636 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2637 size = sizeof(COMMCONFIG);
2638 GetDefaultCommConfig(filename, &comcfg, &size);
2639 comcfg.dcb.DCBlength = sizeof(DCB);
2640 CommConfigDialog(filename, NULL, &comcfg);
2642 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2643 fprintf(stderr, "Failed SetCommState\n");
2644 goto fail;
2647 if (!SetCommMask(s->hcom, EV_ERR)) {
2648 fprintf(stderr, "Failed SetCommMask\n");
2649 goto fail;
2652 cto.ReadIntervalTimeout = MAXDWORD;
2653 if (!SetCommTimeouts(s->hcom, &cto)) {
2654 fprintf(stderr, "Failed SetCommTimeouts\n");
2655 goto fail;
2658 if (!ClearCommError(s->hcom, &err, &comstat)) {
2659 fprintf(stderr, "Failed ClearCommError\n");
2660 goto fail;
2662 qemu_add_polling_cb(win_chr_poll, chr);
2663 return 0;
2665 fail:
2666 win_chr_close(chr);
2667 return -1;
2670 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2672 WinCharState *s = chr->opaque;
2673 DWORD len, ret, size, err;
2675 len = len1;
2676 ZeroMemory(&s->osend, sizeof(s->osend));
2677 s->osend.hEvent = s->hsend;
2678 while (len > 0) {
2679 if (s->hsend)
2680 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2681 else
2682 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2683 if (!ret) {
2684 err = GetLastError();
2685 if (err == ERROR_IO_PENDING) {
2686 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2687 if (ret) {
2688 buf += size;
2689 len -= size;
2690 } else {
2691 break;
2693 } else {
2694 break;
2696 } else {
2697 buf += size;
2698 len -= size;
2701 return len1 - len;
2704 static int win_chr_read_poll(CharDriverState *chr)
2706 WinCharState *s = chr->opaque;
2708 s->max_size = qemu_chr_can_read(chr);
2709 return s->max_size;
2712 static void win_chr_readfile(CharDriverState *chr)
2714 WinCharState *s = chr->opaque;
2715 int ret, err;
2716 uint8_t buf[1024];
2717 DWORD size;
2719 ZeroMemory(&s->orecv, sizeof(s->orecv));
2720 s->orecv.hEvent = s->hrecv;
2721 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2722 if (!ret) {
2723 err = GetLastError();
2724 if (err == ERROR_IO_PENDING) {
2725 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2729 if (size > 0) {
2730 qemu_chr_read(chr, buf, size);
2734 static void win_chr_read(CharDriverState *chr)
2736 WinCharState *s = chr->opaque;
2738 if (s->len > s->max_size)
2739 s->len = s->max_size;
2740 if (s->len == 0)
2741 return;
2743 win_chr_readfile(chr);
2746 static int win_chr_poll(void *opaque)
2748 CharDriverState *chr = opaque;
2749 WinCharState *s = chr->opaque;
2750 COMSTAT status;
2751 DWORD comerr;
2753 ClearCommError(s->hcom, &comerr, &status);
2754 if (status.cbInQue > 0) {
2755 s->len = status.cbInQue;
2756 win_chr_read_poll(chr);
2757 win_chr_read(chr);
2758 return 1;
2760 return 0;
2763 static CharDriverState *qemu_chr_open_win(const char *filename)
2765 CharDriverState *chr;
2766 WinCharState *s;
2768 chr = qemu_mallocz(sizeof(CharDriverState));
2769 if (!chr)
2770 return NULL;
2771 s = qemu_mallocz(sizeof(WinCharState));
2772 if (!s) {
2773 free(chr);
2774 return NULL;
2776 chr->opaque = s;
2777 chr->chr_write = win_chr_write;
2778 chr->chr_close = win_chr_close;
2780 if (win_chr_init(chr, filename) < 0) {
2781 free(s);
2782 free(chr);
2783 return NULL;
2785 qemu_chr_reset(chr);
2786 return chr;
2789 static int win_chr_pipe_poll(void *opaque)
2791 CharDriverState *chr = opaque;
2792 WinCharState *s = chr->opaque;
2793 DWORD size;
2795 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2796 if (size > 0) {
2797 s->len = size;
2798 win_chr_read_poll(chr);
2799 win_chr_read(chr);
2800 return 1;
2802 return 0;
2805 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2807 WinCharState *s = chr->opaque;
2808 OVERLAPPED ov;
2809 int ret;
2810 DWORD size;
2811 char openname[256];
2813 s->fpipe = TRUE;
2815 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2816 if (!s->hsend) {
2817 fprintf(stderr, "Failed CreateEvent\n");
2818 goto fail;
2820 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2821 if (!s->hrecv) {
2822 fprintf(stderr, "Failed CreateEvent\n");
2823 goto fail;
2826 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2827 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2828 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2829 PIPE_WAIT,
2830 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2831 if (s->hcom == INVALID_HANDLE_VALUE) {
2832 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2833 s->hcom = NULL;
2834 goto fail;
2837 ZeroMemory(&ov, sizeof(ov));
2838 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2839 ret = ConnectNamedPipe(s->hcom, &ov);
2840 if (ret) {
2841 fprintf(stderr, "Failed ConnectNamedPipe\n");
2842 goto fail;
2845 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2846 if (!ret) {
2847 fprintf(stderr, "Failed GetOverlappedResult\n");
2848 if (ov.hEvent) {
2849 CloseHandle(ov.hEvent);
2850 ov.hEvent = NULL;
2852 goto fail;
2855 if (ov.hEvent) {
2856 CloseHandle(ov.hEvent);
2857 ov.hEvent = NULL;
2859 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2860 return 0;
2862 fail:
2863 win_chr_close(chr);
2864 return -1;
2868 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2870 CharDriverState *chr;
2871 WinCharState *s;
2873 chr = qemu_mallocz(sizeof(CharDriverState));
2874 if (!chr)
2875 return NULL;
2876 s = qemu_mallocz(sizeof(WinCharState));
2877 if (!s) {
2878 free(chr);
2879 return NULL;
2881 chr->opaque = s;
2882 chr->chr_write = win_chr_write;
2883 chr->chr_close = win_chr_close;
2885 if (win_chr_pipe_init(chr, filename) < 0) {
2886 free(s);
2887 free(chr);
2888 return NULL;
2890 qemu_chr_reset(chr);
2891 return chr;
2894 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2896 CharDriverState *chr;
2897 WinCharState *s;
2899 chr = qemu_mallocz(sizeof(CharDriverState));
2900 if (!chr)
2901 return NULL;
2902 s = qemu_mallocz(sizeof(WinCharState));
2903 if (!s) {
2904 free(chr);
2905 return NULL;
2907 s->hcom = fd_out;
2908 chr->opaque = s;
2909 chr->chr_write = win_chr_write;
2910 qemu_chr_reset(chr);
2911 return chr;
2914 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2916 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2919 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2921 HANDLE fd_out;
2923 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2924 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2925 if (fd_out == INVALID_HANDLE_VALUE)
2926 return NULL;
2928 return qemu_chr_open_win_file(fd_out);
2930 #endif /* !_WIN32 */
2932 /***********************************************************/
2933 /* UDP Net console */
2935 typedef struct {
2936 int fd;
2937 struct sockaddr_in daddr;
2938 uint8_t buf[1024];
2939 int bufcnt;
2940 int bufptr;
2941 int max_size;
2942 } NetCharDriver;
2944 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2946 NetCharDriver *s = chr->opaque;
2948 return sendto(s->fd, buf, len, 0,
2949 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2952 static int udp_chr_read_poll(void *opaque)
2954 CharDriverState *chr = opaque;
2955 NetCharDriver *s = chr->opaque;
2957 s->max_size = qemu_chr_can_read(chr);
2959 /* If there were any stray characters in the queue process them
2960 * first
2962 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2963 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2964 s->bufptr++;
2965 s->max_size = qemu_chr_can_read(chr);
2967 return s->max_size;
2970 static void udp_chr_read(void *opaque)
2972 CharDriverState *chr = opaque;
2973 NetCharDriver *s = chr->opaque;
2975 if (s->max_size == 0)
2976 return;
2977 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2978 s->bufptr = s->bufcnt;
2979 if (s->bufcnt <= 0)
2980 return;
2982 s->bufptr = 0;
2983 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2984 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2985 s->bufptr++;
2986 s->max_size = qemu_chr_can_read(chr);
2990 static void udp_chr_update_read_handler(CharDriverState *chr)
2992 NetCharDriver *s = chr->opaque;
2994 if (s->fd >= 0) {
2995 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2996 udp_chr_read, NULL, chr);
3000 #ifndef _WIN32
3001 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3002 #endif
3003 int parse_host_src_port(struct sockaddr_in *haddr,
3004 struct sockaddr_in *saddr,
3005 const char *str);
3007 static CharDriverState *qemu_chr_open_udp(const char *def)
3009 CharDriverState *chr = NULL;
3010 NetCharDriver *s = NULL;
3011 int fd = -1;
3012 struct sockaddr_in saddr;
3014 chr = qemu_mallocz(sizeof(CharDriverState));
3015 if (!chr)
3016 goto return_err;
3017 s = qemu_mallocz(sizeof(NetCharDriver));
3018 if (!s)
3019 goto return_err;
3021 fd = socket(PF_INET, SOCK_DGRAM, 0);
3022 if (fd < 0) {
3023 perror("socket(PF_INET, SOCK_DGRAM)");
3024 goto return_err;
3027 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3028 printf("Could not parse: %s\n", def);
3029 goto return_err;
3032 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3034 perror("bind");
3035 goto return_err;
3038 s->fd = fd;
3039 s->bufcnt = 0;
3040 s->bufptr = 0;
3041 chr->opaque = s;
3042 chr->chr_write = udp_chr_write;
3043 chr->chr_update_read_handler = udp_chr_update_read_handler;
3044 return chr;
3046 return_err:
3047 if (chr)
3048 free(chr);
3049 if (s)
3050 free(s);
3051 if (fd >= 0)
3052 closesocket(fd);
3053 return NULL;
3056 /***********************************************************/
3057 /* TCP Net console */
3059 typedef struct {
3060 int fd, listen_fd;
3061 int connected;
3062 int max_size;
3063 int do_telnetopt;
3064 int do_nodelay;
3065 int is_unix;
3066 } TCPCharDriver;
3068 static void tcp_chr_accept(void *opaque);
3070 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3072 TCPCharDriver *s = chr->opaque;
3073 if (s->connected) {
3074 return send_all(s->fd, buf, len);
3075 } else {
3076 /* XXX: indicate an error ? */
3077 return len;
3081 static int tcp_chr_read_poll(void *opaque)
3083 CharDriverState *chr = opaque;
3084 TCPCharDriver *s = chr->opaque;
3085 if (!s->connected)
3086 return 0;
3087 s->max_size = qemu_chr_can_read(chr);
3088 return s->max_size;
3091 #define IAC 255
3092 #define IAC_BREAK 243
3093 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3094 TCPCharDriver *s,
3095 uint8_t *buf, int *size)
3097 /* Handle any telnet client's basic IAC options to satisfy char by
3098 * char mode with no echo. All IAC options will be removed from
3099 * the buf and the do_telnetopt variable will be used to track the
3100 * state of the width of the IAC information.
3102 * IAC commands come in sets of 3 bytes with the exception of the
3103 * "IAC BREAK" command and the double IAC.
3106 int i;
3107 int j = 0;
3109 for (i = 0; i < *size; i++) {
3110 if (s->do_telnetopt > 1) {
3111 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3112 /* Double IAC means send an IAC */
3113 if (j != i)
3114 buf[j] = buf[i];
3115 j++;
3116 s->do_telnetopt = 1;
3117 } else {
3118 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3119 /* Handle IAC break commands by sending a serial break */
3120 qemu_chr_event(chr, CHR_EVENT_BREAK);
3121 s->do_telnetopt++;
3123 s->do_telnetopt++;
3125 if (s->do_telnetopt >= 4) {
3126 s->do_telnetopt = 1;
3128 } else {
3129 if ((unsigned char)buf[i] == IAC) {
3130 s->do_telnetopt = 2;
3131 } else {
3132 if (j != i)
3133 buf[j] = buf[i];
3134 j++;
3138 *size = j;
3141 static void tcp_chr_read(void *opaque)
3143 CharDriverState *chr = opaque;
3144 TCPCharDriver *s = chr->opaque;
3145 uint8_t buf[1024];
3146 int len, size;
3148 if (!s->connected || s->max_size <= 0)
3149 return;
3150 len = sizeof(buf);
3151 if (len > s->max_size)
3152 len = s->max_size;
3153 size = recv(s->fd, buf, len, 0);
3154 if (size == 0) {
3155 /* connection closed */
3156 s->connected = 0;
3157 if (s->listen_fd >= 0) {
3158 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3160 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3161 closesocket(s->fd);
3162 s->fd = -1;
3163 } else if (size > 0) {
3164 if (s->do_telnetopt)
3165 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3166 if (size > 0)
3167 qemu_chr_read(chr, buf, size);
3171 static void tcp_chr_connect(void *opaque)
3173 CharDriverState *chr = opaque;
3174 TCPCharDriver *s = chr->opaque;
3176 s->connected = 1;
3177 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3178 tcp_chr_read, NULL, chr);
3179 qemu_chr_reset(chr);
3182 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3183 static void tcp_chr_telnet_init(int fd)
3185 char buf[3];
3186 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3187 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3188 send(fd, (char *)buf, 3, 0);
3189 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3190 send(fd, (char *)buf, 3, 0);
3191 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3192 send(fd, (char *)buf, 3, 0);
3193 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3194 send(fd, (char *)buf, 3, 0);
3197 static void socket_set_nodelay(int fd)
3199 int val = 1;
3200 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3203 static void tcp_chr_accept(void *opaque)
3205 CharDriverState *chr = opaque;
3206 TCPCharDriver *s = chr->opaque;
3207 struct sockaddr_in saddr;
3208 #ifndef _WIN32
3209 struct sockaddr_un uaddr;
3210 #endif
3211 struct sockaddr *addr;
3212 socklen_t len;
3213 int fd;
3215 for(;;) {
3216 #ifndef _WIN32
3217 if (s->is_unix) {
3218 len = sizeof(uaddr);
3219 addr = (struct sockaddr *)&uaddr;
3220 } else
3221 #endif
3223 len = sizeof(saddr);
3224 addr = (struct sockaddr *)&saddr;
3226 fd = accept(s->listen_fd, addr, &len);
3227 if (fd < 0 && errno != EINTR) {
3228 return;
3229 } else if (fd >= 0) {
3230 if (s->do_telnetopt)
3231 tcp_chr_telnet_init(fd);
3232 break;
3235 socket_set_nonblock(fd);
3236 if (s->do_nodelay)
3237 socket_set_nodelay(fd);
3238 s->fd = fd;
3239 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3240 tcp_chr_connect(chr);
3243 static void tcp_chr_close(CharDriverState *chr)
3245 TCPCharDriver *s = chr->opaque;
3246 if (s->fd >= 0)
3247 closesocket(s->fd);
3248 if (s->listen_fd >= 0)
3249 closesocket(s->listen_fd);
3250 qemu_free(s);
3253 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3254 int is_telnet,
3255 int is_unix)
3257 CharDriverState *chr = NULL;
3258 TCPCharDriver *s = NULL;
3259 int fd = -1, ret, err, val;
3260 int is_listen = 0;
3261 int is_waitconnect = 1;
3262 int do_nodelay = 0;
3263 const char *ptr;
3264 struct sockaddr_in saddr;
3265 #ifndef _WIN32
3266 struct sockaddr_un uaddr;
3267 #endif
3268 struct sockaddr *addr;
3269 socklen_t addrlen;
3271 #ifndef _WIN32
3272 if (is_unix) {
3273 addr = (struct sockaddr *)&uaddr;
3274 addrlen = sizeof(uaddr);
3275 if (parse_unix_path(&uaddr, host_str) < 0)
3276 goto fail;
3277 } else
3278 #endif
3280 addr = (struct sockaddr *)&saddr;
3281 addrlen = sizeof(saddr);
3282 if (parse_host_port(&saddr, host_str) < 0)
3283 goto fail;
3286 ptr = host_str;
3287 while((ptr = strchr(ptr,','))) {
3288 ptr++;
3289 if (!strncmp(ptr,"server",6)) {
3290 is_listen = 1;
3291 } else if (!strncmp(ptr,"nowait",6)) {
3292 is_waitconnect = 0;
3293 } else if (!strncmp(ptr,"nodelay",6)) {
3294 do_nodelay = 1;
3295 } else {
3296 printf("Unknown option: %s\n", ptr);
3297 goto fail;
3300 if (!is_listen)
3301 is_waitconnect = 0;
3303 chr = qemu_mallocz(sizeof(CharDriverState));
3304 if (!chr)
3305 goto fail;
3306 s = qemu_mallocz(sizeof(TCPCharDriver));
3307 if (!s)
3308 goto fail;
3310 #ifndef _WIN32
3311 if (is_unix)
3312 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3313 else
3314 #endif
3315 fd = socket(PF_INET, SOCK_STREAM, 0);
3317 if (fd < 0)
3318 goto fail;
3320 if (!is_waitconnect)
3321 socket_set_nonblock(fd);
3323 s->connected = 0;
3324 s->fd = -1;
3325 s->listen_fd = -1;
3326 s->is_unix = is_unix;
3327 s->do_nodelay = do_nodelay && !is_unix;
3329 chr->opaque = s;
3330 chr->chr_write = tcp_chr_write;
3331 chr->chr_close = tcp_chr_close;
3333 if (is_listen) {
3334 /* allow fast reuse */
3335 #ifndef _WIN32
3336 if (is_unix) {
3337 char path[109];
3338 strncpy(path, uaddr.sun_path, 108);
3339 path[108] = 0;
3340 unlink(path);
3341 } else
3342 #endif
3344 val = 1;
3345 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3348 ret = bind(fd, addr, addrlen);
3349 if (ret < 0)
3350 goto fail;
3352 ret = listen(fd, 0);
3353 if (ret < 0)
3354 goto fail;
3356 s->listen_fd = fd;
3357 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3358 if (is_telnet)
3359 s->do_telnetopt = 1;
3360 } else {
3361 for(;;) {
3362 ret = connect(fd, addr, addrlen);
3363 if (ret < 0) {
3364 err = socket_error();
3365 if (err == EINTR || err == EWOULDBLOCK) {
3366 } else if (err == EINPROGRESS) {
3367 break;
3368 #ifdef _WIN32
3369 } else if (err == WSAEALREADY) {
3370 break;
3371 #endif
3372 } else {
3373 goto fail;
3375 } else {
3376 s->connected = 1;
3377 break;
3380 s->fd = fd;
3381 socket_set_nodelay(fd);
3382 if (s->connected)
3383 tcp_chr_connect(chr);
3384 else
3385 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3388 if (is_listen && is_waitconnect) {
3389 printf("QEMU waiting for connection on: %s\n", host_str);
3390 tcp_chr_accept(chr);
3391 socket_set_nonblock(s->listen_fd);
3394 return chr;
3395 fail:
3396 if (fd >= 0)
3397 closesocket(fd);
3398 qemu_free(s);
3399 qemu_free(chr);
3400 return NULL;
3403 CharDriverState *qemu_chr_open(const char *filename)
3405 const char *p;
3407 if (!strcmp(filename, "vc")) {
3408 return text_console_init(&display_state, 0);
3409 } else if (strstart(filename, "vc:", &p)) {
3410 return text_console_init(&display_state, p);
3411 } else if (!strcmp(filename, "null")) {
3412 return qemu_chr_open_null();
3413 } else
3414 if (strstart(filename, "tcp:", &p)) {
3415 return qemu_chr_open_tcp(p, 0, 0);
3416 } else
3417 if (strstart(filename, "telnet:", &p)) {
3418 return qemu_chr_open_tcp(p, 1, 0);
3419 } else
3420 if (strstart(filename, "udp:", &p)) {
3421 return qemu_chr_open_udp(p);
3422 } else
3423 if (strstart(filename, "mon:", &p)) {
3424 CharDriverState *drv = qemu_chr_open(p);
3425 if (drv) {
3426 drv = qemu_chr_open_mux(drv);
3427 monitor_init(drv, !nographic);
3428 return drv;
3430 printf("Unable to open driver: %s\n", p);
3431 return 0;
3432 } else
3433 #ifndef _WIN32
3434 if (strstart(filename, "unix:", &p)) {
3435 return qemu_chr_open_tcp(p, 0, 1);
3436 } else if (strstart(filename, "file:", &p)) {
3437 return qemu_chr_open_file_out(p);
3438 } else if (strstart(filename, "pipe:", &p)) {
3439 return qemu_chr_open_pipe(p);
3440 } else if (!strcmp(filename, "pty")) {
3441 return qemu_chr_open_pty();
3442 } else if (!strcmp(filename, "stdio")) {
3443 return qemu_chr_open_stdio();
3444 } else
3445 #if defined(__linux__)
3446 if (strstart(filename, "/dev/parport", NULL)) {
3447 return qemu_chr_open_pp(filename);
3448 } else
3449 #endif
3450 #if defined(__linux__) || defined(__sun__)
3451 if (strstart(filename, "/dev/", NULL)) {
3452 return qemu_chr_open_tty(filename);
3453 } else
3454 #endif
3455 #else /* !_WIN32 */
3456 if (strstart(filename, "COM", NULL)) {
3457 return qemu_chr_open_win(filename);
3458 } else
3459 if (strstart(filename, "pipe:", &p)) {
3460 return qemu_chr_open_win_pipe(p);
3461 } else
3462 if (strstart(filename, "con:", NULL)) {
3463 return qemu_chr_open_win_con(filename);
3464 } else
3465 if (strstart(filename, "file:", &p)) {
3466 return qemu_chr_open_win_file_out(p);
3468 #endif
3470 return NULL;
3474 void qemu_chr_close(CharDriverState *chr)
3476 if (chr->chr_close)
3477 chr->chr_close(chr);
3478 qemu_free(chr);
3481 /***********************************************************/
3482 /* network device redirectors */
3484 __attribute__ (( unused ))
3485 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3487 int len, i, j, c;
3489 for(i=0;i<size;i+=16) {
3490 len = size - i;
3491 if (len > 16)
3492 len = 16;
3493 fprintf(f, "%08x ", i);
3494 for(j=0;j<16;j++) {
3495 if (j < len)
3496 fprintf(f, " %02x", buf[i+j]);
3497 else
3498 fprintf(f, " ");
3500 fprintf(f, " ");
3501 for(j=0;j<len;j++) {
3502 c = buf[i+j];
3503 if (c < ' ' || c > '~')
3504 c = '.';
3505 fprintf(f, "%c", c);
3507 fprintf(f, "\n");
3511 static int parse_macaddr(uint8_t *macaddr, const char *p)
3513 int i;
3514 char *last_char;
3515 long int offset;
3517 errno = 0;
3518 offset = strtol(p, &last_char, 0);
3519 if (0 == errno && '\0' == *last_char &&
3520 offset >= 0 && offset <= 0xFFFFFF) {
3521 macaddr[3] = (offset & 0xFF0000) >> 16;
3522 macaddr[4] = (offset & 0xFF00) >> 8;
3523 macaddr[5] = offset & 0xFF;
3524 return 0;
3525 } else {
3526 for(i = 0; i < 6; i++) {
3527 macaddr[i] = strtol(p, (char **)&p, 16);
3528 if (i == 5) {
3529 if (*p != '\0')
3530 return -1;
3531 } else {
3532 if (*p != ':' && *p != '-')
3533 return -1;
3534 p++;
3537 return 0;
3540 return -1;
3543 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3545 const char *p, *p1;
3546 int len;
3547 p = *pp;
3548 p1 = strchr(p, sep);
3549 if (!p1)
3550 return -1;
3551 len = p1 - p;
3552 p1++;
3553 if (buf_size > 0) {
3554 if (len > buf_size - 1)
3555 len = buf_size - 1;
3556 memcpy(buf, p, len);
3557 buf[len] = '\0';
3559 *pp = p1;
3560 return 0;
3563 int parse_host_src_port(struct sockaddr_in *haddr,
3564 struct sockaddr_in *saddr,
3565 const char *input_str)
3567 char *str = strdup(input_str);
3568 char *host_str = str;
3569 char *src_str;
3570 char *ptr;
3573 * Chop off any extra arguments at the end of the string which
3574 * would start with a comma, then fill in the src port information
3575 * if it was provided else use the "any address" and "any port".
3577 if ((ptr = strchr(str,',')))
3578 *ptr = '\0';
3580 if ((src_str = strchr(input_str,'@'))) {
3581 *src_str = '\0';
3582 src_str++;
3585 if (parse_host_port(haddr, host_str) < 0)
3586 goto fail;
3588 if (!src_str || *src_str == '\0')
3589 src_str = ":0";
3591 if (parse_host_port(saddr, src_str) < 0)
3592 goto fail;
3594 free(str);
3595 return(0);
3597 fail:
3598 free(str);
3599 return -1;
3602 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3604 char buf[512];
3605 struct hostent *he;
3606 const char *p, *r;
3607 int port;
3609 p = str;
3610 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3611 return -1;
3612 saddr->sin_family = AF_INET;
3613 if (buf[0] == '\0') {
3614 saddr->sin_addr.s_addr = 0;
3615 } else {
3616 if (isdigit(buf[0])) {
3617 if (!inet_aton(buf, &saddr->sin_addr))
3618 return -1;
3619 } else {
3620 if ((he = gethostbyname(buf)) == NULL)
3621 return - 1;
3622 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3625 port = strtol(p, (char **)&r, 0);
3626 if (r == p)
3627 return -1;
3628 saddr->sin_port = htons(port);
3629 return 0;
3632 #ifndef _WIN32
3633 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3635 const char *p;
3636 int len;
3638 len = MIN(108, strlen(str));
3639 p = strchr(str, ',');
3640 if (p)
3641 len = MIN(len, p - str);
3643 memset(uaddr, 0, sizeof(*uaddr));
3645 uaddr->sun_family = AF_UNIX;
3646 memcpy(uaddr->sun_path, str, len);
3648 return 0;
3650 #endif
3652 /* find or alloc a new VLAN */
3653 VLANState *qemu_find_vlan(int id)
3655 VLANState **pvlan, *vlan;
3656 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3657 if (vlan->id == id)
3658 return vlan;
3660 vlan = qemu_mallocz(sizeof(VLANState));
3661 if (!vlan)
3662 return NULL;
3663 vlan->id = id;
3664 vlan->next = NULL;
3665 pvlan = &first_vlan;
3666 while (*pvlan != NULL)
3667 pvlan = &(*pvlan)->next;
3668 *pvlan = vlan;
3669 return vlan;
3672 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3673 IOReadHandler *fd_read,
3674 IOCanRWHandler *fd_can_read,
3675 void *opaque)
3677 VLANClientState *vc, **pvc;
3678 vc = qemu_mallocz(sizeof(VLANClientState));
3679 if (!vc)
3680 return NULL;
3681 vc->fd_read = fd_read;
3682 vc->fd_can_read = fd_can_read;
3683 vc->opaque = opaque;
3684 vc->vlan = vlan;
3686 vc->next = NULL;
3687 pvc = &vlan->first_client;
3688 while (*pvc != NULL)
3689 pvc = &(*pvc)->next;
3690 *pvc = vc;
3691 return vc;
3694 int qemu_can_send_packet(VLANClientState *vc1)
3696 VLANState *vlan = vc1->vlan;
3697 VLANClientState *vc;
3699 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3700 if (vc != vc1) {
3701 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3702 return 1;
3705 return 0;
3708 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3710 VLANState *vlan = vc1->vlan;
3711 VLANClientState *vc;
3713 #if 0
3714 printf("vlan %d send:\n", vlan->id);
3715 hex_dump(stdout, buf, size);
3716 #endif
3717 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3718 if (vc != vc1) {
3719 vc->fd_read(vc->opaque, buf, size);
3724 #if defined(CONFIG_SLIRP)
3726 /* slirp network adapter */
3728 static int slirp_inited;
3729 static VLANClientState *slirp_vc;
3731 int slirp_can_output(void)
3733 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3736 void slirp_output(const uint8_t *pkt, int pkt_len)
3738 #if 0
3739 printf("slirp output:\n");
3740 hex_dump(stdout, pkt, pkt_len);
3741 #endif
3742 if (!slirp_vc)
3743 return;
3744 qemu_send_packet(slirp_vc, pkt, pkt_len);
3747 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3749 #if 0
3750 printf("slirp input:\n");
3751 hex_dump(stdout, buf, size);
3752 #endif
3753 slirp_input(buf, size);
3756 static int net_slirp_init(VLANState *vlan)
3758 if (!slirp_inited) {
3759 slirp_inited = 1;
3760 slirp_init();
3762 slirp_vc = qemu_new_vlan_client(vlan,
3763 slirp_receive, NULL, NULL);
3764 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3765 return 0;
3768 static void net_slirp_redir(const char *redir_str)
3770 int is_udp;
3771 char buf[256], *r;
3772 const char *p;
3773 struct in_addr guest_addr;
3774 int host_port, guest_port;
3776 if (!slirp_inited) {
3777 slirp_inited = 1;
3778 slirp_init();
3781 p = redir_str;
3782 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3783 goto fail;
3784 if (!strcmp(buf, "tcp")) {
3785 is_udp = 0;
3786 } else if (!strcmp(buf, "udp")) {
3787 is_udp = 1;
3788 } else {
3789 goto fail;
3792 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3793 goto fail;
3794 host_port = strtol(buf, &r, 0);
3795 if (r == buf)
3796 goto fail;
3798 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3799 goto fail;
3800 if (buf[0] == '\0') {
3801 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3803 if (!inet_aton(buf, &guest_addr))
3804 goto fail;
3806 guest_port = strtol(p, &r, 0);
3807 if (r == p)
3808 goto fail;
3810 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3811 fprintf(stderr, "qemu: could not set up redirection\n");
3812 exit(1);
3814 return;
3815 fail:
3816 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3817 exit(1);
3820 #ifndef _WIN32
3822 char smb_dir[1024];
3824 static void erase_dir(char *dir_name)
3826 DIR *d;
3827 struct dirent *de;
3828 char filename[1024];
3830 /* erase all the files in the directory */
3831 if ((d = opendir(dir_name)) != 0) {
3832 for(;;) {
3833 de = readdir(d);
3834 if (!de)
3835 break;
3836 if (strcmp(de->d_name, ".") != 0 &&
3837 strcmp(de->d_name, "..") != 0) {
3838 snprintf(filename, sizeof(filename), "%s/%s",
3839 smb_dir, de->d_name);
3840 if (unlink(filename) != 0) /* is it a directory? */
3841 erase_dir(filename);
3844 closedir(d);
3845 rmdir(dir_name);
3849 /* automatic user mode samba server configuration */
3850 static void smb_exit(void)
3852 erase_dir(smb_dir);
3855 /* automatic user mode samba server configuration */
3856 static void net_slirp_smb(const char *exported_dir)
3858 char smb_conf[1024];
3859 char smb_cmdline[1024];
3860 FILE *f;
3862 if (!slirp_inited) {
3863 slirp_inited = 1;
3864 slirp_init();
3867 /* XXX: better tmp dir construction */
3868 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3869 if (mkdir(smb_dir, 0700) < 0) {
3870 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3871 exit(1);
3873 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3875 f = fopen(smb_conf, "w");
3876 if (!f) {
3877 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3878 exit(1);
3880 fprintf(f,
3881 "[global]\n"
3882 "private dir=%s\n"
3883 "smb ports=0\n"
3884 "socket address=127.0.0.1\n"
3885 "pid directory=%s\n"
3886 "lock directory=%s\n"
3887 "log file=%s/log.smbd\n"
3888 "smb passwd file=%s/smbpasswd\n"
3889 "security = share\n"
3890 "[qemu]\n"
3891 "path=%s\n"
3892 "read only=no\n"
3893 "guest ok=yes\n",
3894 smb_dir,
3895 smb_dir,
3896 smb_dir,
3897 smb_dir,
3898 smb_dir,
3899 exported_dir
3901 fclose(f);
3902 atexit(smb_exit);
3904 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3905 SMBD_COMMAND, smb_conf);
3907 slirp_add_exec(0, smb_cmdline, 4, 139);
3910 #endif /* !defined(_WIN32) */
3911 void do_info_slirp(void)
3913 slirp_stats();
3916 #endif /* CONFIG_SLIRP */
3918 #if !defined(_WIN32)
3920 typedef struct TAPState {
3921 VLANClientState *vc;
3922 int fd;
3923 char down_script[1024];
3924 int no_poll;
3925 } TAPState;
3927 static int tap_read_poll(void *opaque)
3929 TAPState *s = opaque;
3930 return (!s->no_poll);
3933 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3935 TAPState *s = opaque;
3936 int ret;
3937 for(;;) {
3938 ret = write(s->fd, buf, size);
3939 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3940 } else {
3941 break;
3946 static void tap_send(void *opaque)
3948 TAPState *s = opaque;
3949 uint8_t buf[4096];
3950 int size;
3952 #ifdef __sun__
3953 struct strbuf sbuf;
3954 int f = 0;
3955 sbuf.maxlen = sizeof(buf);
3956 sbuf.buf = buf;
3957 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3958 #else
3959 size = read(s->fd, buf, sizeof(buf));
3960 #endif
3961 if (size > 0) {
3962 qemu_send_packet(s->vc, buf, size);
3966 int hack_around_tap(void *opaque)
3968 VLANClientState *vc = opaque;
3969 TAPState *ts = vc->opaque;
3971 if (vc->fd_read != tap_receive)
3972 return -1;
3974 if (ts) {
3975 ts->no_poll = 1;
3976 return ts->fd;
3979 return -1;
3982 /* fd support */
3984 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3986 TAPState *s;
3988 s = qemu_mallocz(sizeof(TAPState));
3989 if (!s)
3990 return NULL;
3991 s->fd = fd;
3992 s->no_poll = 0;
3993 enable_sigio_timer(fd);
3994 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3995 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
3996 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3997 return s;
4000 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4001 static int tap_open(char *ifname, int ifname_size)
4003 int fd;
4004 char *dev;
4005 struct stat s;
4007 TFR(fd = open("/dev/tap", O_RDWR));
4008 if (fd < 0) {
4009 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4010 return -1;
4013 fstat(fd, &s);
4014 dev = devname(s.st_rdev, S_IFCHR);
4015 pstrcpy(ifname, ifname_size, dev);
4017 fcntl(fd, F_SETFL, O_NONBLOCK);
4018 return fd;
4020 #elif defined(__sun__)
4021 #define TUNNEWPPA (('T'<<16) | 0x0001)
4023 * Allocate TAP device, returns opened fd.
4024 * Stores dev name in the first arg(must be large enough).
4026 int tap_alloc(char *dev)
4028 int tap_fd, if_fd, ppa = -1;
4029 static int ip_fd = 0;
4030 char *ptr;
4032 static int arp_fd = 0;
4033 int ip_muxid, arp_muxid;
4034 struct strioctl strioc_if, strioc_ppa;
4035 int link_type = I_PLINK;;
4036 struct lifreq ifr;
4037 char actual_name[32] = "";
4039 memset(&ifr, 0x0, sizeof(ifr));
4041 if( *dev ){
4042 ptr = dev;
4043 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4044 ppa = atoi(ptr);
4047 /* Check if IP device was opened */
4048 if( ip_fd )
4049 close(ip_fd);
4051 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4052 if (ip_fd < 0) {
4053 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4054 return -1;
4057 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4058 if (tap_fd < 0) {
4059 syslog(LOG_ERR, "Can't open /dev/tap");
4060 return -1;
4063 /* Assign a new PPA and get its unit number. */
4064 strioc_ppa.ic_cmd = TUNNEWPPA;
4065 strioc_ppa.ic_timout = 0;
4066 strioc_ppa.ic_len = sizeof(ppa);
4067 strioc_ppa.ic_dp = (char *)&ppa;
4068 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4069 syslog (LOG_ERR, "Can't assign new interface");
4071 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4072 if (if_fd < 0) {
4073 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4074 return -1;
4076 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4077 syslog(LOG_ERR, "Can't push IP module");
4078 return -1;
4081 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4082 syslog(LOG_ERR, "Can't get flags\n");
4084 snprintf (actual_name, 32, "tap%d", ppa);
4085 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4087 ifr.lifr_ppa = ppa;
4088 /* Assign ppa according to the unit number returned by tun device */
4090 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4091 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4092 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4093 syslog (LOG_ERR, "Can't get flags\n");
4094 /* Push arp module to if_fd */
4095 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4096 syslog (LOG_ERR, "Can't push ARP module (2)");
4098 /* Push arp module to ip_fd */
4099 if (ioctl (ip_fd, I_POP, NULL) < 0)
4100 syslog (LOG_ERR, "I_POP failed\n");
4101 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4102 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4103 /* Open arp_fd */
4104 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4105 if (arp_fd < 0)
4106 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4108 /* Set ifname to arp */
4109 strioc_if.ic_cmd = SIOCSLIFNAME;
4110 strioc_if.ic_timout = 0;
4111 strioc_if.ic_len = sizeof(ifr);
4112 strioc_if.ic_dp = (char *)&ifr;
4113 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4114 syslog (LOG_ERR, "Can't set ifname to arp\n");
4117 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4118 syslog(LOG_ERR, "Can't link TAP device to IP");
4119 return -1;
4122 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4123 syslog (LOG_ERR, "Can't link TAP device to ARP");
4125 close (if_fd);
4127 memset(&ifr, 0x0, sizeof(ifr));
4128 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4129 ifr.lifr_ip_muxid = ip_muxid;
4130 ifr.lifr_arp_muxid = arp_muxid;
4132 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4134 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4135 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4136 syslog (LOG_ERR, "Can't set multiplexor id");
4139 sprintf(dev, "tap%d", ppa);
4140 return tap_fd;
4143 static int tap_open(char *ifname, int ifname_size)
4145 char dev[10]="";
4146 int fd;
4147 if( (fd = tap_alloc(dev)) < 0 ){
4148 fprintf(stderr, "Cannot allocate TAP device\n");
4149 return -1;
4151 pstrcpy(ifname, ifname_size, dev);
4152 fcntl(fd, F_SETFL, O_NONBLOCK);
4153 return fd;
4155 #else
4156 static int tap_open(char *ifname, int ifname_size)
4158 struct ifreq ifr;
4159 int fd, ret;
4161 TFR(fd = open("/dev/net/tun", O_RDWR));
4162 if (fd < 0) {
4163 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4164 return -1;
4166 memset(&ifr, 0, sizeof(ifr));
4167 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4168 if (ifname[0] != '\0')
4169 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4170 else
4171 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4172 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4173 if (ret != 0) {
4174 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4175 close(fd);
4176 return -1;
4178 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4179 fcntl(fd, F_SETFL, O_NONBLOCK);
4180 return fd;
4182 #endif
4184 static int launch_script(const char *setup_script, const char *ifname, int fd)
4186 int pid, status;
4187 char *args[3];
4188 char **parg;
4190 /* try to launch network script */
4191 pid = fork();
4192 if (pid >= 0) {
4193 if (pid == 0) {
4194 int open_max = sysconf (_SC_OPEN_MAX), i;
4195 for (i = 0; i < open_max; i++)
4196 if (i != STDIN_FILENO &&
4197 i != STDOUT_FILENO &&
4198 i != STDERR_FILENO &&
4199 i != fd)
4200 close(i);
4202 parg = args;
4203 *parg++ = (char *)setup_script;
4204 *parg++ = (char *)ifname;
4205 *parg++ = NULL;
4206 execv(setup_script, args);
4207 _exit(1);
4209 while (waitpid(pid, &status, 0) != pid);
4210 if (!WIFEXITED(status) ||
4211 WEXITSTATUS(status) != 0) {
4212 fprintf(stderr, "%s: could not launch network script\n",
4213 setup_script);
4214 return -1;
4217 return 0;
4220 static int net_tap_init(VLANState *vlan, const char *ifname1,
4221 const char *setup_script, const char *down_script)
4223 TAPState *s;
4224 int fd;
4225 char ifname[128];
4227 if (ifname1 != NULL)
4228 pstrcpy(ifname, sizeof(ifname), ifname1);
4229 else
4230 ifname[0] = '\0';
4231 TFR(fd = tap_open(ifname, sizeof(ifname)));
4232 if (fd < 0)
4233 return -1;
4235 if (!setup_script || !strcmp(setup_script, "no"))
4236 setup_script = "";
4237 if (setup_script[0] != '\0') {
4238 if (launch_script(setup_script, ifname, fd))
4239 return -1;
4241 s = net_tap_fd_init(vlan, fd);
4242 if (!s)
4243 return -1;
4244 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4245 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4246 if (down_script && strcmp(down_script, "no"))
4247 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4248 return 0;
4251 #endif /* !_WIN32 */
4253 /* network connection */
4254 typedef struct NetSocketState {
4255 VLANClientState *vc;
4256 int fd;
4257 int state; /* 0 = getting length, 1 = getting data */
4258 int index;
4259 int packet_len;
4260 uint8_t buf[4096];
4261 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4262 } NetSocketState;
4264 typedef struct NetSocketListenState {
4265 VLANState *vlan;
4266 int fd;
4267 } NetSocketListenState;
4269 /* XXX: we consider we can send the whole packet without blocking */
4270 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4272 NetSocketState *s = opaque;
4273 uint32_t len;
4274 len = htonl(size);
4276 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4277 send_all(s->fd, buf, size);
4280 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4282 NetSocketState *s = opaque;
4283 sendto(s->fd, buf, size, 0,
4284 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4287 static void net_socket_send(void *opaque)
4289 NetSocketState *s = opaque;
4290 int l, size, err;
4291 uint8_t buf1[4096];
4292 const uint8_t *buf;
4294 size = recv(s->fd, buf1, sizeof(buf1), 0);
4295 if (size < 0) {
4296 err = socket_error();
4297 if (err != EWOULDBLOCK)
4298 goto eoc;
4299 } else if (size == 0) {
4300 /* end of connection */
4301 eoc:
4302 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4303 closesocket(s->fd);
4304 return;
4306 buf = buf1;
4307 while (size > 0) {
4308 /* reassemble a packet from the network */
4309 switch(s->state) {
4310 case 0:
4311 l = 4 - s->index;
4312 if (l > size)
4313 l = size;
4314 memcpy(s->buf + s->index, buf, l);
4315 buf += l;
4316 size -= l;
4317 s->index += l;
4318 if (s->index == 4) {
4319 /* got length */
4320 s->packet_len = ntohl(*(uint32_t *)s->buf);
4321 s->index = 0;
4322 s->state = 1;
4324 break;
4325 case 1:
4326 l = s->packet_len - s->index;
4327 if (l > size)
4328 l = size;
4329 memcpy(s->buf + s->index, buf, l);
4330 s->index += l;
4331 buf += l;
4332 size -= l;
4333 if (s->index >= s->packet_len) {
4334 qemu_send_packet(s->vc, s->buf, s->packet_len);
4335 s->index = 0;
4336 s->state = 0;
4338 break;
4343 static void net_socket_send_dgram(void *opaque)
4345 NetSocketState *s = opaque;
4346 int size;
4348 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4349 if (size < 0)
4350 return;
4351 if (size == 0) {
4352 /* end of connection */
4353 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4354 return;
4356 qemu_send_packet(s->vc, s->buf, size);
4359 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4361 struct ip_mreq imr;
4362 int fd;
4363 int val, ret;
4364 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4365 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4366 inet_ntoa(mcastaddr->sin_addr),
4367 (int)ntohl(mcastaddr->sin_addr.s_addr));
4368 return -1;
4371 fd = socket(PF_INET, SOCK_DGRAM, 0);
4372 if (fd < 0) {
4373 perror("socket(PF_INET, SOCK_DGRAM)");
4374 return -1;
4377 val = 1;
4378 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4379 (const char *)&val, sizeof(val));
4380 if (ret < 0) {
4381 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4382 goto fail;
4385 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4386 if (ret < 0) {
4387 perror("bind");
4388 goto fail;
4391 /* Add host to multicast group */
4392 imr.imr_multiaddr = mcastaddr->sin_addr;
4393 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4395 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4396 (const char *)&imr, sizeof(struct ip_mreq));
4397 if (ret < 0) {
4398 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4399 goto fail;
4402 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4403 val = 1;
4404 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4405 (const char *)&val, sizeof(val));
4406 if (ret < 0) {
4407 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4408 goto fail;
4411 socket_set_nonblock(fd);
4412 return fd;
4413 fail:
4414 if (fd >= 0)
4415 closesocket(fd);
4416 return -1;
4419 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4420 int is_connected)
4422 struct sockaddr_in saddr;
4423 int newfd;
4424 socklen_t saddr_len;
4425 NetSocketState *s;
4427 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4428 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4429 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4432 if (is_connected) {
4433 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4434 /* must be bound */
4435 if (saddr.sin_addr.s_addr==0) {
4436 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4437 fd);
4438 return NULL;
4440 /* clone dgram socket */
4441 newfd = net_socket_mcast_create(&saddr);
4442 if (newfd < 0) {
4443 /* error already reported by net_socket_mcast_create() */
4444 close(fd);
4445 return NULL;
4447 /* clone newfd to fd, close newfd */
4448 dup2(newfd, fd);
4449 close(newfd);
4451 } else {
4452 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4453 fd, strerror(errno));
4454 return NULL;
4458 s = qemu_mallocz(sizeof(NetSocketState));
4459 if (!s)
4460 return NULL;
4461 s->fd = fd;
4463 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4464 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4466 /* mcast: save bound address as dst */
4467 if (is_connected) s->dgram_dst=saddr;
4469 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4470 "socket: fd=%d (%s mcast=%s:%d)",
4471 fd, is_connected? "cloned" : "",
4472 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4473 return s;
4476 static void net_socket_connect(void *opaque)
4478 NetSocketState *s = opaque;
4479 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4482 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4483 int is_connected)
4485 NetSocketState *s;
4486 s = qemu_mallocz(sizeof(NetSocketState));
4487 if (!s)
4488 return NULL;
4489 s->fd = fd;
4490 s->vc = qemu_new_vlan_client(vlan,
4491 net_socket_receive, NULL, s);
4492 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4493 "socket: fd=%d", fd);
4494 if (is_connected) {
4495 net_socket_connect(s);
4496 } else {
4497 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4499 return s;
4502 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4503 int is_connected)
4505 int so_type=-1, optlen=sizeof(so_type);
4507 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4508 (socklen_t *)&optlen)< 0) {
4509 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4510 return NULL;
4512 switch(so_type) {
4513 case SOCK_DGRAM:
4514 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4515 case SOCK_STREAM:
4516 return net_socket_fd_init_stream(vlan, fd, is_connected);
4517 default:
4518 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4519 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4520 return net_socket_fd_init_stream(vlan, fd, is_connected);
4522 return NULL;
4525 static void net_socket_accept(void *opaque)
4527 NetSocketListenState *s = opaque;
4528 NetSocketState *s1;
4529 struct sockaddr_in saddr;
4530 socklen_t len;
4531 int fd;
4533 for(;;) {
4534 len = sizeof(saddr);
4535 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4536 if (fd < 0 && errno != EINTR) {
4537 return;
4538 } else if (fd >= 0) {
4539 break;
4542 s1 = net_socket_fd_init(s->vlan, fd, 1);
4543 if (!s1) {
4544 closesocket(fd);
4545 } else {
4546 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4547 "socket: connection from %s:%d",
4548 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4552 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4554 NetSocketListenState *s;
4555 int fd, val, ret;
4556 struct sockaddr_in saddr;
4558 if (parse_host_port(&saddr, host_str) < 0)
4559 return -1;
4561 s = qemu_mallocz(sizeof(NetSocketListenState));
4562 if (!s)
4563 return -1;
4565 fd = socket(PF_INET, SOCK_STREAM, 0);
4566 if (fd < 0) {
4567 perror("socket");
4568 return -1;
4570 socket_set_nonblock(fd);
4572 /* allow fast reuse */
4573 val = 1;
4574 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4576 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4577 if (ret < 0) {
4578 perror("bind");
4579 return -1;
4581 ret = listen(fd, 0);
4582 if (ret < 0) {
4583 perror("listen");
4584 return -1;
4586 s->vlan = vlan;
4587 s->fd = fd;
4588 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4589 return 0;
4592 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4594 NetSocketState *s;
4595 int fd, connected, ret, err;
4596 struct sockaddr_in saddr;
4598 if (parse_host_port(&saddr, host_str) < 0)
4599 return -1;
4601 fd = socket(PF_INET, SOCK_STREAM, 0);
4602 if (fd < 0) {
4603 perror("socket");
4604 return -1;
4606 socket_set_nonblock(fd);
4608 connected = 0;
4609 for(;;) {
4610 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4611 if (ret < 0) {
4612 err = socket_error();
4613 if (err == EINTR || err == EWOULDBLOCK) {
4614 } else if (err == EINPROGRESS) {
4615 break;
4616 #ifdef _WIN32
4617 } else if (err == WSAEALREADY) {
4618 break;
4619 #endif
4620 } else {
4621 perror("connect");
4622 closesocket(fd);
4623 return -1;
4625 } else {
4626 connected = 1;
4627 break;
4630 s = net_socket_fd_init(vlan, fd, connected);
4631 if (!s)
4632 return -1;
4633 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4634 "socket: connect to %s:%d",
4635 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4636 return 0;
4639 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4641 NetSocketState *s;
4642 int fd;
4643 struct sockaddr_in saddr;
4645 if (parse_host_port(&saddr, host_str) < 0)
4646 return -1;
4649 fd = net_socket_mcast_create(&saddr);
4650 if (fd < 0)
4651 return -1;
4653 s = net_socket_fd_init(vlan, fd, 0);
4654 if (!s)
4655 return -1;
4657 s->dgram_dst = saddr;
4659 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4660 "socket: mcast=%s:%d",
4661 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4662 return 0;
4666 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4668 char *q;
4670 q = buf;
4671 while (*p != '\0' && *p != '=') {
4672 if (q && (q - buf) < buf_size - 1)
4673 *q++ = *p;
4674 p++;
4676 if (q)
4677 *q = '\0';
4679 return p;
4682 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4684 char *q;
4686 q = buf;
4687 while (*p != '\0') {
4688 if (*p == ',') {
4689 if (*(p + 1) != ',')
4690 break;
4691 p++;
4693 if (q && (q - buf) < buf_size - 1)
4694 *q++ = *p;
4695 p++;
4697 if (q)
4698 *q = '\0';
4700 return p;
4703 static int get_param_value(char *buf, int buf_size,
4704 const char *tag, const char *str)
4706 const char *p;
4707 char option[128];
4709 p = str;
4710 for(;;) {
4711 p = get_opt_name(option, sizeof(option), p);
4712 if (*p != '=')
4713 break;
4714 p++;
4715 if (!strcmp(tag, option)) {
4716 (void)get_opt_value(buf, buf_size, p);
4717 return strlen(buf);
4718 } else {
4719 p = get_opt_value(NULL, 0, p);
4721 if (*p != ',')
4722 break;
4723 p++;
4725 return 0;
4728 static int check_params(char *buf, int buf_size,
4729 char **params, const char *str)
4731 const char *p;
4732 int i;
4734 p = str;
4735 for(;;) {
4736 p = get_opt_name(buf, buf_size, p);
4737 if (*p != '=')
4738 return -1;
4739 p++;
4740 for(i = 0; params[i] != NULL; i++)
4741 if (!strcmp(params[i], buf))
4742 break;
4743 if (params[i] == NULL)
4744 return -1;
4745 p = get_opt_value(NULL, 0, p);
4746 if (*p != ',')
4747 break;
4748 p++;
4750 return 0;
4754 static int net_client_init(const char *str)
4756 const char *p;
4757 char *q;
4758 char device[64];
4759 char buf[1024];
4760 int vlan_id, ret;
4761 VLANState *vlan;
4763 p = str;
4764 q = device;
4765 while (*p != '\0' && *p != ',') {
4766 if ((q - device) < sizeof(device) - 1)
4767 *q++ = *p;
4768 p++;
4770 *q = '\0';
4771 if (*p == ',')
4772 p++;
4773 vlan_id = 0;
4774 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4775 vlan_id = strtol(buf, NULL, 0);
4777 vlan = qemu_find_vlan(vlan_id);
4778 if (!vlan) {
4779 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4780 return -1;
4782 if (!strcmp(device, "nic")) {
4783 NICInfo *nd;
4784 uint8_t *macaddr;
4786 if (nb_nics >= MAX_NICS) {
4787 fprintf(stderr, "Too Many NICs\n");
4788 return -1;
4790 nd = &nd_table[nb_nics];
4791 macaddr = nd->macaddr;
4792 macaddr[0] = 0x52;
4793 macaddr[1] = 0x54;
4794 macaddr[2] = 0x00;
4795 macaddr[3] = 0x12;
4796 macaddr[4] = 0x34;
4797 macaddr[5] = 0x56 + nb_nics;
4799 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4800 if (parse_macaddr(macaddr, buf) < 0) {
4801 fprintf(stderr, "invalid syntax for ethernet address\n");
4802 return -1;
4805 if (get_param_value(buf, sizeof(buf), "model", p)) {
4806 nd->model = strdup(buf);
4808 nd->vlan = vlan;
4809 nb_nics++;
4810 vlan->nb_guest_devs++;
4811 ret = 0;
4812 } else
4813 if (!strcmp(device, "none")) {
4814 /* does nothing. It is needed to signal that no network cards
4815 are wanted */
4816 ret = 0;
4817 } else
4818 #ifdef CONFIG_SLIRP
4819 if (!strcmp(device, "user")) {
4820 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4821 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4823 vlan->nb_host_devs++;
4824 ret = net_slirp_init(vlan);
4825 } else
4826 #endif
4827 #ifdef _WIN32
4828 if (!strcmp(device, "tap")) {
4829 char ifname[64];
4830 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4831 fprintf(stderr, "tap: no interface name\n");
4832 return -1;
4834 vlan->nb_host_devs++;
4835 ret = tap_win32_init(vlan, ifname);
4836 } else
4837 #else
4838 if (!strcmp(device, "tap")) {
4839 char ifname[64];
4840 char setup_script[1024], down_script[1024];
4841 int fd;
4842 vlan->nb_host_devs++;
4843 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4844 fd = strtol(buf, NULL, 0);
4845 ret = -1;
4846 if (net_tap_fd_init(vlan, fd))
4847 ret = 0;
4848 } else {
4849 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4850 ifname[0] = '\0';
4852 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4853 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4855 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4856 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4858 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4860 } else
4861 #endif
4862 if (!strcmp(device, "socket")) {
4863 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4864 int fd;
4865 fd = strtol(buf, NULL, 0);
4866 ret = -1;
4867 if (net_socket_fd_init(vlan, fd, 1))
4868 ret = 0;
4869 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4870 ret = net_socket_listen_init(vlan, buf);
4871 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4872 ret = net_socket_connect_init(vlan, buf);
4873 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4874 ret = net_socket_mcast_init(vlan, buf);
4875 } else {
4876 fprintf(stderr, "Unknown socket options: %s\n", p);
4877 return -1;
4879 vlan->nb_host_devs++;
4880 } else
4882 fprintf(stderr, "Unknown network device: %s\n", device);
4883 return -1;
4885 if (ret < 0) {
4886 fprintf(stderr, "Could not initialize device '%s'\n", device);
4889 return ret;
4892 void do_info_network(void)
4894 VLANState *vlan;
4895 VLANClientState *vc;
4897 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4898 term_printf("VLAN %d devices:\n", vlan->id);
4899 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4900 term_printf(" %s\n", vc->info_str);
4904 #define HD_ALIAS "index=%d,media=disk"
4905 #ifdef TARGET_PPC
4906 #define CDROM_ALIAS "index=1,media=cdrom"
4907 #else
4908 #define CDROM_ALIAS "index=2,media=cdrom"
4909 #endif
4910 #define FD_ALIAS "index=%d,if=floppy"
4911 #define PFLASH_ALIAS "if=pflash"
4912 #define MTD_ALIAS "if=mtd"
4913 #define SD_ALIAS "index=0,if=sd"
4915 static int drive_add(const char *file, const char *fmt, ...)
4917 va_list ap;
4919 if (nb_drives_opt >= MAX_DRIVES) {
4920 fprintf(stderr, "qemu: too many drives\n");
4921 exit(1);
4924 drives_opt[nb_drives_opt].file = file;
4925 va_start(ap, fmt);
4926 vsnprintf(drives_opt[nb_drives_opt].opt,
4927 sizeof(drives_opt[0].opt), fmt, ap);
4928 va_end(ap);
4930 return nb_drives_opt++;
4933 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4935 int index;
4937 /* seek interface, bus and unit */
4939 for (index = 0; index < nb_drives; index++)
4940 if (drives_table[index].type == type &&
4941 drives_table[index].bus == bus &&
4942 drives_table[index].unit == unit)
4943 return index;
4945 return -1;
4948 int drive_get_max_bus(BlockInterfaceType type)
4950 int max_bus;
4951 int index;
4953 max_bus = -1;
4954 for (index = 0; index < nb_drives; index++) {
4955 if(drives_table[index].type == type &&
4956 drives_table[index].bus > max_bus)
4957 max_bus = drives_table[index].bus;
4959 return max_bus;
4962 static int drive_init(struct drive_opt *arg, int snapshot,
4963 QEMUMachine *machine)
4965 char buf[128];
4966 char file[1024];
4967 char devname[128];
4968 const char *mediastr = "";
4969 BlockInterfaceType type;
4970 enum { MEDIA_DISK, MEDIA_CDROM } media;
4971 int bus_id, unit_id;
4972 int cyls, heads, secs, translation;
4973 BlockDriverState *bdrv;
4974 int max_devs;
4975 int index;
4976 int cache;
4977 int bdrv_flags;
4978 char *str = arg->opt;
4979 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4980 "secs", "trans", "media", "snapshot", "file",
4981 "cache", "boot", NULL };
4983 if (check_params(buf, sizeof(buf), params, str) < 0) {
4984 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4985 buf, str);
4986 return -1;
4989 file[0] = 0;
4990 cyls = heads = secs = 0;
4991 bus_id = 0;
4992 unit_id = -1;
4993 translation = BIOS_ATA_TRANSLATION_AUTO;
4994 index = -1;
4995 cache = 1;
4997 if (!strcmp(machine->name, "realview") ||
4998 !strcmp(machine->name, "SS-5") ||
4999 !strcmp(machine->name, "SS-10") ||
5000 !strcmp(machine->name, "SS-600MP") ||
5001 !strcmp(machine->name, "versatilepb") ||
5002 !strcmp(machine->name, "versatileab")) {
5003 type = IF_SCSI;
5004 max_devs = MAX_SCSI_DEVS;
5005 strcpy(devname, "scsi");
5006 } else {
5007 type = IF_IDE;
5008 max_devs = MAX_IDE_DEVS;
5009 strcpy(devname, "ide");
5011 media = MEDIA_DISK;
5013 /* extract parameters */
5015 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5016 bus_id = strtol(buf, NULL, 0);
5017 if (bus_id < 0) {
5018 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5019 return -1;
5023 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5024 unit_id = strtol(buf, NULL, 0);
5025 if (unit_id < 0) {
5026 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5027 return -1;
5031 if (get_param_value(buf, sizeof(buf), "if", str)) {
5032 strncpy(devname, buf, sizeof(devname));
5033 if (!strcmp(buf, "ide")) {
5034 type = IF_IDE;
5035 max_devs = MAX_IDE_DEVS;
5036 } else if (!strcmp(buf, "scsi")) {
5037 type = IF_SCSI;
5038 max_devs = MAX_SCSI_DEVS;
5039 } else if (!strcmp(buf, "floppy")) {
5040 type = IF_FLOPPY;
5041 max_devs = 0;
5042 } else if (!strcmp(buf, "pflash")) {
5043 type = IF_PFLASH;
5044 max_devs = 0;
5045 } else if (!strcmp(buf, "mtd")) {
5046 type = IF_MTD;
5047 max_devs = 0;
5048 } else if (!strcmp(buf, "sd")) {
5049 type = IF_SD;
5050 max_devs = 0;
5051 } else if (!strcmp(buf, "virtio")) {
5052 type = IF_VIRTIO;
5053 max_devs = 0;
5054 } else {
5055 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5056 return -1;
5060 if (get_param_value(buf, sizeof(buf), "index", str)) {
5061 index = strtol(buf, NULL, 0);
5062 if (index < 0) {
5063 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5064 return -1;
5068 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5069 cyls = strtol(buf, NULL, 0);
5072 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5073 heads = strtol(buf, NULL, 0);
5076 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5077 secs = strtol(buf, NULL, 0);
5080 if (cyls || heads || secs) {
5081 if (cyls < 1 || cyls > 16383) {
5082 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5083 return -1;
5085 if (heads < 1 || heads > 16) {
5086 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5087 return -1;
5089 if (secs < 1 || secs > 63) {
5090 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5091 return -1;
5095 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5096 if (!cyls) {
5097 fprintf(stderr,
5098 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5099 str);
5100 return -1;
5102 if (!strcmp(buf, "none"))
5103 translation = BIOS_ATA_TRANSLATION_NONE;
5104 else if (!strcmp(buf, "lba"))
5105 translation = BIOS_ATA_TRANSLATION_LBA;
5106 else if (!strcmp(buf, "auto"))
5107 translation = BIOS_ATA_TRANSLATION_AUTO;
5108 else {
5109 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5110 return -1;
5114 if (get_param_value(buf, sizeof(buf), "media", str)) {
5115 if (!strcmp(buf, "disk")) {
5116 media = MEDIA_DISK;
5117 } else if (!strcmp(buf, "cdrom")) {
5118 if (cyls || secs || heads) {
5119 fprintf(stderr,
5120 "qemu: '%s' invalid physical CHS format\n", str);
5121 return -1;
5123 media = MEDIA_CDROM;
5124 } else {
5125 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5126 return -1;
5130 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5131 if (!strcmp(buf, "on"))
5132 snapshot = 1;
5133 else if (!strcmp(buf, "off"))
5134 snapshot = 0;
5135 else {
5136 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5137 return -1;
5141 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5142 if (!strcmp(buf, "off"))
5143 cache = 0;
5144 else if (!strcmp(buf, "on"))
5145 cache = 1;
5146 else {
5147 fprintf(stderr, "qemu: invalid cache option\n");
5148 return -1;
5152 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5153 if (!strcmp(buf, "on")) {
5154 if (extboot_drive != -1) {
5155 fprintf(stderr, "qemu: two bootable drives specified\n");
5156 return -1;
5158 extboot_drive = nb_drives;
5159 } else if (strcmp(buf, "off")) {
5160 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5161 return -1;
5165 if (arg->file == NULL)
5166 get_param_value(file, sizeof(file), "file", str);
5167 else
5168 pstrcpy(file, sizeof(file), arg->file);
5170 /* compute bus and unit according index */
5172 if (index != -1) {
5173 if (bus_id != 0 || unit_id != -1) {
5174 fprintf(stderr,
5175 "qemu: '%s' index cannot be used with bus and unit\n", str);
5176 return -1;
5178 if (max_devs == 0)
5180 unit_id = index;
5181 bus_id = 0;
5182 } else {
5183 unit_id = index % max_devs;
5184 bus_id = index / max_devs;
5188 /* if user doesn't specify a unit_id,
5189 * try to find the first free
5192 if (unit_id == -1) {
5193 unit_id = 0;
5194 while (drive_get_index(type, bus_id, unit_id) != -1) {
5195 unit_id++;
5196 if (max_devs && unit_id >= max_devs) {
5197 unit_id -= max_devs;
5198 bus_id++;
5203 /* check unit id */
5205 if (max_devs && unit_id >= max_devs) {
5206 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5207 str, unit_id, max_devs - 1);
5208 return -1;
5212 * ignore multiple definitions
5215 if (drive_get_index(type, bus_id, unit_id) != -1)
5216 return 0;
5218 /* init */
5220 if (type == IF_IDE || type == IF_SCSI)
5221 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5222 if (max_devs)
5223 snprintf(buf, sizeof(buf), "%s%i%s%i",
5224 devname, bus_id, mediastr, unit_id);
5225 else
5226 snprintf(buf, sizeof(buf), "%s%s%i",
5227 devname, mediastr, unit_id);
5228 bdrv = bdrv_new(buf);
5229 drives_table[nb_drives].bdrv = bdrv;
5230 drives_table[nb_drives].type = type;
5231 drives_table[nb_drives].bus = bus_id;
5232 drives_table[nb_drives].unit = unit_id;
5233 nb_drives++;
5235 switch(type) {
5236 case IF_IDE:
5237 case IF_SCSI:
5238 switch(media) {
5239 case MEDIA_DISK:
5240 if (cyls != 0) {
5241 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5242 bdrv_set_translation_hint(bdrv, translation);
5244 break;
5245 case MEDIA_CDROM:
5246 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5247 break;
5249 break;
5250 case IF_SD:
5251 /* FIXME: This isn't really a floppy, but it's a reasonable
5252 approximation. */
5253 case IF_FLOPPY:
5254 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5255 break;
5256 case IF_PFLASH:
5257 case IF_MTD:
5258 case IF_VIRTIO:
5259 break;
5261 if (!file[0])
5262 return 0;
5263 bdrv_flags = 0;
5264 if (snapshot)
5265 bdrv_flags |= BDRV_O_SNAPSHOT;
5266 if (!cache)
5267 bdrv_flags |= BDRV_O_DIRECT;
5268 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5269 fprintf(stderr, "qemu: could not open disk image %s\n",
5270 file);
5271 return -1;
5273 return 0;
5276 /***********************************************************/
5277 /* USB devices */
5279 static USBPort *used_usb_ports;
5280 static USBPort *free_usb_ports;
5282 /* ??? Maybe change this to register a hub to keep track of the topology. */
5283 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5284 usb_attachfn attach)
5286 port->opaque = opaque;
5287 port->index = index;
5288 port->attach = attach;
5289 port->next = free_usb_ports;
5290 free_usb_ports = port;
5293 static int usb_device_add(const char *devname)
5295 const char *p;
5296 USBDevice *dev;
5297 USBPort *port;
5299 if (!free_usb_ports)
5300 return -1;
5302 if (strstart(devname, "host:", &p)) {
5303 dev = usb_host_device_open(p);
5304 } else if (!strcmp(devname, "mouse")) {
5305 dev = usb_mouse_init();
5306 } else if (!strcmp(devname, "tablet")) {
5307 dev = usb_tablet_init();
5308 } else if (!strcmp(devname, "keyboard")) {
5309 dev = usb_keyboard_init();
5310 } else if (strstart(devname, "disk:", &p)) {
5311 dev = usb_msd_init(p);
5312 } else if (!strcmp(devname, "wacom-tablet")) {
5313 dev = usb_wacom_init();
5314 } else if (strstart(devname, "serial:", &p)) {
5315 dev = usb_serial_init(p);
5316 } else {
5317 return -1;
5319 if (!dev)
5320 return -1;
5322 /* Find a USB port to add the device to. */
5323 port = free_usb_ports;
5324 if (!port->next) {
5325 USBDevice *hub;
5327 /* Create a new hub and chain it on. */
5328 free_usb_ports = NULL;
5329 port->next = used_usb_ports;
5330 used_usb_ports = port;
5332 hub = usb_hub_init(VM_USB_HUB_SIZE);
5333 usb_attach(port, hub);
5334 port = free_usb_ports;
5337 free_usb_ports = port->next;
5338 port->next = used_usb_ports;
5339 used_usb_ports = port;
5340 usb_attach(port, dev);
5341 return 0;
5344 static int usb_device_del(const char *devname)
5346 USBPort *port;
5347 USBPort **lastp;
5348 USBDevice *dev;
5349 int bus_num, addr;
5350 const char *p;
5352 if (!used_usb_ports)
5353 return -1;
5355 p = strchr(devname, '.');
5356 if (!p)
5357 return -1;
5358 bus_num = strtoul(devname, NULL, 0);
5359 addr = strtoul(p + 1, NULL, 0);
5360 if (bus_num != 0)
5361 return -1;
5363 lastp = &used_usb_ports;
5364 port = used_usb_ports;
5365 while (port && port->dev->addr != addr) {
5366 lastp = &port->next;
5367 port = port->next;
5370 if (!port)
5371 return -1;
5373 dev = port->dev;
5374 *lastp = port->next;
5375 usb_attach(port, NULL);
5376 dev->handle_destroy(dev);
5377 port->next = free_usb_ports;
5378 free_usb_ports = port;
5379 return 0;
5382 void do_usb_add(const char *devname)
5384 int ret;
5385 ret = usb_device_add(devname);
5386 if (ret < 0)
5387 term_printf("Could not add USB device '%s'\n", devname);
5390 void do_usb_del(const char *devname)
5392 int ret;
5393 ret = usb_device_del(devname);
5394 if (ret < 0)
5395 term_printf("Could not remove USB device '%s'\n", devname);
5398 void usb_info(void)
5400 USBDevice *dev;
5401 USBPort *port;
5402 const char *speed_str;
5404 if (!usb_enabled) {
5405 term_printf("USB support not enabled\n");
5406 return;
5409 for (port = used_usb_ports; port; port = port->next) {
5410 dev = port->dev;
5411 if (!dev)
5412 continue;
5413 switch(dev->speed) {
5414 case USB_SPEED_LOW:
5415 speed_str = "1.5";
5416 break;
5417 case USB_SPEED_FULL:
5418 speed_str = "12";
5419 break;
5420 case USB_SPEED_HIGH:
5421 speed_str = "480";
5422 break;
5423 default:
5424 speed_str = "?";
5425 break;
5427 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5428 0, dev->addr, speed_str, dev->devname);
5432 /***********************************************************/
5433 /* PCMCIA/Cardbus */
5435 static struct pcmcia_socket_entry_s {
5436 struct pcmcia_socket_s *socket;
5437 struct pcmcia_socket_entry_s *next;
5438 } *pcmcia_sockets = 0;
5440 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5442 struct pcmcia_socket_entry_s *entry;
5444 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5445 entry->socket = socket;
5446 entry->next = pcmcia_sockets;
5447 pcmcia_sockets = entry;
5450 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5452 struct pcmcia_socket_entry_s *entry, **ptr;
5454 ptr = &pcmcia_sockets;
5455 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5456 if (entry->socket == socket) {
5457 *ptr = entry->next;
5458 qemu_free(entry);
5462 void pcmcia_info(void)
5464 struct pcmcia_socket_entry_s *iter;
5465 if (!pcmcia_sockets)
5466 term_printf("No PCMCIA sockets\n");
5468 for (iter = pcmcia_sockets; iter; iter = iter->next)
5469 term_printf("%s: %s\n", iter->socket->slot_string,
5470 iter->socket->attached ? iter->socket->card_string :
5471 "Empty");
5474 /***********************************************************/
5475 /* dumb display */
5477 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5481 static void dumb_resize(DisplayState *ds, int w, int h)
5485 static void dumb_refresh(DisplayState *ds)
5487 #if defined(CONFIG_SDL)
5488 vga_hw_update();
5489 #endif
5492 static void dumb_display_init(DisplayState *ds)
5494 ds->data = NULL;
5495 ds->linesize = 0;
5496 ds->depth = 0;
5497 ds->dpy_update = dumb_update;
5498 ds->dpy_resize = dumb_resize;
5499 ds->dpy_refresh = dumb_refresh;
5502 /***********************************************************/
5503 /* I/O handling */
5505 #define MAX_IO_HANDLERS 64
5507 typedef struct IOHandlerRecord {
5508 int fd;
5509 IOCanRWHandler *fd_read_poll;
5510 IOHandler *fd_read;
5511 IOHandler *fd_write;
5512 int deleted;
5513 void *opaque;
5514 /* temporary data */
5515 struct pollfd *ufd;
5516 struct IOHandlerRecord *next;
5517 } IOHandlerRecord;
5519 static IOHandlerRecord *first_io_handler;
5521 /* XXX: fd_read_poll should be suppressed, but an API change is
5522 necessary in the character devices to suppress fd_can_read(). */
5523 int qemu_set_fd_handler2(int fd,
5524 IOCanRWHandler *fd_read_poll,
5525 IOHandler *fd_read,
5526 IOHandler *fd_write,
5527 void *opaque)
5529 IOHandlerRecord **pioh, *ioh;
5531 if (!fd_read && !fd_write) {
5532 pioh = &first_io_handler;
5533 for(;;) {
5534 ioh = *pioh;
5535 if (ioh == NULL)
5536 break;
5537 if (ioh->fd == fd) {
5538 ioh->deleted = 1;
5539 break;
5541 pioh = &ioh->next;
5543 } else {
5544 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5545 if (ioh->fd == fd)
5546 goto found;
5548 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5549 if (!ioh)
5550 return -1;
5551 ioh->next = first_io_handler;
5552 first_io_handler = ioh;
5553 found:
5554 ioh->fd = fd;
5555 ioh->fd_read_poll = fd_read_poll;
5556 ioh->fd_read = fd_read;
5557 ioh->fd_write = fd_write;
5558 ioh->opaque = opaque;
5559 ioh->deleted = 0;
5561 return 0;
5564 int qemu_set_fd_handler(int fd,
5565 IOHandler *fd_read,
5566 IOHandler *fd_write,
5567 void *opaque)
5569 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5572 /***********************************************************/
5573 /* Polling handling */
5575 typedef struct PollingEntry {
5576 PollingFunc *func;
5577 void *opaque;
5578 struct PollingEntry *next;
5579 } PollingEntry;
5581 static PollingEntry *first_polling_entry;
5583 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5585 PollingEntry **ppe, *pe;
5586 pe = qemu_mallocz(sizeof(PollingEntry));
5587 if (!pe)
5588 return -1;
5589 pe->func = func;
5590 pe->opaque = opaque;
5591 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5592 *ppe = pe;
5593 return 0;
5596 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5598 PollingEntry **ppe, *pe;
5599 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5600 pe = *ppe;
5601 if (pe->func == func && pe->opaque == opaque) {
5602 *ppe = pe->next;
5603 qemu_free(pe);
5604 break;
5609 #ifdef _WIN32
5610 /***********************************************************/
5611 /* Wait objects support */
5612 typedef struct WaitObjects {
5613 int num;
5614 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5615 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5616 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5617 } WaitObjects;
5619 static WaitObjects wait_objects = {0};
5621 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5623 WaitObjects *w = &wait_objects;
5625 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5626 return -1;
5627 w->events[w->num] = handle;
5628 w->func[w->num] = func;
5629 w->opaque[w->num] = opaque;
5630 w->num++;
5631 return 0;
5634 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5636 int i, found;
5637 WaitObjects *w = &wait_objects;
5639 found = 0;
5640 for (i = 0; i < w->num; i++) {
5641 if (w->events[i] == handle)
5642 found = 1;
5643 if (found) {
5644 w->events[i] = w->events[i + 1];
5645 w->func[i] = w->func[i + 1];
5646 w->opaque[i] = w->opaque[i + 1];
5649 if (found)
5650 w->num--;
5652 #endif
5654 #define SELF_ANNOUNCE_ROUNDS 5
5655 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5656 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5657 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5659 static int announce_self_create(uint8_t *buf,
5660 uint8_t *mac_addr)
5662 uint32_t magic = EXPERIMENTAL_MAGIC;
5663 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5665 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5667 memset(buf, 0xff, 6); /* h_dst */
5668 memcpy(buf + 6, mac_addr, 6); /* h_src */
5669 memcpy(buf + 12, &proto, 2); /* h_proto */
5670 memcpy(buf + 14, &magic, 4); /* magic */
5672 return 18; /* len */
5675 static void qemu_announce_self(void)
5677 int i, j, len;
5678 VLANState *vlan;
5679 VLANClientState *vc;
5680 uint8_t buf[256];
5682 for (i = 0; i < nb_nics; i++) {
5683 len = announce_self_create(buf, nd_table[i].macaddr);
5684 vlan = nd_table[i].vlan;
5685 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5686 if (vc->fd_read == tap_receive) /* send only if tap */
5687 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5688 vc->fd_read(vc->opaque, buf, len);
5693 /***********************************************************/
5694 /* savevm/loadvm support */
5696 #define IO_BUF_SIZE 32768
5698 struct QEMUFile {
5699 QEMUFilePutBufferFunc *put_buffer;
5700 QEMUFileGetBufferFunc *get_buffer;
5701 QEMUFileCloseFunc *close;
5702 void *opaque;
5704 int64_t buf_offset; /* start of buffer when writing, end of buffer
5705 when reading */
5706 int buf_index;
5707 int buf_size; /* 0 when writing */
5708 uint8_t buf[IO_BUF_SIZE];
5711 typedef struct QEMUFileFD
5713 int fd;
5714 } QEMUFileFD;
5716 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5718 QEMUFileFD *s = opaque;
5719 int offset = 0;
5720 ssize_t len;
5722 again:
5723 len = read(s->fd, buf + offset, size - offset);
5724 if (len == -1) {
5725 if (errno == EINTR || errno == EAGAIN)
5726 goto again;
5729 return len;
5732 QEMUFile *qemu_fopen_fd(int fd)
5734 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5735 s->fd = fd;
5736 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5739 typedef struct QEMUFileUnix
5741 FILE *outfile;
5742 } QEMUFileUnix;
5744 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5746 QEMUFileUnix *s = opaque;
5747 fseek(s->outfile, pos, SEEK_SET);
5748 fwrite(buf, 1, size, s->outfile);
5751 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5753 QEMUFileUnix *s = opaque;
5754 fseek(s->outfile, pos, SEEK_SET);
5755 return fread(buf, 1, size, s->outfile);
5758 static void file_close(void *opaque)
5760 QEMUFileUnix *s = opaque;
5761 fclose(s->outfile);
5762 qemu_free(s);
5765 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5767 QEMUFileUnix *s;
5769 s = qemu_mallocz(sizeof(QEMUFileUnix));
5770 if (!s)
5771 return NULL;
5773 s->outfile = fopen(filename, mode);
5774 if (!s->outfile)
5775 goto fail;
5777 if (!strcmp(mode, "wb"))
5778 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5779 else if (!strcmp(mode, "rb"))
5780 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5782 fail:
5783 if (s->outfile)
5784 fclose(s->outfile);
5785 qemu_free(s);
5786 return NULL;
5789 typedef struct QEMUFileBdrv
5791 BlockDriverState *bs;
5792 int64_t base_offset;
5793 } QEMUFileBdrv;
5795 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5797 QEMUFileBdrv *s = opaque;
5798 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5801 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5803 QEMUFileBdrv *s = opaque;
5804 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5807 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5809 QEMUFileBdrv *s;
5811 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5812 if (!s)
5813 return NULL;
5815 s->bs = bs;
5816 s->base_offset = offset;
5818 if (is_writable)
5819 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5821 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5824 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5825 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5827 QEMUFile *f;
5829 f = qemu_mallocz(sizeof(QEMUFile));
5830 if (!f)
5831 return NULL;
5833 f->opaque = opaque;
5834 f->put_buffer = put_buffer;
5835 f->get_buffer = get_buffer;
5836 f->close = close;
5838 return f;
5841 void qemu_fflush(QEMUFile *f)
5843 if (!f->put_buffer)
5844 return;
5846 if (f->buf_index > 0) {
5847 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5848 f->buf_offset += f->buf_index;
5849 f->buf_index = 0;
5853 static void qemu_fill_buffer(QEMUFile *f)
5855 int len;
5857 if (!f->get_buffer)
5858 return;
5860 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5861 if (len < 0)
5862 len = 0;
5864 f->buf_index = 0;
5865 f->buf_size = len;
5866 f->buf_offset += len;
5869 void qemu_fclose(QEMUFile *f)
5871 qemu_fflush(f);
5872 if (f->close)
5873 f->close(f->opaque);
5874 qemu_free(f);
5877 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5879 int l;
5880 while (size > 0) {
5881 l = IO_BUF_SIZE - f->buf_index;
5882 if (l > size)
5883 l = size;
5884 memcpy(f->buf + f->buf_index, buf, l);
5885 f->buf_index += l;
5886 buf += l;
5887 size -= l;
5888 if (f->buf_index >= IO_BUF_SIZE)
5889 qemu_fflush(f);
5893 void qemu_put_byte(QEMUFile *f, int v)
5895 f->buf[f->buf_index++] = v;
5896 if (f->buf_index >= IO_BUF_SIZE)
5897 qemu_fflush(f);
5900 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5902 int size, l;
5904 size = size1;
5905 while (size > 0) {
5906 l = f->buf_size - f->buf_index;
5907 if (l == 0) {
5908 qemu_fill_buffer(f);
5909 l = f->buf_size - f->buf_index;
5910 if (l == 0)
5911 break;
5913 if (l > size)
5914 l = size;
5915 memcpy(buf, f->buf + f->buf_index, l);
5916 f->buf_index += l;
5917 buf += l;
5918 size -= l;
5920 return size1 - size;
5923 int qemu_get_byte(QEMUFile *f)
5925 if (f->buf_index >= f->buf_size) {
5926 qemu_fill_buffer(f);
5927 if (f->buf_index >= f->buf_size)
5928 return 0;
5930 return f->buf[f->buf_index++];
5933 int64_t qemu_ftell(QEMUFile *f)
5935 return f->buf_offset - f->buf_size + f->buf_index;
5938 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5940 if (whence == SEEK_SET) {
5941 /* nothing to do */
5942 } else if (whence == SEEK_CUR) {
5943 pos += qemu_ftell(f);
5944 } else {
5945 /* SEEK_END not supported */
5946 return -1;
5948 if (f->put_buffer) {
5949 qemu_fflush(f);
5950 f->buf_offset = pos;
5951 } else {
5952 f->buf_offset = pos;
5953 f->buf_index = 0;
5954 f->buf_size = 0;
5956 return pos;
5959 void qemu_put_be16(QEMUFile *f, unsigned int v)
5961 qemu_put_byte(f, v >> 8);
5962 qemu_put_byte(f, v);
5965 void qemu_put_be32(QEMUFile *f, unsigned int v)
5967 qemu_put_byte(f, v >> 24);
5968 qemu_put_byte(f, v >> 16);
5969 qemu_put_byte(f, v >> 8);
5970 qemu_put_byte(f, v);
5973 void qemu_put_be64(QEMUFile *f, uint64_t v)
5975 qemu_put_be32(f, v >> 32);
5976 qemu_put_be32(f, v);
5979 unsigned int qemu_get_be16(QEMUFile *f)
5981 unsigned int v;
5982 v = qemu_get_byte(f) << 8;
5983 v |= qemu_get_byte(f);
5984 return v;
5987 unsigned int qemu_get_be32(QEMUFile *f)
5989 unsigned int v;
5990 v = qemu_get_byte(f) << 24;
5991 v |= qemu_get_byte(f) << 16;
5992 v |= qemu_get_byte(f) << 8;
5993 v |= qemu_get_byte(f);
5994 return v;
5997 uint64_t qemu_get_be64(QEMUFile *f)
5999 uint64_t v;
6000 v = (uint64_t)qemu_get_be32(f) << 32;
6001 v |= qemu_get_be32(f);
6002 return v;
6005 typedef struct SaveStateEntry {
6006 char idstr[256];
6007 int instance_id;
6008 int version_id;
6009 SaveStateHandler *save_state;
6010 LoadStateHandler *load_state;
6011 void *opaque;
6012 struct SaveStateEntry *next;
6013 } SaveStateEntry;
6015 static SaveStateEntry *first_se;
6017 int register_savevm(const char *idstr,
6018 int instance_id,
6019 int version_id,
6020 SaveStateHandler *save_state,
6021 LoadStateHandler *load_state,
6022 void *opaque)
6024 SaveStateEntry *se, **pse;
6026 se = qemu_malloc(sizeof(SaveStateEntry));
6027 if (!se)
6028 return -1;
6029 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6030 se->instance_id = instance_id;
6031 se->version_id = version_id;
6032 se->save_state = save_state;
6033 se->load_state = load_state;
6034 se->opaque = opaque;
6035 se->next = NULL;
6037 /* add at the end of list */
6038 pse = &first_se;
6039 while (*pse != NULL)
6040 pse = &(*pse)->next;
6041 *pse = se;
6042 return 0;
6045 #define QEMU_VM_FILE_MAGIC 0x5145564d
6046 #define QEMU_VM_FILE_VERSION 0x00000002
6048 static int qemu_savevm_state(QEMUFile *f)
6050 SaveStateEntry *se;
6051 int len, ret;
6052 int64_t cur_pos, len_pos, total_len_pos;
6054 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6055 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6056 total_len_pos = qemu_ftell(f);
6057 qemu_put_be64(f, 0); /* total size */
6059 for(se = first_se; se != NULL; se = se->next) {
6060 /* ID string */
6061 len = strlen(se->idstr);
6062 qemu_put_byte(f, len);
6063 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6065 qemu_put_be32(f, se->instance_id);
6066 qemu_put_be32(f, se->version_id);
6068 /* record size: filled later */
6069 len_pos = qemu_ftell(f);
6070 qemu_put_be32(f, 0);
6071 se->save_state(f, se->opaque);
6073 /* fill record size */
6074 cur_pos = qemu_ftell(f);
6075 len = cur_pos - len_pos - 4;
6076 qemu_fseek(f, len_pos, SEEK_SET);
6077 qemu_put_be32(f, len);
6078 qemu_fseek(f, cur_pos, SEEK_SET);
6080 cur_pos = qemu_ftell(f);
6081 qemu_fseek(f, total_len_pos, SEEK_SET);
6082 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6083 qemu_fseek(f, cur_pos, SEEK_SET);
6085 ret = 0;
6086 return ret;
6089 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6091 SaveStateEntry *se;
6093 for(se = first_se; se != NULL; se = se->next) {
6094 if (!strcmp(se->idstr, idstr) &&
6095 instance_id == se->instance_id)
6096 return se;
6098 return NULL;
6101 static int qemu_loadvm_state(QEMUFile *f)
6103 SaveStateEntry *se;
6104 int len, ret, instance_id, record_len, version_id;
6105 int64_t total_len, end_pos, cur_pos;
6106 unsigned int v;
6107 char idstr[256];
6109 v = qemu_get_be32(f);
6110 if (v != QEMU_VM_FILE_MAGIC)
6111 goto fail;
6112 v = qemu_get_be32(f);
6113 if (v != QEMU_VM_FILE_VERSION) {
6114 fail:
6115 ret = -1;
6116 goto the_end;
6118 total_len = qemu_get_be64(f);
6119 end_pos = total_len + qemu_ftell(f);
6120 for(;;) {
6121 if (qemu_ftell(f) >= end_pos)
6122 break;
6123 len = qemu_get_byte(f);
6124 qemu_get_buffer(f, (uint8_t *)idstr, len);
6125 idstr[len] = '\0';
6126 instance_id = qemu_get_be32(f);
6127 version_id = qemu_get_be32(f);
6128 record_len = qemu_get_be32(f);
6129 #if 0
6130 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6131 idstr, instance_id, version_id, record_len);
6132 #endif
6133 cur_pos = qemu_ftell(f);
6134 se = find_se(idstr, instance_id);
6135 if (!se) {
6136 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6137 instance_id, idstr);
6138 } else {
6139 ret = se->load_state(f, se->opaque, version_id);
6140 if (ret < 0) {
6141 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6142 instance_id, idstr);
6143 goto the_end;
6146 /* always seek to exact end of record */
6147 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6149 ret = 0;
6150 the_end:
6151 return ret;
6154 int qemu_live_savevm_state(QEMUFile *f)
6156 SaveStateEntry *se;
6157 int len, ret;
6159 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6160 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6162 for(se = first_se; se != NULL; se = se->next) {
6163 len = strlen(se->idstr);
6165 qemu_put_byte(f, len);
6166 qemu_put_buffer(f, se->idstr, len);
6167 qemu_put_be32(f, se->instance_id);
6168 qemu_put_be32(f, se->version_id);
6170 se->save_state(f, se->opaque);
6173 qemu_put_byte(f, 0);
6175 ret = 0;
6176 return ret;
6179 int qemu_live_loadvm_state(QEMUFile *f)
6181 SaveStateEntry *se;
6182 int len, ret, instance_id, version_id;
6183 unsigned int v;
6184 char idstr[256];
6186 v = qemu_get_be32(f);
6187 if (v != QEMU_VM_FILE_MAGIC)
6188 goto fail;
6189 v = qemu_get_be32(f);
6190 if (v != QEMU_VM_FILE_VERSION) {
6191 fail:
6192 ret = -1;
6193 goto the_end;
6196 for(;;) {
6197 len = qemu_get_byte(f);
6198 if (len == 0)
6199 break;
6200 qemu_get_buffer(f, idstr, len);
6201 idstr[len] = '\0';
6202 instance_id = qemu_get_be32(f);
6203 version_id = qemu_get_be32(f);
6204 se = find_se(idstr, instance_id);
6205 if (!se) {
6206 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6207 instance_id, idstr);
6208 } else {
6209 if (version_id > se->version_id) { /* src version > dst version */
6210 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6211 idstr, version_id, se->version_id);
6212 ret = -1;
6213 goto the_end;
6215 ret = se->load_state(f, se->opaque, version_id);
6216 if (ret < 0) {
6217 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6218 instance_id, idstr);
6219 goto the_end;
6223 ret = 0;
6225 qemu_announce_self();
6227 the_end:
6228 return ret;
6231 /* device can contain snapshots */
6232 static int bdrv_can_snapshot(BlockDriverState *bs)
6234 return (bs &&
6235 !bdrv_is_removable(bs) &&
6236 !bdrv_is_read_only(bs));
6239 /* device must be snapshots in order to have a reliable snapshot */
6240 static int bdrv_has_snapshot(BlockDriverState *bs)
6242 return (bs &&
6243 !bdrv_is_removable(bs) &&
6244 !bdrv_is_read_only(bs));
6247 static BlockDriverState *get_bs_snapshots(void)
6249 BlockDriverState *bs;
6250 int i;
6252 if (bs_snapshots)
6253 return bs_snapshots;
6254 for(i = 0; i <= nb_drives; i++) {
6255 bs = drives_table[i].bdrv;
6256 if (bdrv_can_snapshot(bs))
6257 goto ok;
6259 return NULL;
6261 bs_snapshots = bs;
6262 return bs;
6265 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6266 const char *name)
6268 QEMUSnapshotInfo *sn_tab, *sn;
6269 int nb_sns, i, ret;
6271 ret = -ENOENT;
6272 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6273 if (nb_sns < 0)
6274 return ret;
6275 for(i = 0; i < nb_sns; i++) {
6276 sn = &sn_tab[i];
6277 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6278 *sn_info = *sn;
6279 ret = 0;
6280 break;
6283 qemu_free(sn_tab);
6284 return ret;
6287 void do_savevm(const char *name)
6289 BlockDriverState *bs, *bs1;
6290 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6291 int must_delete, ret, i;
6292 BlockDriverInfo bdi1, *bdi = &bdi1;
6293 QEMUFile *f;
6294 int saved_vm_running;
6295 #ifdef _WIN32
6296 struct _timeb tb;
6297 #else
6298 struct timeval tv;
6299 #endif
6301 bs = get_bs_snapshots();
6302 if (!bs) {
6303 term_printf("No block device can accept snapshots\n");
6304 return;
6307 /* ??? Should this occur after vm_stop? */
6308 qemu_aio_flush();
6310 saved_vm_running = vm_running;
6311 vm_stop(0);
6313 must_delete = 0;
6314 if (name) {
6315 ret = bdrv_snapshot_find(bs, old_sn, name);
6316 if (ret >= 0) {
6317 must_delete = 1;
6320 memset(sn, 0, sizeof(*sn));
6321 if (must_delete) {
6322 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6323 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6324 } else {
6325 if (name)
6326 pstrcpy(sn->name, sizeof(sn->name), name);
6329 /* fill auxiliary fields */
6330 #ifdef _WIN32
6331 _ftime(&tb);
6332 sn->date_sec = tb.time;
6333 sn->date_nsec = tb.millitm * 1000000;
6334 #else
6335 gettimeofday(&tv, NULL);
6336 sn->date_sec = tv.tv_sec;
6337 sn->date_nsec = tv.tv_usec * 1000;
6338 #endif
6339 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6341 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6342 term_printf("Device %s does not support VM state snapshots\n",
6343 bdrv_get_device_name(bs));
6344 goto the_end;
6347 /* save the VM state */
6348 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6349 if (!f) {
6350 term_printf("Could not open VM state file\n");
6351 goto the_end;
6353 ret = qemu_savevm_state(f);
6354 sn->vm_state_size = qemu_ftell(f);
6355 qemu_fclose(f);
6356 if (ret < 0) {
6357 term_printf("Error %d while writing VM\n", ret);
6358 goto the_end;
6361 /* create the snapshots */
6363 for(i = 0; i < nb_drives; i++) {
6364 bs1 = drives_table[i].bdrv;
6365 if (bdrv_has_snapshot(bs1)) {
6366 if (must_delete) {
6367 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6368 if (ret < 0) {
6369 term_printf("Error while deleting snapshot on '%s'\n",
6370 bdrv_get_device_name(bs1));
6373 ret = bdrv_snapshot_create(bs1, sn);
6374 if (ret < 0) {
6375 term_printf("Error while creating snapshot on '%s'\n",
6376 bdrv_get_device_name(bs1));
6381 the_end:
6382 if (saved_vm_running)
6383 vm_start();
6386 void do_loadvm(const char *name)
6388 BlockDriverState *bs, *bs1;
6389 BlockDriverInfo bdi1, *bdi = &bdi1;
6390 QEMUFile *f;
6391 int i, ret;
6392 int saved_vm_running;
6394 bs = get_bs_snapshots();
6395 if (!bs) {
6396 term_printf("No block device supports snapshots\n");
6397 return;
6400 /* Flush all IO requests so they don't interfere with the new state. */
6401 qemu_aio_flush();
6403 saved_vm_running = vm_running;
6404 vm_stop(0);
6406 for(i = 0; i <= nb_drives; i++) {
6407 bs1 = drives_table[i].bdrv;
6408 if (bdrv_has_snapshot(bs1)) {
6409 ret = bdrv_snapshot_goto(bs1, name);
6410 if (ret < 0) {
6411 if (bs != bs1)
6412 term_printf("Warning: ");
6413 switch(ret) {
6414 case -ENOTSUP:
6415 term_printf("Snapshots not supported on device '%s'\n",
6416 bdrv_get_device_name(bs1));
6417 break;
6418 case -ENOENT:
6419 term_printf("Could not find snapshot '%s' on device '%s'\n",
6420 name, bdrv_get_device_name(bs1));
6421 break;
6422 default:
6423 term_printf("Error %d while activating snapshot on '%s'\n",
6424 ret, bdrv_get_device_name(bs1));
6425 break;
6427 /* fatal on snapshot block device */
6428 if (bs == bs1)
6429 goto the_end;
6434 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6435 term_printf("Device %s does not support VM state snapshots\n",
6436 bdrv_get_device_name(bs));
6437 return;
6440 /* restore the VM state */
6441 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6442 if (!f) {
6443 term_printf("Could not open VM state file\n");
6444 goto the_end;
6446 ret = qemu_loadvm_state(f);
6447 qemu_fclose(f);
6448 if (ret < 0) {
6449 term_printf("Error %d while loading VM state\n", ret);
6451 the_end:
6452 if (saved_vm_running)
6453 vm_start();
6456 void do_delvm(const char *name)
6458 BlockDriverState *bs, *bs1;
6459 int i, ret;
6461 bs = get_bs_snapshots();
6462 if (!bs) {
6463 term_printf("No block device supports snapshots\n");
6464 return;
6467 for(i = 0; i <= nb_drives; i++) {
6468 bs1 = drives_table[i].bdrv;
6469 if (bdrv_has_snapshot(bs1)) {
6470 ret = bdrv_snapshot_delete(bs1, name);
6471 if (ret < 0) {
6472 if (ret == -ENOTSUP)
6473 term_printf("Snapshots not supported on device '%s'\n",
6474 bdrv_get_device_name(bs1));
6475 else
6476 term_printf("Error %d while deleting snapshot on '%s'\n",
6477 ret, bdrv_get_device_name(bs1));
6483 void do_info_snapshots(void)
6485 BlockDriverState *bs, *bs1;
6486 QEMUSnapshotInfo *sn_tab, *sn;
6487 int nb_sns, i;
6488 char buf[256];
6490 bs = get_bs_snapshots();
6491 if (!bs) {
6492 term_printf("No available block device supports snapshots\n");
6493 return;
6495 term_printf("Snapshot devices:");
6496 for(i = 0; i <= nb_drives; i++) {
6497 bs1 = drives_table[i].bdrv;
6498 if (bdrv_has_snapshot(bs1)) {
6499 if (bs == bs1)
6500 term_printf(" %s", bdrv_get_device_name(bs1));
6503 term_printf("\n");
6505 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6506 if (nb_sns < 0) {
6507 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6508 return;
6510 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6511 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6512 for(i = 0; i < nb_sns; i++) {
6513 sn = &sn_tab[i];
6514 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6516 qemu_free(sn_tab);
6519 /***********************************************************/
6520 /* cpu save/restore */
6522 #if defined(TARGET_I386)
6524 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6526 qemu_put_be32(f, dt->selector);
6527 qemu_put_betl(f, dt->base);
6528 qemu_put_be32(f, dt->limit);
6529 qemu_put_be32(f, dt->flags);
6532 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6534 dt->selector = qemu_get_be32(f);
6535 dt->base = qemu_get_betl(f);
6536 dt->limit = qemu_get_be32(f);
6537 dt->flags = qemu_get_be32(f);
6540 void cpu_save(QEMUFile *f, void *opaque)
6542 CPUState *env = opaque;
6543 uint16_t fptag, fpus, fpuc, fpregs_format;
6544 uint32_t hflags;
6545 int i;
6547 if (kvm_enabled())
6548 kvm_save_registers(env);
6550 for(i = 0; i < CPU_NB_REGS; i++)
6551 qemu_put_betls(f, &env->regs[i]);
6552 qemu_put_betls(f, &env->eip);
6553 qemu_put_betls(f, &env->eflags);
6554 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6555 qemu_put_be32s(f, &hflags);
6557 /* FPU */
6558 fpuc = env->fpuc;
6559 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6560 fptag = 0;
6561 for(i = 0; i < 8; i++) {
6562 fptag |= ((!env->fptags[i]) << i);
6565 qemu_put_be16s(f, &fpuc);
6566 qemu_put_be16s(f, &fpus);
6567 qemu_put_be16s(f, &fptag);
6569 #ifdef USE_X86LDOUBLE
6570 fpregs_format = 0;
6571 #else
6572 fpregs_format = 1;
6573 #endif
6574 qemu_put_be16s(f, &fpregs_format);
6576 for(i = 0; i < 8; i++) {
6577 #ifdef USE_X86LDOUBLE
6579 uint64_t mant;
6580 uint16_t exp;
6581 /* we save the real CPU data (in case of MMX usage only 'mant'
6582 contains the MMX register */
6583 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6584 qemu_put_be64(f, mant);
6585 qemu_put_be16(f, exp);
6587 #else
6588 /* if we use doubles for float emulation, we save the doubles to
6589 avoid losing information in case of MMX usage. It can give
6590 problems if the image is restored on a CPU where long
6591 doubles are used instead. */
6592 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6593 #endif
6596 for(i = 0; i < 6; i++)
6597 cpu_put_seg(f, &env->segs[i]);
6598 cpu_put_seg(f, &env->ldt);
6599 cpu_put_seg(f, &env->tr);
6600 cpu_put_seg(f, &env->gdt);
6601 cpu_put_seg(f, &env->idt);
6603 qemu_put_be32s(f, &env->sysenter_cs);
6604 qemu_put_be32s(f, &env->sysenter_esp);
6605 qemu_put_be32s(f, &env->sysenter_eip);
6607 qemu_put_betls(f, &env->cr[0]);
6608 qemu_put_betls(f, &env->cr[2]);
6609 qemu_put_betls(f, &env->cr[3]);
6610 qemu_put_betls(f, &env->cr[4]);
6612 for(i = 0; i < 8; i++)
6613 qemu_put_betls(f, &env->dr[i]);
6615 /* MMU */
6616 qemu_put_be32s(f, &env->a20_mask);
6618 /* XMM */
6619 qemu_put_be32s(f, &env->mxcsr);
6620 for(i = 0; i < CPU_NB_REGS; i++) {
6621 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6622 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6625 #ifdef TARGET_X86_64
6626 qemu_put_be64s(f, &env->efer);
6627 qemu_put_be64s(f, &env->star);
6628 qemu_put_be64s(f, &env->lstar);
6629 qemu_put_be64s(f, &env->cstar);
6630 qemu_put_be64s(f, &env->fmask);
6631 qemu_put_be64s(f, &env->kernelgsbase);
6632 #endif
6633 qemu_put_be32s(f, &env->smbase);
6635 if (kvm_enabled()) {
6636 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6637 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6639 qemu_put_be64s(f, &env->tsc);
6643 #ifdef USE_X86LDOUBLE
6644 /* XXX: add that in a FPU generic layer */
6645 union x86_longdouble {
6646 uint64_t mant;
6647 uint16_t exp;
6650 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6651 #define EXPBIAS1 1023
6652 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6653 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6655 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6657 int e;
6658 /* mantissa */
6659 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6660 /* exponent + sign */
6661 e = EXPD1(temp) - EXPBIAS1 + 16383;
6662 e |= SIGND1(temp) >> 16;
6663 p->exp = e;
6665 #endif
6667 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6669 CPUState *env = opaque;
6670 int i, guess_mmx;
6671 uint32_t hflags;
6672 uint16_t fpus, fpuc, fptag, fpregs_format;
6674 if (version_id != 3 && version_id != 4)
6675 return -EINVAL;
6676 for(i = 0; i < CPU_NB_REGS; i++)
6677 qemu_get_betls(f, &env->regs[i]);
6678 qemu_get_betls(f, &env->eip);
6679 qemu_get_betls(f, &env->eflags);
6680 qemu_get_be32s(f, &hflags);
6682 qemu_get_be16s(f, &fpuc);
6683 qemu_get_be16s(f, &fpus);
6684 qemu_get_be16s(f, &fptag);
6685 qemu_get_be16s(f, &fpregs_format);
6687 /* NOTE: we cannot always restore the FPU state if the image come
6688 from a host with a different 'USE_X86LDOUBLE' define. We guess
6689 if we are in an MMX state to restore correctly in that case. */
6690 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6691 for(i = 0; i < 8; i++) {
6692 uint64_t mant;
6693 uint16_t exp;
6695 switch(fpregs_format) {
6696 case 0:
6697 mant = qemu_get_be64(f);
6698 exp = qemu_get_be16(f);
6699 #ifdef USE_X86LDOUBLE
6700 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6701 #else
6702 /* difficult case */
6703 if (guess_mmx)
6704 env->fpregs[i].mmx.MMX_Q(0) = mant;
6705 else
6706 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6707 #endif
6708 break;
6709 case 1:
6710 mant = qemu_get_be64(f);
6711 #ifdef USE_X86LDOUBLE
6713 union x86_longdouble *p;
6714 /* difficult case */
6715 p = (void *)&env->fpregs[i];
6716 if (guess_mmx) {
6717 p->mant = mant;
6718 p->exp = 0xffff;
6719 } else {
6720 fp64_to_fp80(p, mant);
6723 #else
6724 env->fpregs[i].mmx.MMX_Q(0) = mant;
6725 #endif
6726 break;
6727 default:
6728 return -EINVAL;
6732 env->fpuc = fpuc;
6733 /* XXX: restore FPU round state */
6734 env->fpstt = (fpus >> 11) & 7;
6735 env->fpus = fpus & ~0x3800;
6736 fptag ^= 0xff;
6737 for(i = 0; i < 8; i++) {
6738 env->fptags[i] = (fptag >> i) & 1;
6741 for(i = 0; i < 6; i++)
6742 cpu_get_seg(f, &env->segs[i]);
6743 cpu_get_seg(f, &env->ldt);
6744 cpu_get_seg(f, &env->tr);
6745 cpu_get_seg(f, &env->gdt);
6746 cpu_get_seg(f, &env->idt);
6748 qemu_get_be32s(f, &env->sysenter_cs);
6749 qemu_get_be32s(f, &env->sysenter_esp);
6750 qemu_get_be32s(f, &env->sysenter_eip);
6752 qemu_get_betls(f, &env->cr[0]);
6753 qemu_get_betls(f, &env->cr[2]);
6754 qemu_get_betls(f, &env->cr[3]);
6755 qemu_get_betls(f, &env->cr[4]);
6757 for(i = 0; i < 8; i++)
6758 qemu_get_betls(f, &env->dr[i]);
6760 /* MMU */
6761 qemu_get_be32s(f, &env->a20_mask);
6763 qemu_get_be32s(f, &env->mxcsr);
6764 for(i = 0; i < CPU_NB_REGS; i++) {
6765 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6766 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6769 #ifdef TARGET_X86_64
6770 qemu_get_be64s(f, &env->efer);
6771 qemu_get_be64s(f, &env->star);
6772 qemu_get_be64s(f, &env->lstar);
6773 qemu_get_be64s(f, &env->cstar);
6774 qemu_get_be64s(f, &env->fmask);
6775 qemu_get_be64s(f, &env->kernelgsbase);
6776 #endif
6777 if (version_id >= 4)
6778 qemu_get_be32s(f, &env->smbase);
6780 /* XXX: compute hflags from scratch, except for CPL and IIF */
6781 env->hflags = hflags;
6782 tlb_flush(env, 1);
6783 if (kvm_enabled()) {
6784 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6785 because no userspace IRQs will ever clear this flag */
6786 env->hflags &= ~HF_HALTED_MASK;
6787 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6788 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6790 qemu_get_be64s(f, &env->tsc);
6791 kvm_load_registers(env);
6793 return 0;
6796 #elif defined(TARGET_PPC)
6797 void cpu_save(QEMUFile *f, void *opaque)
6801 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6803 return 0;
6806 #elif defined(TARGET_MIPS)
6807 void cpu_save(QEMUFile *f, void *opaque)
6811 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6813 return 0;
6816 #elif defined(TARGET_SPARC)
6817 void cpu_save(QEMUFile *f, void *opaque)
6819 CPUState *env = opaque;
6820 int i;
6821 uint32_t tmp;
6823 for(i = 0; i < 8; i++)
6824 qemu_put_betls(f, &env->gregs[i]);
6825 for(i = 0; i < NWINDOWS * 16; i++)
6826 qemu_put_betls(f, &env->regbase[i]);
6828 /* FPU */
6829 for(i = 0; i < TARGET_FPREGS; i++) {
6830 union {
6831 float32 f;
6832 uint32_t i;
6833 } u;
6834 u.f = env->fpr[i];
6835 qemu_put_be32(f, u.i);
6838 qemu_put_betls(f, &env->pc);
6839 qemu_put_betls(f, &env->npc);
6840 qemu_put_betls(f, &env->y);
6841 tmp = GET_PSR(env);
6842 qemu_put_be32(f, tmp);
6843 qemu_put_betls(f, &env->fsr);
6844 qemu_put_betls(f, &env->tbr);
6845 #ifndef TARGET_SPARC64
6846 qemu_put_be32s(f, &env->wim);
6847 /* MMU */
6848 for(i = 0; i < 16; i++)
6849 qemu_put_be32s(f, &env->mmuregs[i]);
6850 #endif
6853 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6855 CPUState *env = opaque;
6856 int i;
6857 uint32_t tmp;
6859 for(i = 0; i < 8; i++)
6860 qemu_get_betls(f, &env->gregs[i]);
6861 for(i = 0; i < NWINDOWS * 16; i++)
6862 qemu_get_betls(f, &env->regbase[i]);
6864 /* FPU */
6865 for(i = 0; i < TARGET_FPREGS; i++) {
6866 union {
6867 float32 f;
6868 uint32_t i;
6869 } u;
6870 u.i = qemu_get_be32(f);
6871 env->fpr[i] = u.f;
6874 qemu_get_betls(f, &env->pc);
6875 qemu_get_betls(f, &env->npc);
6876 qemu_get_betls(f, &env->y);
6877 tmp = qemu_get_be32(f);
6878 env->cwp = 0; /* needed to ensure that the wrapping registers are
6879 correctly updated */
6880 PUT_PSR(env, tmp);
6881 qemu_get_betls(f, &env->fsr);
6882 qemu_get_betls(f, &env->tbr);
6883 #ifndef TARGET_SPARC64
6884 qemu_get_be32s(f, &env->wim);
6885 /* MMU */
6886 for(i = 0; i < 16; i++)
6887 qemu_get_be32s(f, &env->mmuregs[i]);
6888 #endif
6889 tlb_flush(env, 1);
6890 return 0;
6893 #elif defined(TARGET_ARM)
6895 void cpu_save(QEMUFile *f, void *opaque)
6897 int i;
6898 CPUARMState *env = (CPUARMState *)opaque;
6900 for (i = 0; i < 16; i++) {
6901 qemu_put_be32(f, env->regs[i]);
6903 qemu_put_be32(f, cpsr_read(env));
6904 qemu_put_be32(f, env->spsr);
6905 for (i = 0; i < 6; i++) {
6906 qemu_put_be32(f, env->banked_spsr[i]);
6907 qemu_put_be32(f, env->banked_r13[i]);
6908 qemu_put_be32(f, env->banked_r14[i]);
6910 for (i = 0; i < 5; i++) {
6911 qemu_put_be32(f, env->usr_regs[i]);
6912 qemu_put_be32(f, env->fiq_regs[i]);
6914 qemu_put_be32(f, env->cp15.c0_cpuid);
6915 qemu_put_be32(f, env->cp15.c0_cachetype);
6916 qemu_put_be32(f, env->cp15.c1_sys);
6917 qemu_put_be32(f, env->cp15.c1_coproc);
6918 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6919 qemu_put_be32(f, env->cp15.c2_base0);
6920 qemu_put_be32(f, env->cp15.c2_base1);
6921 qemu_put_be32(f, env->cp15.c2_mask);
6922 qemu_put_be32(f, env->cp15.c2_data);
6923 qemu_put_be32(f, env->cp15.c2_insn);
6924 qemu_put_be32(f, env->cp15.c3);
6925 qemu_put_be32(f, env->cp15.c5_insn);
6926 qemu_put_be32(f, env->cp15.c5_data);
6927 for (i = 0; i < 8; i++) {
6928 qemu_put_be32(f, env->cp15.c6_region[i]);
6930 qemu_put_be32(f, env->cp15.c6_insn);
6931 qemu_put_be32(f, env->cp15.c6_data);
6932 qemu_put_be32(f, env->cp15.c9_insn);
6933 qemu_put_be32(f, env->cp15.c9_data);
6934 qemu_put_be32(f, env->cp15.c13_fcse);
6935 qemu_put_be32(f, env->cp15.c13_context);
6936 qemu_put_be32(f, env->cp15.c13_tls1);
6937 qemu_put_be32(f, env->cp15.c13_tls2);
6938 qemu_put_be32(f, env->cp15.c13_tls3);
6939 qemu_put_be32(f, env->cp15.c15_cpar);
6941 qemu_put_be32(f, env->features);
6943 if (arm_feature(env, ARM_FEATURE_VFP)) {
6944 for (i = 0; i < 16; i++) {
6945 CPU_DoubleU u;
6946 u.d = env->vfp.regs[i];
6947 qemu_put_be32(f, u.l.upper);
6948 qemu_put_be32(f, u.l.lower);
6950 for (i = 0; i < 16; i++) {
6951 qemu_put_be32(f, env->vfp.xregs[i]);
6954 /* TODO: Should use proper FPSCR access functions. */
6955 qemu_put_be32(f, env->vfp.vec_len);
6956 qemu_put_be32(f, env->vfp.vec_stride);
6958 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6959 for (i = 16; i < 32; i++) {
6960 CPU_DoubleU u;
6961 u.d = env->vfp.regs[i];
6962 qemu_put_be32(f, u.l.upper);
6963 qemu_put_be32(f, u.l.lower);
6968 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6969 for (i = 0; i < 16; i++) {
6970 qemu_put_be64(f, env->iwmmxt.regs[i]);
6972 for (i = 0; i < 16; i++) {
6973 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6977 if (arm_feature(env, ARM_FEATURE_M)) {
6978 qemu_put_be32(f, env->v7m.other_sp);
6979 qemu_put_be32(f, env->v7m.vecbase);
6980 qemu_put_be32(f, env->v7m.basepri);
6981 qemu_put_be32(f, env->v7m.control);
6982 qemu_put_be32(f, env->v7m.current_sp);
6983 qemu_put_be32(f, env->v7m.exception);
6987 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6989 CPUARMState *env = (CPUARMState *)opaque;
6990 int i;
6992 if (version_id != ARM_CPU_SAVE_VERSION)
6993 return -EINVAL;
6995 for (i = 0; i < 16; i++) {
6996 env->regs[i] = qemu_get_be32(f);
6998 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6999 env->spsr = qemu_get_be32(f);
7000 for (i = 0; i < 6; i++) {
7001 env->banked_spsr[i] = qemu_get_be32(f);
7002 env->banked_r13[i] = qemu_get_be32(f);
7003 env->banked_r14[i] = qemu_get_be32(f);
7005 for (i = 0; i < 5; i++) {
7006 env->usr_regs[i] = qemu_get_be32(f);
7007 env->fiq_regs[i] = qemu_get_be32(f);
7009 env->cp15.c0_cpuid = qemu_get_be32(f);
7010 env->cp15.c0_cachetype = qemu_get_be32(f);
7011 env->cp15.c1_sys = qemu_get_be32(f);
7012 env->cp15.c1_coproc = qemu_get_be32(f);
7013 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7014 env->cp15.c2_base0 = qemu_get_be32(f);
7015 env->cp15.c2_base1 = qemu_get_be32(f);
7016 env->cp15.c2_mask = qemu_get_be32(f);
7017 env->cp15.c2_data = qemu_get_be32(f);
7018 env->cp15.c2_insn = qemu_get_be32(f);
7019 env->cp15.c3 = qemu_get_be32(f);
7020 env->cp15.c5_insn = qemu_get_be32(f);
7021 env->cp15.c5_data = qemu_get_be32(f);
7022 for (i = 0; i < 8; i++) {
7023 env->cp15.c6_region[i] = qemu_get_be32(f);
7025 env->cp15.c6_insn = qemu_get_be32(f);
7026 env->cp15.c6_data = qemu_get_be32(f);
7027 env->cp15.c9_insn = qemu_get_be32(f);
7028 env->cp15.c9_data = qemu_get_be32(f);
7029 env->cp15.c13_fcse = qemu_get_be32(f);
7030 env->cp15.c13_context = qemu_get_be32(f);
7031 env->cp15.c13_tls1 = qemu_get_be32(f);
7032 env->cp15.c13_tls2 = qemu_get_be32(f);
7033 env->cp15.c13_tls3 = qemu_get_be32(f);
7034 env->cp15.c15_cpar = qemu_get_be32(f);
7036 env->features = qemu_get_be32(f);
7038 if (arm_feature(env, ARM_FEATURE_VFP)) {
7039 for (i = 0; i < 16; i++) {
7040 CPU_DoubleU u;
7041 u.l.upper = qemu_get_be32(f);
7042 u.l.lower = qemu_get_be32(f);
7043 env->vfp.regs[i] = u.d;
7045 for (i = 0; i < 16; i++) {
7046 env->vfp.xregs[i] = qemu_get_be32(f);
7049 /* TODO: Should use proper FPSCR access functions. */
7050 env->vfp.vec_len = qemu_get_be32(f);
7051 env->vfp.vec_stride = qemu_get_be32(f);
7053 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7054 for (i = 0; i < 16; i++) {
7055 CPU_DoubleU u;
7056 u.l.upper = qemu_get_be32(f);
7057 u.l.lower = qemu_get_be32(f);
7058 env->vfp.regs[i] = u.d;
7063 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7064 for (i = 0; i < 16; i++) {
7065 env->iwmmxt.regs[i] = qemu_get_be64(f);
7067 for (i = 0; i < 16; i++) {
7068 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7072 if (arm_feature(env, ARM_FEATURE_M)) {
7073 env->v7m.other_sp = qemu_get_be32(f);
7074 env->v7m.vecbase = qemu_get_be32(f);
7075 env->v7m.basepri = qemu_get_be32(f);
7076 env->v7m.control = qemu_get_be32(f);
7077 env->v7m.current_sp = qemu_get_be32(f);
7078 env->v7m.exception = qemu_get_be32(f);
7081 return 0;
7084 #elif defined(TARGET_IA64)
7085 void cpu_save(QEMUFile *f, void *opaque)
7089 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7091 return 0;
7093 #else
7095 //#warning No CPU save/restore functions
7097 #endif
7099 /***********************************************************/
7100 /* ram save/restore */
7102 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7104 int v;
7106 v = qemu_get_byte(f);
7107 switch(v) {
7108 case 0:
7109 if (qemu_get_buffer(f, buf, len) != len)
7110 return -EIO;
7111 break;
7112 case 1:
7113 v = qemu_get_byte(f);
7114 memset(buf, v, len);
7115 break;
7116 default:
7117 return -EINVAL;
7119 return 0;
7122 static int ram_load_v1(QEMUFile *f, void *opaque)
7124 int i, ret;
7126 if (qemu_get_be32(f) != phys_ram_size)
7127 return -EINVAL;
7128 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7129 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7130 continue;
7131 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7132 if (ret)
7133 return ret;
7135 return 0;
7138 #define BDRV_HASH_BLOCK_SIZE 1024
7139 #define IOBUF_SIZE 4096
7140 #define RAM_CBLOCK_MAGIC 0xfabe
7142 typedef struct RamCompressState {
7143 z_stream zstream;
7144 QEMUFile *f;
7145 uint8_t buf[IOBUF_SIZE];
7146 } RamCompressState;
7148 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7150 int ret;
7151 memset(s, 0, sizeof(*s));
7152 s->f = f;
7153 ret = deflateInit2(&s->zstream, 1,
7154 Z_DEFLATED, 15,
7155 9, Z_DEFAULT_STRATEGY);
7156 if (ret != Z_OK)
7157 return -1;
7158 s->zstream.avail_out = IOBUF_SIZE;
7159 s->zstream.next_out = s->buf;
7160 return 0;
7163 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7165 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7166 qemu_put_be16(s->f, len);
7167 qemu_put_buffer(s->f, buf, len);
7170 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7172 int ret;
7174 s->zstream.avail_in = len;
7175 s->zstream.next_in = (uint8_t *)buf;
7176 while (s->zstream.avail_in > 0) {
7177 ret = deflate(&s->zstream, Z_NO_FLUSH);
7178 if (ret != Z_OK)
7179 return -1;
7180 if (s->zstream.avail_out == 0) {
7181 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7182 s->zstream.avail_out = IOBUF_SIZE;
7183 s->zstream.next_out = s->buf;
7186 return 0;
7189 static void ram_compress_close(RamCompressState *s)
7191 int len, ret;
7193 /* compress last bytes */
7194 for(;;) {
7195 ret = deflate(&s->zstream, Z_FINISH);
7196 if (ret == Z_OK || ret == Z_STREAM_END) {
7197 len = IOBUF_SIZE - s->zstream.avail_out;
7198 if (len > 0) {
7199 ram_put_cblock(s, s->buf, len);
7201 s->zstream.avail_out = IOBUF_SIZE;
7202 s->zstream.next_out = s->buf;
7203 if (ret == Z_STREAM_END)
7204 break;
7205 } else {
7206 goto fail;
7209 fail:
7210 deflateEnd(&s->zstream);
7213 typedef struct RamDecompressState {
7214 z_stream zstream;
7215 QEMUFile *f;
7216 uint8_t buf[IOBUF_SIZE];
7217 } RamDecompressState;
7219 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7221 int ret;
7222 memset(s, 0, sizeof(*s));
7223 s->f = f;
7224 ret = inflateInit(&s->zstream);
7225 if (ret != Z_OK)
7226 return -1;
7227 return 0;
7230 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7232 int ret, clen;
7234 s->zstream.avail_out = len;
7235 s->zstream.next_out = buf;
7236 while (s->zstream.avail_out > 0) {
7237 if (s->zstream.avail_in == 0) {
7238 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7239 return -1;
7240 clen = qemu_get_be16(s->f);
7241 if (clen > IOBUF_SIZE)
7242 return -1;
7243 qemu_get_buffer(s->f, s->buf, clen);
7244 s->zstream.avail_in = clen;
7245 s->zstream.next_in = s->buf;
7247 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7248 if (ret != Z_OK && ret != Z_STREAM_END) {
7249 return -1;
7252 return 0;
7255 static void ram_decompress_close(RamDecompressState *s)
7257 inflateEnd(&s->zstream);
7260 static void ram_save_live(QEMUFile *f, void *opaque)
7262 target_ulong addr;
7264 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7265 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7266 continue;
7267 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7268 qemu_put_be32(f, addr);
7269 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7272 qemu_put_be32(f, 1);
7275 static void ram_save_static(QEMUFile *f, void *opaque)
7277 int i;
7278 RamCompressState s1, *s = &s1;
7279 uint8_t buf[10];
7281 qemu_put_be32(f, phys_ram_size);
7282 if (ram_compress_open(s, f) < 0)
7283 return;
7284 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7285 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7286 continue;
7287 #if 0
7288 if (tight_savevm_enabled) {
7289 int64_t sector_num;
7290 int j;
7292 /* find if the memory block is available on a virtual
7293 block device */
7294 sector_num = -1;
7295 for(j = 0; j < nb_drives; j++) {
7296 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7297 phys_ram_base + i,
7298 BDRV_HASH_BLOCK_SIZE);
7299 if (sector_num >= 0)
7300 break;
7302 if (j == nb_drives)
7303 goto normal_compress;
7304 buf[0] = 1;
7305 buf[1] = j;
7306 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7307 ram_compress_buf(s, buf, 10);
7308 } else
7309 #endif
7311 // normal_compress:
7312 buf[0] = 0;
7313 ram_compress_buf(s, buf, 1);
7314 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7317 ram_compress_close(s);
7320 static void ram_save(QEMUFile *f, void *opaque)
7322 int in_migration = cpu_physical_memory_get_dirty_tracking();
7324 qemu_put_byte(f, in_migration);
7326 if (in_migration)
7327 ram_save_live(f, opaque);
7328 else
7329 ram_save_static(f, opaque);
7332 static int ram_load_live(QEMUFile *f, void *opaque)
7334 target_ulong addr;
7336 do {
7337 addr = qemu_get_be32(f);
7338 if (addr == 1)
7339 break;
7341 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7342 } while (1);
7344 return 0;
7347 static int ram_load_static(QEMUFile *f, void *opaque)
7349 RamDecompressState s1, *s = &s1;
7350 uint8_t buf[10];
7351 int i;
7353 if (qemu_get_be32(f) != phys_ram_size)
7354 return -EINVAL;
7355 if (ram_decompress_open(s, f) < 0)
7356 return -EINVAL;
7357 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7358 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7359 continue;
7360 if (ram_decompress_buf(s, buf, 1) < 0) {
7361 fprintf(stderr, "Error while reading ram block header\n");
7362 goto error;
7364 if (buf[0] == 0) {
7365 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7366 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7367 goto error;
7369 } else
7370 #if 0
7371 if (buf[0] == 1) {
7372 int bs_index;
7373 int64_t sector_num;
7375 ram_decompress_buf(s, buf + 1, 9);
7376 bs_index = buf[1];
7377 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7378 if (bs_index >= nb_drives) {
7379 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7380 goto error;
7382 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7383 phys_ram_base + i,
7384 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7385 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7386 bs_index, sector_num);
7387 goto error;
7389 } else
7390 #endif
7392 error:
7393 printf("Error block header\n");
7394 return -EINVAL;
7397 ram_decompress_close(s);
7398 return 0;
7401 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7403 int ret;
7405 switch (version_id) {
7406 case 1:
7407 ret = ram_load_v1(f, opaque);
7408 break;
7409 case 3:
7410 if (qemu_get_byte(f)) {
7411 ret = ram_load_live(f, opaque);
7412 break;
7414 case 2:
7415 ret = ram_load_static(f, opaque);
7416 break;
7417 default:
7418 ret = -EINVAL;
7419 break;
7422 return ret;
7425 /***********************************************************/
7426 /* bottom halves (can be seen as timers which expire ASAP) */
7428 struct QEMUBH {
7429 QEMUBHFunc *cb;
7430 void *opaque;
7431 int scheduled;
7432 QEMUBH *next;
7435 static QEMUBH *first_bh = NULL;
7437 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7439 QEMUBH *bh;
7440 bh = qemu_mallocz(sizeof(QEMUBH));
7441 if (!bh)
7442 return NULL;
7443 bh->cb = cb;
7444 bh->opaque = opaque;
7445 return bh;
7448 int qemu_bh_poll(void)
7450 QEMUBH *bh, **pbh;
7451 int ret;
7453 ret = 0;
7454 for(;;) {
7455 pbh = &first_bh;
7456 bh = *pbh;
7457 if (!bh)
7458 break;
7459 ret = 1;
7460 *pbh = bh->next;
7461 bh->scheduled = 0;
7462 bh->cb(bh->opaque);
7464 return ret;
7467 void qemu_bh_schedule(QEMUBH *bh)
7469 CPUState *env = cpu_single_env;
7470 if (bh->scheduled)
7471 return;
7472 bh->scheduled = 1;
7473 bh->next = first_bh;
7474 first_bh = bh;
7476 /* stop the currently executing CPU to execute the BH ASAP */
7477 if (env) {
7478 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7482 void qemu_bh_cancel(QEMUBH *bh)
7484 QEMUBH **pbh;
7485 if (bh->scheduled) {
7486 pbh = &first_bh;
7487 while (*pbh != bh)
7488 pbh = &(*pbh)->next;
7489 *pbh = bh->next;
7490 bh->scheduled = 0;
7494 void qemu_bh_delete(QEMUBH *bh)
7496 qemu_bh_cancel(bh);
7497 qemu_free(bh);
7500 /***********************************************************/
7501 /* machine registration */
7503 QEMUMachine *first_machine = NULL;
7505 int qemu_register_machine(QEMUMachine *m)
7507 QEMUMachine **pm;
7508 pm = &first_machine;
7509 while (*pm != NULL)
7510 pm = &(*pm)->next;
7511 m->next = NULL;
7512 *pm = m;
7513 return 0;
7516 static QEMUMachine *find_machine(const char *name)
7518 QEMUMachine *m;
7520 for(m = first_machine; m != NULL; m = m->next) {
7521 if (!strcmp(m->name, name))
7522 return m;
7524 return NULL;
7527 /***********************************************************/
7528 /* main execution loop */
7530 static void gui_update(void *opaque)
7532 DisplayState *ds = opaque;
7533 ds->dpy_refresh(ds);
7534 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7537 struct vm_change_state_entry {
7538 VMChangeStateHandler *cb;
7539 void *opaque;
7540 LIST_ENTRY (vm_change_state_entry) entries;
7543 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7545 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7546 void *opaque)
7548 VMChangeStateEntry *e;
7550 e = qemu_mallocz(sizeof (*e));
7551 if (!e)
7552 return NULL;
7554 e->cb = cb;
7555 e->opaque = opaque;
7556 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7557 return e;
7560 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7562 LIST_REMOVE (e, entries);
7563 qemu_free (e);
7566 static void vm_state_notify(int running)
7568 VMChangeStateEntry *e;
7570 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7571 e->cb(e->opaque, running);
7575 /* XXX: support several handlers */
7576 static VMStopHandler *vm_stop_cb;
7577 static void *vm_stop_opaque;
7579 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7581 vm_stop_cb = cb;
7582 vm_stop_opaque = opaque;
7583 return 0;
7586 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7588 vm_stop_cb = NULL;
7591 void vm_start(void)
7593 if (!vm_running) {
7594 cpu_enable_ticks();
7595 vm_running = 1;
7596 vm_state_notify(1);
7597 qemu_rearm_alarm_timer(alarm_timer);
7601 void vm_stop(int reason)
7603 if (vm_running) {
7604 cpu_disable_ticks();
7605 vm_running = 0;
7606 if (reason != 0) {
7607 if (vm_stop_cb) {
7608 vm_stop_cb(vm_stop_opaque, reason);
7611 vm_state_notify(0);
7615 /* reset/shutdown handler */
7617 typedef struct QEMUResetEntry {
7618 QEMUResetHandler *func;
7619 void *opaque;
7620 struct QEMUResetEntry *next;
7621 } QEMUResetEntry;
7623 static QEMUResetEntry *first_reset_entry;
7624 static int reset_requested;
7625 static int shutdown_requested;
7626 static int powerdown_requested;
7628 int qemu_shutdown_requested(void)
7630 int r = shutdown_requested;
7631 shutdown_requested = 0;
7632 return r;
7635 int qemu_reset_requested(void)
7637 int r = reset_requested;
7638 reset_requested = 0;
7639 return r;
7642 int qemu_powerdown_requested(void)
7644 int r = powerdown_requested;
7645 powerdown_requested = 0;
7646 return r;
7649 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7651 QEMUResetEntry **pre, *re;
7653 pre = &first_reset_entry;
7654 while (*pre != NULL)
7655 pre = &(*pre)->next;
7656 re = qemu_mallocz(sizeof(QEMUResetEntry));
7657 re->func = func;
7658 re->opaque = opaque;
7659 re->next = NULL;
7660 *pre = re;
7663 void qemu_system_reset(void)
7665 QEMUResetEntry *re;
7667 /* reset all devices */
7668 for(re = first_reset_entry; re != NULL; re = re->next) {
7669 re->func(re->opaque);
7673 void qemu_system_reset_request(void)
7675 if (no_reboot) {
7676 shutdown_requested = 1;
7677 } else {
7678 reset_requested = 1;
7680 if (cpu_single_env)
7681 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7684 void qemu_system_shutdown_request(void)
7686 shutdown_requested = 1;
7687 if (cpu_single_env)
7688 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7691 void qemu_system_powerdown_request(void)
7693 powerdown_requested = 1;
7694 if (cpu_single_env)
7695 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7698 void main_loop_wait(int timeout)
7700 IOHandlerRecord *ioh;
7701 fd_set rfds, wfds, xfds;
7702 int ret, nfds;
7703 #ifdef _WIN32
7704 int ret2, i;
7705 #endif
7706 struct timeval tv;
7707 PollingEntry *pe;
7710 /* XXX: need to suppress polling by better using win32 events */
7711 ret = 0;
7712 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7713 ret |= pe->func(pe->opaque);
7715 #ifdef _WIN32
7716 if (ret == 0) {
7717 int err;
7718 WaitObjects *w = &wait_objects;
7720 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7721 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7722 if (w->func[ret - WAIT_OBJECT_0])
7723 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7725 /* Check for additional signaled events */
7726 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7728 /* Check if event is signaled */
7729 ret2 = WaitForSingleObject(w->events[i], 0);
7730 if(ret2 == WAIT_OBJECT_0) {
7731 if (w->func[i])
7732 w->func[i](w->opaque[i]);
7733 } else if (ret2 == WAIT_TIMEOUT) {
7734 } else {
7735 err = GetLastError();
7736 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7739 } else if (ret == WAIT_TIMEOUT) {
7740 } else {
7741 err = GetLastError();
7742 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7745 #endif
7746 /* poll any events */
7747 /* XXX: separate device handlers from system ones */
7748 nfds = -1;
7749 FD_ZERO(&rfds);
7750 FD_ZERO(&wfds);
7751 FD_ZERO(&xfds);
7752 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7753 if (ioh->deleted)
7754 continue;
7755 if (ioh->fd_read &&
7756 (!ioh->fd_read_poll ||
7757 ioh->fd_read_poll(ioh->opaque) != 0)) {
7758 FD_SET(ioh->fd, &rfds);
7759 if (ioh->fd > nfds)
7760 nfds = ioh->fd;
7762 if (ioh->fd_write) {
7763 FD_SET(ioh->fd, &wfds);
7764 if (ioh->fd > nfds)
7765 nfds = ioh->fd;
7769 tv.tv_sec = 0;
7770 #ifdef _WIN32
7771 tv.tv_usec = 0;
7772 #else
7773 tv.tv_usec = timeout * 1000;
7774 #endif
7775 #if defined(CONFIG_SLIRP)
7776 if (slirp_inited) {
7777 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7779 #endif
7780 moreio:
7781 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7782 if (ret > 0) {
7783 IOHandlerRecord **pioh;
7784 int more = 0;
7786 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7787 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7788 ioh->fd_read(ioh->opaque);
7789 more = 1;
7791 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7792 ioh->fd_write(ioh->opaque);
7793 more = 1;
7797 /* remove deleted IO handlers */
7798 pioh = &first_io_handler;
7799 while (*pioh) {
7800 ioh = *pioh;
7801 if (ioh->deleted) {
7802 *pioh = ioh->next;
7803 qemu_free(ioh);
7804 } else
7805 pioh = &ioh->next;
7807 if (more)
7808 goto moreio;
7810 #if defined(CONFIG_SLIRP)
7811 if (slirp_inited) {
7812 if (ret < 0) {
7813 FD_ZERO(&rfds);
7814 FD_ZERO(&wfds);
7815 FD_ZERO(&xfds);
7817 slirp_select_poll(&rfds, &wfds, &xfds);
7819 #endif
7820 virtio_net_poll();
7822 qemu_aio_poll();
7824 if (vm_running) {
7825 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7826 qemu_get_clock(vm_clock));
7827 /* run dma transfers, if any */
7828 DMA_run();
7831 /* real time timers */
7832 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7833 qemu_get_clock(rt_clock));
7835 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7836 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7837 qemu_rearm_alarm_timer(alarm_timer);
7840 /* Check bottom-halves last in case any of the earlier events triggered
7841 them. */
7842 qemu_bh_poll();
7846 static int main_loop(void)
7848 int ret, timeout;
7849 #ifdef CONFIG_PROFILER
7850 int64_t ti;
7851 #endif
7852 CPUState *env;
7855 if (kvm_enabled()) {
7856 kvm_main_loop();
7857 cpu_disable_ticks();
7858 return 0;
7861 cur_cpu = first_cpu;
7862 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7863 for(;;) {
7864 if (vm_running) {
7866 for(;;) {
7867 /* get next cpu */
7868 env = next_cpu;
7869 #ifdef CONFIG_PROFILER
7870 ti = profile_getclock();
7871 #endif
7872 ret = cpu_exec(env);
7873 #ifdef CONFIG_PROFILER
7874 qemu_time += profile_getclock() - ti;
7875 #endif
7876 next_cpu = env->next_cpu ?: first_cpu;
7877 if (event_pending) {
7878 ret = EXCP_INTERRUPT;
7879 event_pending = 0;
7880 break;
7882 if (ret == EXCP_HLT) {
7883 /* Give the next CPU a chance to run. */
7884 cur_cpu = env;
7885 continue;
7887 if (ret != EXCP_HALTED)
7888 break;
7889 /* all CPUs are halted ? */
7890 if (env == cur_cpu)
7891 break;
7893 cur_cpu = env;
7895 if (shutdown_requested) {
7896 ret = EXCP_INTERRUPT;
7897 break;
7899 if (reset_requested) {
7900 reset_requested = 0;
7901 qemu_system_reset();
7902 if (kvm_enabled())
7903 kvm_load_registers(env);
7904 ret = EXCP_INTERRUPT;
7906 if (powerdown_requested) {
7907 powerdown_requested = 0;
7908 qemu_system_powerdown();
7909 ret = EXCP_INTERRUPT;
7911 if (ret == EXCP_DEBUG) {
7912 vm_stop(EXCP_DEBUG);
7914 /* If all cpus are halted then wait until the next IRQ */
7915 /* XXX: use timeout computed from timers */
7916 if (ret == EXCP_HALTED)
7917 timeout = 10;
7918 else
7919 timeout = 0;
7920 } else {
7921 timeout = 10;
7923 #ifdef CONFIG_PROFILER
7924 ti = profile_getclock();
7925 #endif
7926 main_loop_wait(timeout);
7927 #ifdef CONFIG_PROFILER
7928 dev_time += profile_getclock() - ti;
7929 #endif
7931 cpu_disable_ticks();
7932 return ret;
7935 static void help(int exitcode)
7937 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7938 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7939 "usage: %s [options] [disk_image]\n"
7940 "\n"
7941 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7942 "\n"
7943 "Standard options:\n"
7944 "-M machine select emulated machine (-M ? for list)\n"
7945 "-cpu cpu select CPU (-cpu ? for list)\n"
7946 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7947 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7948 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7949 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7950 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7951 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7952 " [,cache=on|off][,boot=on|off]\n"
7953 " use 'file' as a drive image\n"
7954 "-mtdblock file use 'file' as on-board Flash memory image\n"
7955 "-sd file use 'file' as SecureDigital card image\n"
7956 "-pflash file use 'file' as a parallel flash image\n"
7957 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7958 "-snapshot write to temporary files instead of disk image files\n"
7959 #ifdef CONFIG_SDL
7960 "-no-frame open SDL window without a frame and window decorations\n"
7961 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7962 "-no-quit disable SDL window close capability\n"
7963 #endif
7964 #ifdef TARGET_I386
7965 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7966 #endif
7967 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7968 "-smp n set the number of CPUs to 'n' [default=1]\n"
7969 "-nographic disable graphical output and redirect serial I/Os to console\n"
7970 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7971 #ifndef _WIN32
7972 "-k language use keyboard layout (for example \"fr\" for French)\n"
7973 #endif
7974 #ifdef HAS_AUDIO
7975 "-audio-help print list of audio drivers and their options\n"
7976 "-soundhw c1,... enable audio support\n"
7977 " and only specified sound cards (comma separated list)\n"
7978 " use -soundhw ? to get the list of supported cards\n"
7979 " use -soundhw all to enable all of them\n"
7980 #endif
7981 "-localtime set the real time clock to local time [default=utc]\n"
7982 "-full-screen start in full screen\n"
7983 #ifdef TARGET_I386
7984 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7985 #endif
7986 "-usb enable the USB driver (will be the default soon)\n"
7987 "-usbdevice name add the host or guest USB device 'name'\n"
7988 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7989 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7990 #endif
7991 "-name string set the name of the guest\n"
7992 "\n"
7993 "Network options:\n"
7994 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7995 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7996 #ifdef CONFIG_SLIRP
7997 "-net user[,vlan=n][,hostname=host]\n"
7998 " connect the user mode network stack to VLAN 'n' and send\n"
7999 " hostname 'host' to DHCP clients\n"
8000 #endif
8001 #ifdef _WIN32
8002 "-net tap[,vlan=n],ifname=name\n"
8003 " connect the host TAP network interface to VLAN 'n'\n"
8004 #else
8005 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8006 " connect the host TAP network interface to VLAN 'n' and use the\n"
8007 " network scripts 'file' (default=%s)\n"
8008 " and 'dfile' (default=%s);\n"
8009 " use '[down]script=no' to disable script execution;\n"
8010 " use 'fd=h' to connect to an already opened TAP interface\n"
8011 #endif
8012 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8013 " connect the vlan 'n' to another VLAN using a socket connection\n"
8014 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8015 " connect the vlan 'n' to multicast maddr and port\n"
8016 "-net none use it alone to have zero network devices; if no -net option\n"
8017 " is provided, the default is '-net nic -net user'\n"
8018 "\n"
8019 #ifdef CONFIG_SLIRP
8020 "-tftp dir allow tftp access to files in dir [-net user]\n"
8021 "-bootp file advertise file in BOOTP replies\n"
8022 #ifndef _WIN32
8023 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8024 #endif
8025 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8026 " redirect TCP or UDP connections from host to guest [-net user]\n"
8027 #endif
8028 "\n"
8029 "Linux boot specific:\n"
8030 "-kernel bzImage use 'bzImage' as kernel image\n"
8031 "-append cmdline use 'cmdline' as kernel command line\n"
8032 "-initrd file use 'file' as initial ram disk\n"
8033 "\n"
8034 "Debug/Expert options:\n"
8035 "-monitor dev redirect the monitor to char device 'dev'\n"
8036 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8037 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8038 "-serial dev redirect the serial port to char device 'dev'\n"
8039 "-parallel dev redirect the parallel port to char device 'dev'\n"
8040 "-pidfile file Write PID to 'file'\n"
8041 "-S freeze CPU at startup (use 'c' to start execution)\n"
8042 "-s wait gdb connection to port\n"
8043 "-p port set gdb connection port [default=%s]\n"
8044 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8045 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8046 " translation (t=none or lba) (usually qemu can guess them)\n"
8047 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8048 #ifdef USE_KQEMU
8049 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8050 "-no-kqemu disable KQEMU kernel module usage\n"
8051 #endif
8052 #ifdef USE_KVM
8053 "-no-kvm disable KVM hardware virtualization\n"
8054 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8055 #endif
8056 #ifdef TARGET_I386
8057 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8058 " (default is CL-GD5446 PCI VGA)\n"
8059 "-no-acpi disable ACPI\n"
8060 #endif
8061 "-no-reboot exit instead of rebooting\n"
8062 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8063 "-vnc display start a VNC server on display\n"
8064 #ifndef _WIN32
8065 "-daemonize daemonize QEMU after initializing\n"
8066 #endif
8067 "-tdf inject timer interrupts that got lost\n"
8068 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8069 "-option-rom rom load a file, rom, into the option ROM space\n"
8070 #ifdef TARGET_SPARC
8071 "-prom-env variable=value set OpenBIOS nvram variables\n"
8072 #endif
8073 "-clock force the use of the given methods for timer alarm.\n"
8074 " To see what timers are available use -clock help\n"
8075 "-startdate select initial date of the clock\n"
8076 "\n"
8077 "During emulation, the following keys are useful:\n"
8078 "ctrl-alt-f toggle full screen\n"
8079 "ctrl-alt-n switch to virtual console 'n'\n"
8080 "ctrl-alt toggle mouse and keyboard grab\n"
8081 "\n"
8082 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8084 "qemu",
8085 DEFAULT_RAM_SIZE,
8086 #ifndef _WIN32
8087 DEFAULT_NETWORK_SCRIPT,
8088 DEFAULT_NETWORK_DOWN_SCRIPT,
8089 #endif
8090 DEFAULT_GDBSTUB_PORT,
8091 "/tmp/qemu.log");
8092 exit(exitcode);
8095 #define HAS_ARG 0x0001
8097 enum {
8098 QEMU_OPTION_h,
8100 QEMU_OPTION_M,
8101 QEMU_OPTION_cpu,
8102 QEMU_OPTION_fda,
8103 QEMU_OPTION_fdb,
8104 QEMU_OPTION_hda,
8105 QEMU_OPTION_hdb,
8106 QEMU_OPTION_hdc,
8107 QEMU_OPTION_hdd,
8108 QEMU_OPTION_drive,
8109 QEMU_OPTION_cdrom,
8110 QEMU_OPTION_mtdblock,
8111 QEMU_OPTION_sd,
8112 QEMU_OPTION_pflash,
8113 QEMU_OPTION_boot,
8114 QEMU_OPTION_snapshot,
8115 #ifdef TARGET_I386
8116 QEMU_OPTION_no_fd_bootchk,
8117 #endif
8118 QEMU_OPTION_m,
8119 QEMU_OPTION_nographic,
8120 QEMU_OPTION_portrait,
8121 #ifdef HAS_AUDIO
8122 QEMU_OPTION_audio_help,
8123 QEMU_OPTION_soundhw,
8124 #endif
8126 QEMU_OPTION_net,
8127 QEMU_OPTION_tftp,
8128 QEMU_OPTION_bootp,
8129 QEMU_OPTION_smb,
8130 QEMU_OPTION_redir,
8132 QEMU_OPTION_kernel,
8133 QEMU_OPTION_append,
8134 QEMU_OPTION_initrd,
8136 QEMU_OPTION_S,
8137 QEMU_OPTION_s,
8138 QEMU_OPTION_p,
8139 QEMU_OPTION_d,
8140 QEMU_OPTION_hdachs,
8141 QEMU_OPTION_L,
8142 QEMU_OPTION_bios,
8143 QEMU_OPTION_no_code_copy,
8144 QEMU_OPTION_k,
8145 QEMU_OPTION_localtime,
8146 QEMU_OPTION_cirrusvga,
8147 QEMU_OPTION_vmsvga,
8148 QEMU_OPTION_g,
8149 QEMU_OPTION_std_vga,
8150 QEMU_OPTION_echr,
8151 QEMU_OPTION_monitor,
8152 QEMU_OPTION_balloon,
8153 QEMU_OPTION_vmchannel,
8154 QEMU_OPTION_serial,
8155 QEMU_OPTION_parallel,
8156 QEMU_OPTION_loadvm,
8157 QEMU_OPTION_full_screen,
8158 QEMU_OPTION_no_frame,
8159 QEMU_OPTION_alt_grab,
8160 QEMU_OPTION_no_quit,
8161 QEMU_OPTION_pidfile,
8162 QEMU_OPTION_no_kqemu,
8163 QEMU_OPTION_kernel_kqemu,
8164 QEMU_OPTION_win2k_hack,
8165 QEMU_OPTION_usb,
8166 QEMU_OPTION_usbdevice,
8167 QEMU_OPTION_smp,
8168 QEMU_OPTION_vnc,
8169 QEMU_OPTION_no_acpi,
8170 QEMU_OPTION_no_kvm,
8171 QEMU_OPTION_no_kvm_irqchip,
8172 QEMU_OPTION_no_reboot,
8173 QEMU_OPTION_show_cursor,
8174 QEMU_OPTION_daemonize,
8175 QEMU_OPTION_option_rom,
8176 QEMU_OPTION_semihosting,
8177 QEMU_OPTION_cpu_vendor,
8178 QEMU_OPTION_name,
8179 QEMU_OPTION_prom_env,
8180 QEMU_OPTION_old_param,
8181 QEMU_OPTION_clock,
8182 QEMU_OPTION_startdate,
8183 QEMU_OPTION_translation,
8184 QEMU_OPTION_incoming,
8185 QEMU_OPTION_tdf,
8186 QEMU_OPTION_kvm_shadow_memory,
8189 typedef struct QEMUOption {
8190 const char *name;
8191 int flags;
8192 int index;
8193 } QEMUOption;
8195 const QEMUOption qemu_options[] = {
8196 { "h", 0, QEMU_OPTION_h },
8197 { "help", 0, QEMU_OPTION_h },
8199 { "M", HAS_ARG, QEMU_OPTION_M },
8200 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8201 { "fda", HAS_ARG, QEMU_OPTION_fda },
8202 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8203 { "hda", HAS_ARG, QEMU_OPTION_hda },
8204 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8205 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8206 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8207 { "drive", HAS_ARG, QEMU_OPTION_drive },
8208 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8209 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8210 { "sd", HAS_ARG, QEMU_OPTION_sd },
8211 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8212 { "boot", HAS_ARG, QEMU_OPTION_boot },
8213 { "snapshot", 0, QEMU_OPTION_snapshot },
8214 #ifdef TARGET_I386
8215 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8216 #endif
8217 { "m", HAS_ARG, QEMU_OPTION_m },
8218 { "nographic", 0, QEMU_OPTION_nographic },
8219 { "portrait", 0, QEMU_OPTION_portrait },
8220 { "k", HAS_ARG, QEMU_OPTION_k },
8221 #ifdef HAS_AUDIO
8222 { "audio-help", 0, QEMU_OPTION_audio_help },
8223 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8224 #endif
8226 { "net", HAS_ARG, QEMU_OPTION_net},
8227 #ifdef CONFIG_SLIRP
8228 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8229 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8230 #ifndef _WIN32
8231 { "smb", HAS_ARG, QEMU_OPTION_smb },
8232 #endif
8233 { "redir", HAS_ARG, QEMU_OPTION_redir },
8234 #endif
8236 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8237 { "append", HAS_ARG, QEMU_OPTION_append },
8238 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8240 { "S", 0, QEMU_OPTION_S },
8241 { "s", 0, QEMU_OPTION_s },
8242 { "p", HAS_ARG, QEMU_OPTION_p },
8243 { "d", HAS_ARG, QEMU_OPTION_d },
8244 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8245 { "L", HAS_ARG, QEMU_OPTION_L },
8246 { "bios", HAS_ARG, QEMU_OPTION_bios },
8247 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8248 #ifdef USE_KQEMU
8249 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8250 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8251 #endif
8252 #ifdef USE_KVM
8253 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8254 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8255 #endif
8256 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8257 { "g", 1, QEMU_OPTION_g },
8258 #endif
8259 { "localtime", 0, QEMU_OPTION_localtime },
8260 { "std-vga", 0, QEMU_OPTION_std_vga },
8261 { "monitor", 1, QEMU_OPTION_monitor },
8262 { "balloon", 1, QEMU_OPTION_balloon },
8263 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8264 { "echr", HAS_ARG, QEMU_OPTION_echr },
8265 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8266 { "serial", HAS_ARG, QEMU_OPTION_serial },
8267 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8268 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8269 { "incoming", 1, QEMU_OPTION_incoming },
8270 { "full-screen", 0, QEMU_OPTION_full_screen },
8271 #ifdef CONFIG_SDL
8272 { "no-frame", 0, QEMU_OPTION_no_frame },
8273 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8274 { "no-quit", 0, QEMU_OPTION_no_quit },
8275 #endif
8276 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8277 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8278 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8279 { "smp", HAS_ARG, QEMU_OPTION_smp },
8280 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8282 /* temporary options */
8283 { "usb", 0, QEMU_OPTION_usb },
8284 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8285 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8286 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8287 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8288 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8289 { "daemonize", 0, QEMU_OPTION_daemonize },
8290 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8291 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8292 { "semihosting", 0, QEMU_OPTION_semihosting },
8293 #endif
8294 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8295 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8296 { "name", HAS_ARG, QEMU_OPTION_name },
8297 #if defined(TARGET_SPARC)
8298 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8299 #endif
8300 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8301 #if defined(TARGET_ARM)
8302 { "old-param", 0, QEMU_OPTION_old_param },
8303 #endif
8304 { "clock", HAS_ARG, QEMU_OPTION_clock },
8305 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8306 { NULL },
8309 /* password input */
8311 int qemu_key_check(BlockDriverState *bs, const char *name)
8313 char password[256];
8314 int i;
8316 if (!bdrv_is_encrypted(bs))
8317 return 0;
8319 term_printf("%s is encrypted.\n", name);
8320 for(i = 0; i < 3; i++) {
8321 monitor_readline("Password: ", 1, password, sizeof(password));
8322 if (bdrv_set_key(bs, password) == 0)
8323 return 0;
8324 term_printf("invalid password\n");
8326 return -EPERM;
8329 static BlockDriverState *get_bdrv(int index)
8331 if (index > nb_drives)
8332 return NULL;
8333 return drives_table[index].bdrv;
8336 static void read_passwords(void)
8338 BlockDriverState *bs;
8339 int i;
8341 for(i = 0; i < 6; i++) {
8342 bs = get_bdrv(i);
8343 if (bs)
8344 qemu_key_check(bs, bdrv_get_device_name(bs));
8348 /* XXX: currently we cannot use simultaneously different CPUs */
8349 static void register_machines(void)
8351 #if defined(TARGET_I386)
8352 qemu_register_machine(&pc_machine);
8353 qemu_register_machine(&isapc_machine);
8354 #elif defined(TARGET_PPC)
8355 qemu_register_machine(&heathrow_machine);
8356 qemu_register_machine(&core99_machine);
8357 qemu_register_machine(&prep_machine);
8358 qemu_register_machine(&ref405ep_machine);
8359 qemu_register_machine(&taihu_machine);
8360 qemu_register_machine(&bamboo_machine);
8361 #elif defined(TARGET_MIPS)
8362 qemu_register_machine(&mips_machine);
8363 qemu_register_machine(&mips_malta_machine);
8364 qemu_register_machine(&mips_pica61_machine);
8365 qemu_register_machine(&mips_mipssim_machine);
8366 #elif defined(TARGET_SPARC)
8367 #ifdef TARGET_SPARC64
8368 qemu_register_machine(&sun4u_machine);
8369 #else
8370 qemu_register_machine(&ss5_machine);
8371 qemu_register_machine(&ss10_machine);
8372 qemu_register_machine(&ss600mp_machine);
8373 qemu_register_machine(&ss20_machine);
8374 qemu_register_machine(&ss2_machine);
8375 qemu_register_machine(&ss1000_machine);
8376 qemu_register_machine(&ss2000_machine);
8377 #endif
8378 #elif defined(TARGET_ARM)
8379 qemu_register_machine(&integratorcp_machine);
8380 qemu_register_machine(&versatilepb_machine);
8381 qemu_register_machine(&versatileab_machine);
8382 qemu_register_machine(&realview_machine);
8383 qemu_register_machine(&akitapda_machine);
8384 qemu_register_machine(&spitzpda_machine);
8385 qemu_register_machine(&borzoipda_machine);
8386 qemu_register_machine(&terrierpda_machine);
8387 qemu_register_machine(&palmte_machine);
8388 qemu_register_machine(&lm3s811evb_machine);
8389 qemu_register_machine(&lm3s6965evb_machine);
8390 qemu_register_machine(&connex_machine);
8391 qemu_register_machine(&verdex_machine);
8392 qemu_register_machine(&mainstone2_machine);
8393 #elif defined(TARGET_SH4)
8394 qemu_register_machine(&shix_machine);
8395 qemu_register_machine(&r2d_machine);
8396 #elif defined(TARGET_ALPHA)
8397 /* XXX: TODO */
8398 #elif defined(TARGET_M68K)
8399 qemu_register_machine(&mcf5208evb_machine);
8400 qemu_register_machine(&an5206_machine);
8401 qemu_register_machine(&dummy_m68k_machine);
8402 #elif defined(TARGET_CRIS)
8403 qemu_register_machine(&bareetraxfs_machine);
8404 #elif defined(TARGET_IA64)
8405 qemu_register_machine(&ipf_machine);
8406 #else
8407 #error unsupported CPU
8408 #endif
8411 #ifdef HAS_AUDIO
8412 struct soundhw soundhw[] = {
8413 #ifdef HAS_AUDIO_CHOICE
8414 #ifdef TARGET_I386
8416 "pcspk",
8417 "PC speaker",
8420 { .init_isa = pcspk_audio_init }
8422 #endif
8424 "sb16",
8425 "Creative Sound Blaster 16",
8428 { .init_isa = SB16_init }
8431 #ifdef CONFIG_ADLIB
8433 "adlib",
8434 #ifdef HAS_YMF262
8435 "Yamaha YMF262 (OPL3)",
8436 #else
8437 "Yamaha YM3812 (OPL2)",
8438 #endif
8441 { .init_isa = Adlib_init }
8443 #endif
8445 #ifdef CONFIG_GUS
8447 "gus",
8448 "Gravis Ultrasound GF1",
8451 { .init_isa = GUS_init }
8453 #endif
8455 #ifdef CONFIG_AC97
8457 "ac97",
8458 "Intel 82801AA AC97 Audio",
8461 { .init_pci = ac97_init }
8463 #endif
8466 "es1370",
8467 "ENSONIQ AudioPCI ES1370",
8470 { .init_pci = es1370_init }
8472 #endif
8474 { NULL, NULL, 0, 0, { NULL } }
8477 static void select_soundhw (const char *optarg)
8479 struct soundhw *c;
8481 if (*optarg == '?') {
8482 show_valid_cards:
8484 printf ("Valid sound card names (comma separated):\n");
8485 for (c = soundhw; c->name; ++c) {
8486 printf ("%-11s %s\n", c->name, c->descr);
8488 printf ("\n-soundhw all will enable all of the above\n");
8489 exit (*optarg != '?');
8491 else {
8492 size_t l;
8493 const char *p;
8494 char *e;
8495 int bad_card = 0;
8497 if (!strcmp (optarg, "all")) {
8498 for (c = soundhw; c->name; ++c) {
8499 c->enabled = 1;
8501 return;
8504 p = optarg;
8505 while (*p) {
8506 e = strchr (p, ',');
8507 l = !e ? strlen (p) : (size_t) (e - p);
8509 for (c = soundhw; c->name; ++c) {
8510 if (!strncmp (c->name, p, l)) {
8511 c->enabled = 1;
8512 break;
8516 if (!c->name) {
8517 if (l > 80) {
8518 fprintf (stderr,
8519 "Unknown sound card name (too big to show)\n");
8521 else {
8522 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8523 (int) l, p);
8525 bad_card = 1;
8527 p += l + (e != NULL);
8530 if (bad_card)
8531 goto show_valid_cards;
8534 #endif
8536 #ifdef _WIN32
8537 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8539 exit(STATUS_CONTROL_C_EXIT);
8540 return TRUE;
8542 #endif
8544 #define MAX_NET_CLIENTS 32
8546 static int saved_argc;
8547 static char **saved_argv;
8549 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8551 *argc = saved_argc;
8552 *argv = saved_argv;
8553 *opt_daemonize = daemonize;
8554 *opt_incoming = incoming;
8557 int main(int argc, char **argv)
8559 #ifdef CONFIG_GDBSTUB
8560 int use_gdbstub;
8561 const char *gdbstub_port;
8562 #endif
8563 uint32_t boot_devices_bitmap = 0;
8564 int i;
8565 int snapshot, linux_boot, net_boot;
8566 const char *initrd_filename;
8567 const char *kernel_filename, *kernel_cmdline;
8568 const char *boot_devices = "";
8569 DisplayState *ds = &display_state;
8570 int cyls, heads, secs, translation;
8571 char net_clients[MAX_NET_CLIENTS][256];
8572 int nb_net_clients;
8573 int hda_index;
8574 int optind;
8575 const char *r, *optarg;
8576 CharDriverState *monitor_hd;
8577 char monitor_device[128];
8578 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8579 int vmchannel_device_index;
8580 char serial_devices[MAX_SERIAL_PORTS][128];
8581 int serial_device_index;
8582 char parallel_devices[MAX_PARALLEL_PORTS][128];
8583 int parallel_device_index;
8584 const char *loadvm = NULL;
8585 QEMUMachine *machine;
8586 const char *cpu_model;
8587 char usb_devices[MAX_USB_CMDLINE][128];
8588 int usb_devices_index;
8589 int fds[2];
8590 const char *pid_file = NULL;
8591 VLANState *vlan;
8593 saved_argc = argc;
8594 saved_argv = argv;
8596 LIST_INIT (&vm_change_state_head);
8597 #ifndef _WIN32
8599 struct sigaction act;
8600 sigfillset(&act.sa_mask);
8601 act.sa_flags = 0;
8602 act.sa_handler = SIG_IGN;
8603 sigaction(SIGPIPE, &act, NULL);
8605 #else
8606 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8607 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8608 QEMU to run on a single CPU */
8610 HANDLE h;
8611 DWORD mask, smask;
8612 int i;
8613 h = GetCurrentProcess();
8614 if (GetProcessAffinityMask(h, &mask, &smask)) {
8615 for(i = 0; i < 32; i++) {
8616 if (mask & (1 << i))
8617 break;
8619 if (i != 32) {
8620 mask = 1 << i;
8621 SetProcessAffinityMask(h, mask);
8625 #endif
8627 register_machines();
8628 machine = first_machine;
8629 cpu_model = NULL;
8630 initrd_filename = NULL;
8631 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8632 vga_ram_size = VGA_RAM_SIZE;
8633 #ifdef CONFIG_GDBSTUB
8634 use_gdbstub = 0;
8635 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8636 #endif
8637 snapshot = 0;
8638 nographic = 0;
8639 kernel_filename = NULL;
8640 kernel_cmdline = "";
8641 cyls = heads = secs = 0;
8642 translation = BIOS_ATA_TRANSLATION_AUTO;
8643 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8645 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8646 vmchannel_devices[i][0] = '\0';
8647 vmchannel_device_index = 0;
8649 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8650 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8651 serial_devices[i][0] = '\0';
8652 serial_device_index = 0;
8654 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8655 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8656 parallel_devices[i][0] = '\0';
8657 parallel_device_index = 0;
8659 usb_devices_index = 0;
8661 nb_net_clients = 0;
8662 nb_drives = 0;
8663 nb_drives_opt = 0;
8664 hda_index = -1;
8666 nb_nics = 0;
8667 /* default mac address of the first network interface */
8669 optind = 1;
8670 for(;;) {
8671 if (optind >= argc)
8672 break;
8673 r = argv[optind];
8674 if (r[0] != '-') {
8675 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8676 } else {
8677 const QEMUOption *popt;
8679 optind++;
8680 /* Treat --foo the same as -foo. */
8681 if (r[1] == '-')
8682 r++;
8683 popt = qemu_options;
8684 for(;;) {
8685 if (!popt->name) {
8686 fprintf(stderr, "%s: invalid option -- '%s'\n",
8687 argv[0], r);
8688 exit(1);
8690 if (!strcmp(popt->name, r + 1))
8691 break;
8692 popt++;
8694 if (popt->flags & HAS_ARG) {
8695 if (optind >= argc) {
8696 fprintf(stderr, "%s: option '%s' requires an argument\n",
8697 argv[0], r);
8698 exit(1);
8700 optarg = argv[optind++];
8701 } else {
8702 optarg = NULL;
8705 switch(popt->index) {
8706 case QEMU_OPTION_M:
8707 machine = find_machine(optarg);
8708 if (!machine) {
8709 QEMUMachine *m;
8710 printf("Supported machines are:\n");
8711 for(m = first_machine; m != NULL; m = m->next) {
8712 printf("%-10s %s%s\n",
8713 m->name, m->desc,
8714 m == first_machine ? " (default)" : "");
8716 exit(*optarg != '?');
8718 break;
8719 case QEMU_OPTION_cpu:
8720 /* hw initialization will check this */
8721 if (*optarg == '?') {
8722 /* XXX: implement xxx_cpu_list for targets that still miss it */
8723 #if defined(cpu_list)
8724 cpu_list(stdout, &fprintf);
8725 #endif
8726 exit(0);
8727 } else {
8728 cpu_model = optarg;
8730 break;
8731 case QEMU_OPTION_initrd:
8732 initrd_filename = optarg;
8733 break;
8734 case QEMU_OPTION_hda:
8735 if (cyls == 0)
8736 hda_index = drive_add(optarg, HD_ALIAS, 0);
8737 else
8738 hda_index = drive_add(optarg, HD_ALIAS
8739 ",cyls=%d,heads=%d,secs=%d%s",
8740 0, cyls, heads, secs,
8741 translation == BIOS_ATA_TRANSLATION_LBA ?
8742 ",trans=lba" :
8743 translation == BIOS_ATA_TRANSLATION_NONE ?
8744 ",trans=none" : "");
8745 break;
8746 case QEMU_OPTION_hdb:
8747 case QEMU_OPTION_hdc:
8748 case QEMU_OPTION_hdd:
8749 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8750 break;
8751 case QEMU_OPTION_drive:
8752 drive_add(NULL, "%s", optarg);
8753 break;
8754 case QEMU_OPTION_mtdblock:
8755 drive_add(optarg, MTD_ALIAS);
8756 break;
8757 case QEMU_OPTION_sd:
8758 drive_add(optarg, SD_ALIAS);
8759 break;
8760 case QEMU_OPTION_pflash:
8761 drive_add(optarg, PFLASH_ALIAS);
8762 break;
8763 case QEMU_OPTION_snapshot:
8764 snapshot = 1;
8765 break;
8766 case QEMU_OPTION_hdachs:
8768 const char *p;
8769 p = optarg;
8770 cyls = strtol(p, (char **)&p, 0);
8771 if (cyls < 1 || cyls > 16383)
8772 goto chs_fail;
8773 if (*p != ',')
8774 goto chs_fail;
8775 p++;
8776 heads = strtol(p, (char **)&p, 0);
8777 if (heads < 1 || heads > 16)
8778 goto chs_fail;
8779 if (*p != ',')
8780 goto chs_fail;
8781 p++;
8782 secs = strtol(p, (char **)&p, 0);
8783 if (secs < 1 || secs > 63)
8784 goto chs_fail;
8785 if (*p == ',') {
8786 p++;
8787 if (!strcmp(p, "none"))
8788 translation = BIOS_ATA_TRANSLATION_NONE;
8789 else if (!strcmp(p, "lba"))
8790 translation = BIOS_ATA_TRANSLATION_LBA;
8791 else if (!strcmp(p, "auto"))
8792 translation = BIOS_ATA_TRANSLATION_AUTO;
8793 else
8794 goto chs_fail;
8795 } else if (*p != '\0') {
8796 chs_fail:
8797 fprintf(stderr, "qemu: invalid physical CHS format\n");
8798 exit(1);
8800 if (hda_index != -1)
8801 snprintf(drives_opt[hda_index].opt,
8802 sizeof(drives_opt[hda_index].opt),
8803 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8804 0, cyls, heads, secs,
8805 translation == BIOS_ATA_TRANSLATION_LBA ?
8806 ",trans=lba" :
8807 translation == BIOS_ATA_TRANSLATION_NONE ?
8808 ",trans=none" : "");
8810 break;
8811 case QEMU_OPTION_nographic:
8812 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8813 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8814 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8815 nographic = 1;
8816 break;
8817 case QEMU_OPTION_portrait:
8818 graphic_rotate = 1;
8819 break;
8820 case QEMU_OPTION_kernel:
8821 kernel_filename = optarg;
8822 break;
8823 case QEMU_OPTION_append:
8824 kernel_cmdline = optarg;
8825 break;
8826 case QEMU_OPTION_cdrom:
8827 drive_add(optarg, CDROM_ALIAS);
8828 break;
8829 case QEMU_OPTION_boot:
8830 boot_devices = optarg;
8831 /* We just do some generic consistency checks */
8833 /* Could easily be extended to 64 devices if needed */
8834 const char *p;
8836 boot_devices_bitmap = 0;
8837 for (p = boot_devices; *p != '\0'; p++) {
8838 /* Allowed boot devices are:
8839 * a b : floppy disk drives
8840 * c ... f : IDE disk drives
8841 * g ... m : machine implementation dependant drives
8842 * n ... p : network devices
8843 * It's up to each machine implementation to check
8844 * if the given boot devices match the actual hardware
8845 * implementation and firmware features.
8847 if (*p < 'a' || *p > 'q') {
8848 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8849 exit(1);
8851 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8852 fprintf(stderr,
8853 "Boot device '%c' was given twice\n",*p);
8854 exit(1);
8856 boot_devices_bitmap |= 1 << (*p - 'a');
8859 break;
8860 case QEMU_OPTION_fda:
8861 case QEMU_OPTION_fdb:
8862 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8863 break;
8864 #ifdef TARGET_I386
8865 case QEMU_OPTION_no_fd_bootchk:
8866 fd_bootchk = 0;
8867 break;
8868 #endif
8869 case QEMU_OPTION_no_code_copy:
8870 code_copy_enabled = 0;
8871 break;
8872 case QEMU_OPTION_net:
8873 if (nb_net_clients >= MAX_NET_CLIENTS) {
8874 fprintf(stderr, "qemu: too many network clients\n");
8875 exit(1);
8877 pstrcpy(net_clients[nb_net_clients],
8878 sizeof(net_clients[0]),
8879 optarg);
8880 nb_net_clients++;
8881 break;
8882 #ifdef CONFIG_SLIRP
8883 case QEMU_OPTION_tftp:
8884 tftp_prefix = optarg;
8885 break;
8886 case QEMU_OPTION_bootp:
8887 bootp_filename = optarg;
8888 break;
8889 #ifndef _WIN32
8890 case QEMU_OPTION_smb:
8891 net_slirp_smb(optarg);
8892 break;
8893 #endif
8894 case QEMU_OPTION_redir:
8895 net_slirp_redir(optarg);
8896 break;
8897 #endif
8898 #ifdef HAS_AUDIO
8899 case QEMU_OPTION_audio_help:
8900 AUD_help ();
8901 exit (0);
8902 break;
8903 case QEMU_OPTION_soundhw:
8904 select_soundhw (optarg);
8905 break;
8906 #endif
8907 case QEMU_OPTION_h:
8908 help(0);
8909 break;
8910 case QEMU_OPTION_m:
8911 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
8912 if (ram_size <= 0)
8913 help(1);
8914 if (ram_size > PHYS_RAM_MAX_SIZE) {
8915 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8916 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8917 exit(1);
8919 break;
8920 case QEMU_OPTION_d:
8922 int mask;
8923 CPULogItem *item;
8925 mask = cpu_str_to_log_mask(optarg);
8926 if (!mask) {
8927 printf("Log items (comma separated):\n");
8928 for(item = cpu_log_items; item->mask != 0; item++) {
8929 printf("%-10s %s\n", item->name, item->help);
8931 exit(1);
8933 cpu_set_log(mask);
8935 break;
8936 #ifdef CONFIG_GDBSTUB
8937 case QEMU_OPTION_s:
8938 use_gdbstub = 1;
8939 break;
8940 case QEMU_OPTION_p:
8941 gdbstub_port = optarg;
8942 break;
8943 #endif
8944 case QEMU_OPTION_L:
8945 bios_dir = optarg;
8946 break;
8947 case QEMU_OPTION_bios:
8948 bios_name = optarg;
8949 break;
8950 case QEMU_OPTION_S:
8951 autostart = 0;
8952 break;
8953 case QEMU_OPTION_k:
8954 keyboard_layout = optarg;
8955 break;
8956 case QEMU_OPTION_localtime:
8957 rtc_utc = 0;
8958 break;
8959 case QEMU_OPTION_cirrusvga:
8960 cirrus_vga_enabled = 1;
8961 vmsvga_enabled = 0;
8962 break;
8963 case QEMU_OPTION_vmsvga:
8964 cirrus_vga_enabled = 0;
8965 vmsvga_enabled = 1;
8966 break;
8967 case QEMU_OPTION_std_vga:
8968 cirrus_vga_enabled = 0;
8969 vmsvga_enabled = 0;
8970 break;
8971 case QEMU_OPTION_g:
8973 const char *p;
8974 int w, h, depth;
8975 p = optarg;
8976 w = strtol(p, (char **)&p, 10);
8977 if (w <= 0) {
8978 graphic_error:
8979 fprintf(stderr, "qemu: invalid resolution or depth\n");
8980 exit(1);
8982 if (*p != 'x')
8983 goto graphic_error;
8984 p++;
8985 h = strtol(p, (char **)&p, 10);
8986 if (h <= 0)
8987 goto graphic_error;
8988 if (*p == 'x') {
8989 p++;
8990 depth = strtol(p, (char **)&p, 10);
8991 if (depth != 8 && depth != 15 && depth != 16 &&
8992 depth != 24 && depth != 32)
8993 goto graphic_error;
8994 } else if (*p == '\0') {
8995 depth = graphic_depth;
8996 } else {
8997 goto graphic_error;
9000 graphic_width = w;
9001 graphic_height = h;
9002 graphic_depth = depth;
9004 break;
9005 case QEMU_OPTION_echr:
9007 char *r;
9008 term_escape_char = strtol(optarg, &r, 0);
9009 if (r == optarg)
9010 printf("Bad argument to echr\n");
9011 break;
9013 case QEMU_OPTION_monitor:
9014 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9015 break;
9016 case QEMU_OPTION_balloon:
9017 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9018 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9019 exit(1);
9021 if (balloon_used) {
9022 fprintf(stderr, "qemu: only one balloon device can be used\n");
9023 exit(1);
9025 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9026 vmchannel_device_index++;
9027 balloon_used = 1;
9028 break;
9029 case QEMU_OPTION_vmchannel:
9030 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9031 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9032 exit(1);
9034 pstrcpy(vmchannel_devices[vmchannel_device_index],
9035 sizeof(vmchannel_devices[0]), optarg);
9036 vmchannel_device_index++;
9037 break;
9038 case QEMU_OPTION_serial:
9039 if (serial_device_index >= MAX_SERIAL_PORTS) {
9040 fprintf(stderr, "qemu: too many serial ports\n");
9041 exit(1);
9043 pstrcpy(serial_devices[serial_device_index],
9044 sizeof(serial_devices[0]), optarg);
9045 serial_device_index++;
9046 break;
9047 case QEMU_OPTION_parallel:
9048 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9049 fprintf(stderr, "qemu: too many parallel ports\n");
9050 exit(1);
9052 pstrcpy(parallel_devices[parallel_device_index],
9053 sizeof(parallel_devices[0]), optarg);
9054 parallel_device_index++;
9055 break;
9056 case QEMU_OPTION_loadvm:
9057 loadvm = optarg;
9058 break;
9059 case QEMU_OPTION_incoming:
9060 incoming = optarg;
9061 break;
9062 case QEMU_OPTION_full_screen:
9063 full_screen = 1;
9064 break;
9065 #ifdef CONFIG_SDL
9066 case QEMU_OPTION_no_frame:
9067 no_frame = 1;
9068 break;
9069 case QEMU_OPTION_alt_grab:
9070 alt_grab = 1;
9071 break;
9072 case QEMU_OPTION_no_quit:
9073 no_quit = 1;
9074 break;
9075 #endif
9076 case QEMU_OPTION_pidfile:
9077 pid_file = optarg;
9078 break;
9079 #ifdef TARGET_I386
9080 case QEMU_OPTION_win2k_hack:
9081 win2k_install_hack = 1;
9082 break;
9083 #endif
9084 #ifdef USE_KQEMU
9085 case QEMU_OPTION_no_kqemu:
9086 kqemu_allowed = 0;
9087 break;
9088 case QEMU_OPTION_kernel_kqemu:
9089 kqemu_allowed = 2;
9090 break;
9091 #endif
9092 #ifdef USE_KVM
9093 case QEMU_OPTION_no_kvm:
9094 kvm_allowed = 0;
9095 break;
9096 case QEMU_OPTION_no_kvm_irqchip: {
9097 extern int kvm_irqchip;
9098 kvm_irqchip = 0;
9099 break;
9101 #endif
9102 case QEMU_OPTION_usb:
9103 usb_enabled = 1;
9104 break;
9105 case QEMU_OPTION_usbdevice:
9106 usb_enabled = 1;
9107 if (usb_devices_index >= MAX_USB_CMDLINE) {
9108 fprintf(stderr, "Too many USB devices\n");
9109 exit(1);
9111 pstrcpy(usb_devices[usb_devices_index],
9112 sizeof(usb_devices[usb_devices_index]),
9113 optarg);
9114 usb_devices_index++;
9115 break;
9116 case QEMU_OPTION_smp:
9117 smp_cpus = atoi(optarg);
9118 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9119 fprintf(stderr, "Invalid number of CPUs\n");
9120 exit(1);
9122 break;
9123 case QEMU_OPTION_vnc:
9124 vnc_display = optarg;
9125 break;
9126 case QEMU_OPTION_no_acpi:
9127 acpi_enabled = 0;
9128 break;
9129 case QEMU_OPTION_no_reboot:
9130 no_reboot = 1;
9131 break;
9132 case QEMU_OPTION_show_cursor:
9133 cursor_hide = 0;
9134 break;
9135 case QEMU_OPTION_daemonize:
9136 daemonize = 1;
9137 break;
9138 case QEMU_OPTION_option_rom:
9139 if (nb_option_roms >= MAX_OPTION_ROMS) {
9140 fprintf(stderr, "Too many option ROMs\n");
9141 exit(1);
9143 option_rom[nb_option_roms] = optarg;
9144 nb_option_roms++;
9145 break;
9146 case QEMU_OPTION_semihosting:
9147 semihosting_enabled = 1;
9148 break;
9149 case QEMU_OPTION_tdf:
9150 time_drift_fix = 1;
9151 break;
9152 case QEMU_OPTION_kvm_shadow_memory:
9153 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9154 break;
9155 case QEMU_OPTION_name:
9156 qemu_name = optarg;
9157 break;
9158 #ifdef TARGET_SPARC
9159 case QEMU_OPTION_prom_env:
9160 if (nb_prom_envs >= MAX_PROM_ENVS) {
9161 fprintf(stderr, "Too many prom variables\n");
9162 exit(1);
9164 prom_envs[nb_prom_envs] = optarg;
9165 nb_prom_envs++;
9166 break;
9167 #endif
9168 case QEMU_OPTION_cpu_vendor:
9169 cpu_vendor_string = optarg;
9170 break;
9171 #ifdef TARGET_ARM
9172 case QEMU_OPTION_old_param:
9173 old_param = 1;
9174 break;
9175 #endif
9176 case QEMU_OPTION_clock:
9177 configure_alarms(optarg);
9178 break;
9179 case QEMU_OPTION_startdate:
9181 struct tm tm;
9182 if (!strcmp(optarg, "now")) {
9183 rtc_start_date = -1;
9184 } else {
9185 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9186 &tm.tm_year,
9187 &tm.tm_mon,
9188 &tm.tm_mday,
9189 &tm.tm_hour,
9190 &tm.tm_min,
9191 &tm.tm_sec) == 6) {
9192 /* OK */
9193 } else if (sscanf(optarg, "%d-%d-%d",
9194 &tm.tm_year,
9195 &tm.tm_mon,
9196 &tm.tm_mday) == 3) {
9197 tm.tm_hour = 0;
9198 tm.tm_min = 0;
9199 tm.tm_sec = 0;
9200 } else {
9201 goto date_fail;
9203 tm.tm_year -= 1900;
9204 tm.tm_mon--;
9205 rtc_start_date = mktimegm(&tm);
9206 if (rtc_start_date == -1) {
9207 date_fail:
9208 fprintf(stderr, "Invalid date format. Valid format are:\n"
9209 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9210 exit(1);
9214 break;
9219 #ifndef _WIN32
9220 if (daemonize) {
9221 pid_t pid;
9223 if (pipe(fds) == -1)
9224 exit(1);
9226 pid = fork();
9227 if (pid > 0) {
9228 uint8_t status;
9229 ssize_t len;
9231 close(fds[1]);
9233 again:
9234 len = read(fds[0], &status, 1);
9235 if (len == -1 && (errno == EINTR))
9236 goto again;
9238 if (len != 1)
9239 exit(1);
9240 else if (status == 1) {
9241 fprintf(stderr, "Could not acquire pidfile\n");
9242 exit(1);
9243 } else
9244 exit(0);
9245 } else if (pid < 0)
9246 exit(1);
9248 setsid();
9250 pid = fork();
9251 if (pid > 0)
9252 exit(0);
9253 else if (pid < 0)
9254 exit(1);
9256 umask(027);
9258 signal(SIGTSTP, SIG_IGN);
9259 signal(SIGTTOU, SIG_IGN);
9260 signal(SIGTTIN, SIG_IGN);
9262 #endif
9264 #if USE_KVM
9265 if (kvm_enabled()) {
9266 if (kvm_qemu_init() < 0) {
9267 extern int kvm_allowed;
9268 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9269 kvm_allowed = 0;
9272 #endif
9274 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9275 if (daemonize) {
9276 uint8_t status = 1;
9277 write(fds[1], &status, 1);
9278 } else
9279 fprintf(stderr, "Could not acquire pid file\n");
9280 exit(1);
9283 #ifdef USE_KQEMU
9284 if (smp_cpus > 1)
9285 kqemu_allowed = 0;
9286 #endif
9287 linux_boot = (kernel_filename != NULL);
9288 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9290 /* XXX: this should not be: some embedded targets just have flash */
9291 if (!linux_boot && net_boot == 0 &&
9292 nb_drives_opt == 0)
9293 help(1);
9295 /* boot to floppy or the default cd if no hard disk defined yet */
9296 if (!boot_devices[0]) {
9297 boot_devices = "cad";
9299 setvbuf(stdout, NULL, _IOLBF, 0);
9301 init_timers();
9302 init_timer_alarm();
9303 qemu_aio_init();
9305 #ifdef _WIN32
9306 socket_init();
9307 #endif
9309 /* init network clients */
9310 if (nb_net_clients == 0) {
9311 /* if no clients, we use a default config */
9312 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9313 "nic");
9314 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9315 "user");
9316 nb_net_clients = 2;
9319 for(i = 0;i < nb_net_clients; i++) {
9320 if (net_client_init(net_clients[i]) < 0)
9321 exit(1);
9323 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9324 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9325 continue;
9326 if (vlan->nb_guest_devs == 0) {
9327 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9328 exit(1);
9330 if (vlan->nb_host_devs == 0)
9331 fprintf(stderr,
9332 "Warning: vlan %d is not connected to host network\n",
9333 vlan->id);
9336 #ifdef TARGET_I386
9337 /* XXX: this should be moved in the PC machine instantiation code */
9338 if (net_boot != 0) {
9339 int netroms = 0;
9340 for (i = 0; i < nb_nics && i < 4; i++) {
9341 const char *model = nd_table[i].model;
9342 char buf[1024];
9343 if (net_boot & (1 << i)) {
9344 if (model == NULL)
9345 model = "rtl8139";
9346 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9347 if (get_image_size(buf) > 0) {
9348 if (nb_option_roms >= MAX_OPTION_ROMS) {
9349 fprintf(stderr, "Too many option ROMs\n");
9350 exit(1);
9352 option_rom[nb_option_roms] = strdup(buf);
9353 nb_option_roms++;
9354 netroms++;
9358 if (netroms == 0) {
9359 fprintf(stderr, "No valid PXE rom found for network device\n");
9360 exit(1);
9363 #endif
9365 /* init the memory */
9366 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9368 /* Initialize kvm */
9369 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9370 #define KVM_EXTRA_PAGES 3
9371 #else
9372 #define KVM_EXTRA_PAGES 0
9373 #endif
9374 if (kvm_enabled()) {
9375 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9376 if (kvm_qemu_create_context() < 0) {
9377 fprintf(stderr, "Could not create KVM context\n");
9378 exit(1);
9380 #ifdef KVM_CAP_USER_MEMORY
9382 int ret;
9384 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9385 if (ret) {
9386 phys_ram_base = qemu_vmalloc(phys_ram_size);
9387 if (!phys_ram_base) {
9388 fprintf(stderr, "Could not allocate physical memory\n");
9389 exit(1);
9393 #endif
9394 } else {
9395 phys_ram_base = qemu_vmalloc(phys_ram_size);
9396 if (!phys_ram_base) {
9397 fprintf(stderr, "Could not allocate physical memory\n");
9398 exit(1);
9402 bdrv_init();
9404 /* we always create the cdrom drive, even if no disk is there */
9406 if (nb_drives_opt < MAX_DRIVES)
9407 drive_add(NULL, CDROM_ALIAS);
9409 /* we always create at least one floppy */
9411 if (nb_drives_opt < MAX_DRIVES)
9412 drive_add(NULL, FD_ALIAS, 0);
9414 /* we always create one sd slot, even if no card is in it */
9416 if (nb_drives_opt < MAX_DRIVES)
9417 drive_add(NULL, SD_ALIAS);
9419 /* open the virtual block devices */
9421 for(i = 0; i < nb_drives_opt; i++)
9422 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9423 exit(1);
9425 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9426 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9428 init_ioports();
9430 /* terminal init */
9431 memset(&display_state, 0, sizeof(display_state));
9432 if (nographic) {
9433 /* nearly nothing to do */
9434 dumb_display_init(ds);
9435 } else if (vnc_display != NULL) {
9436 vnc_display_init(ds);
9437 if (vnc_display_open(ds, vnc_display) < 0)
9438 exit(1);
9439 } else {
9440 #if defined(CONFIG_SDL)
9441 sdl_display_init(ds, full_screen, no_frame);
9442 #elif defined(CONFIG_COCOA)
9443 cocoa_display_init(ds, full_screen);
9444 #else
9445 dumb_display_init(ds);
9446 #endif
9449 /* Maintain compatibility with multiple stdio monitors */
9450 if (!strcmp(monitor_device,"stdio")) {
9451 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9452 if (!strcmp(serial_devices[i],"mon:stdio")) {
9453 monitor_device[0] = '\0';
9454 break;
9455 } else if (!strcmp(serial_devices[i],"stdio")) {
9456 monitor_device[0] = '\0';
9457 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9458 break;
9462 if (monitor_device[0] != '\0') {
9463 monitor_hd = qemu_chr_open(monitor_device);
9464 if (!monitor_hd) {
9465 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9466 exit(1);
9468 monitor_init(monitor_hd, !nographic);
9471 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9472 const char *devname = vmchannel_devices[i];
9473 if (devname[0] != '\0' && strcmp(devname, "none")) {
9474 int devid;
9475 char *termn;
9477 if (strstart(devname, "di:", &devname)) {
9478 devid = strtol(devname, &termn, 16);
9479 devname = termn + 1;
9481 else {
9482 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9483 devname);
9484 exit(1);
9486 vmchannel_hds[i] = qemu_chr_open(devname);
9487 if (!vmchannel_hds[i]) {
9488 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9489 devname);
9490 exit(1);
9492 vmchannel_init(vmchannel_hds[i], devid, i);
9496 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9497 const char *devname = serial_devices[i];
9498 if (devname[0] != '\0' && strcmp(devname, "none")) {
9499 serial_hds[i] = qemu_chr_open(devname);
9500 if (!serial_hds[i]) {
9501 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9502 devname);
9503 exit(1);
9505 if (strstart(devname, "vc", 0))
9506 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9510 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9511 const char *devname = parallel_devices[i];
9512 if (devname[0] != '\0' && strcmp(devname, "none")) {
9513 parallel_hds[i] = qemu_chr_open(devname);
9514 if (!parallel_hds[i]) {
9515 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9516 devname);
9517 exit(1);
9519 if (strstart(devname, "vc", 0))
9520 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9524 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9525 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9527 /* init USB devices */
9528 if (usb_enabled) {
9529 for(i = 0; i < usb_devices_index; i++) {
9530 if (usb_device_add(usb_devices[i]) < 0) {
9531 fprintf(stderr, "Warning: could not add USB device %s\n",
9532 usb_devices[i]);
9537 if (display_state.dpy_refresh) {
9538 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9539 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9542 if (kvm_enabled())
9543 kvm_init_ap();
9545 #ifdef CONFIG_GDBSTUB
9546 if (use_gdbstub) {
9547 /* XXX: use standard host:port notation and modify options
9548 accordingly. */
9549 if (gdbserver_start(gdbstub_port) < 0) {
9550 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9551 gdbstub_port);
9552 exit(1);
9555 #endif
9556 if (loadvm)
9557 do_loadvm(loadvm);
9559 if (incoming) {
9560 int rc;
9562 rc = migrate_incoming(incoming);
9563 if (rc != 0) {
9564 fprintf(stderr, "Migration failed rc=%d\n", rc);
9565 exit(rc);
9570 /* XXX: simplify init */
9571 read_passwords();
9572 if (autostart) {
9573 vm_start();
9577 if (daemonize) {
9578 uint8_t status = 0;
9579 ssize_t len;
9580 int fd;
9582 again1:
9583 len = write(fds[1], &status, 1);
9584 if (len == -1 && (errno == EINTR))
9585 goto again1;
9587 if (len != 1)
9588 exit(1);
9590 chdir("/");
9591 TFR(fd = open("/dev/null", O_RDWR));
9592 if (fd == -1)
9593 exit(1);
9595 dup2(fd, 0);
9596 dup2(fd, 1);
9597 dup2(fd, 2);
9599 close(fd);
9602 main_loop();
9603 quit_timers();
9605 #if !defined(_WIN32)
9606 /* close network clients */
9607 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9608 VLANClientState *vc;
9610 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9611 if (vc->fd_read == tap_receive) {
9612 char ifname[64];
9613 TAPState *s = vc->opaque;
9615 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9616 s->down_script[0])
9617 launch_script(s->down_script, ifname, s->fd);
9621 #endif
9622 return 0;