Add copyright notices
[qemu-kvm/fedora.git] / vl.c
blobaa08c8932337c2be756f0a786e36214dac2c1529
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 extern char *logfilename;
262 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
264 void decorate_application_name(char *appname, int max_len)
266 if (kvm_enabled())
268 int remain = max_len - strlen(appname) - 1;
270 if (remain > 0)
271 strncat(appname, "/KVM", remain);
275 /***********************************************************/
276 /* x86 ISA bus support */
278 target_phys_addr_t isa_mem_base = 0;
279 PicState2 *isa_pic;
281 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
283 #ifdef DEBUG_UNUSED_IOPORT
284 fprintf(stderr, "unused inb: port=0x%04x\n", address);
285 #endif
286 return 0xff;
289 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
291 #ifdef DEBUG_UNUSED_IOPORT
292 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
293 #endif
296 /* default is to make two byte accesses */
297 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
299 uint32_t data;
300 data = ioport_read_table[0][address](ioport_opaque[address], address);
301 address = (address + 1) & (MAX_IOPORTS - 1);
302 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
303 return data;
306 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
308 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
309 address = (address + 1) & (MAX_IOPORTS - 1);
310 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
313 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
315 #ifdef DEBUG_UNUSED_IOPORT
316 fprintf(stderr, "unused inl: port=0x%04x\n", address);
317 #endif
318 return 0xffffffff;
321 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
323 #ifdef DEBUG_UNUSED_IOPORT
324 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
325 #endif
328 static void init_ioports(void)
330 int i;
332 for(i = 0; i < MAX_IOPORTS; i++) {
333 ioport_read_table[0][i] = default_ioport_readb;
334 ioport_write_table[0][i] = default_ioport_writeb;
335 ioport_read_table[1][i] = default_ioport_readw;
336 ioport_write_table[1][i] = default_ioport_writew;
337 ioport_read_table[2][i] = default_ioport_readl;
338 ioport_write_table[2][i] = default_ioport_writel;
342 /* size is the word size in byte */
343 int register_ioport_read(int start, int length, int size,
344 IOPortReadFunc *func, void *opaque)
346 int i, bsize;
348 if (size == 1) {
349 bsize = 0;
350 } else if (size == 2) {
351 bsize = 1;
352 } else if (size == 4) {
353 bsize = 2;
354 } else {
355 hw_error("register_ioport_read: invalid size");
356 return -1;
358 for(i = start; i < start + length; i += size) {
359 ioport_read_table[bsize][i] = func;
360 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
361 hw_error("register_ioport_read: invalid opaque");
362 ioport_opaque[i] = opaque;
364 return 0;
367 /* size is the word size in byte */
368 int register_ioport_write(int start, int length, int size,
369 IOPortWriteFunc *func, void *opaque)
371 int i, bsize;
373 if (size == 1) {
374 bsize = 0;
375 } else if (size == 2) {
376 bsize = 1;
377 } else if (size == 4) {
378 bsize = 2;
379 } else {
380 hw_error("register_ioport_write: invalid size");
381 return -1;
383 for(i = start; i < start + length; i += size) {
384 ioport_write_table[bsize][i] = func;
385 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
386 hw_error("register_ioport_write: invalid opaque");
387 ioport_opaque[i] = opaque;
389 return 0;
392 void isa_unassign_ioport(int start, int length)
394 int i;
396 for(i = start; i < start + length; i++) {
397 ioport_read_table[0][i] = default_ioport_readb;
398 ioport_read_table[1][i] = default_ioport_readw;
399 ioport_read_table[2][i] = default_ioport_readl;
401 ioport_write_table[0][i] = default_ioport_writeb;
402 ioport_write_table[1][i] = default_ioport_writew;
403 ioport_write_table[2][i] = default_ioport_writel;
407 /***********************************************************/
409 void cpu_outb(CPUState *env, int addr, int val)
411 #ifdef DEBUG_IOPORT
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "outb: %04x %02x\n", addr, val);
414 #endif
415 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
422 void cpu_outw(CPUState *env, int addr, int val)
424 #ifdef DEBUG_IOPORT
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "outw: %04x %04x\n", addr, val);
427 #endif
428 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
429 #ifdef USE_KQEMU
430 if (env)
431 env->last_io_time = cpu_get_time_fast();
432 #endif
435 void cpu_outl(CPUState *env, int addr, int val)
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "outl: %04x %08x\n", addr, val);
440 #endif
441 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 int cpu_inb(CPUState *env, int addr)
450 int val;
451 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
452 #ifdef DEBUG_IOPORT
453 if (loglevel & CPU_LOG_IOPORT)
454 fprintf(logfile, "inb : %04x %02x\n", addr, val);
455 #endif
456 #ifdef USE_KQEMU
457 if (env)
458 env->last_io_time = cpu_get_time_fast();
459 #endif
460 return val;
463 int cpu_inw(CPUState *env, int addr)
465 int val;
466 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
467 #ifdef DEBUG_IOPORT
468 if (loglevel & CPU_LOG_IOPORT)
469 fprintf(logfile, "inw : %04x %04x\n", addr, val);
470 #endif
471 #ifdef USE_KQEMU
472 if (env)
473 env->last_io_time = cpu_get_time_fast();
474 #endif
475 return val;
478 int cpu_inl(CPUState *env, int addr)
480 int val;
481 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
482 #ifdef DEBUG_IOPORT
483 if (loglevel & CPU_LOG_IOPORT)
484 fprintf(logfile, "inl : %04x %08x\n", addr, val);
485 #endif
486 #ifdef USE_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
490 return val;
493 /***********************************************************/
494 void hw_error(const char *fmt, ...)
496 va_list ap;
497 CPUState *env;
499 va_start(ap, fmt);
500 fprintf(stderr, "qemu: hardware error: ");
501 vfprintf(stderr, fmt, ap);
502 fprintf(stderr, "\n");
503 for(env = first_cpu; env != NULL; env = env->next_cpu) {
504 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
505 #ifdef TARGET_I386
506 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
507 #else
508 cpu_dump_state(env, stderr, fprintf, 0);
509 #endif
511 va_end(ap);
512 abort();
515 /***********************************************************/
516 /* keyboard/mouse */
518 static QEMUPutKBDEvent *qemu_put_kbd_event;
519 static void *qemu_put_kbd_event_opaque;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
525 qemu_put_kbd_event_opaque = opaque;
526 qemu_put_kbd_event = func;
529 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
530 void *opaque, int absolute,
531 const char *name)
533 QEMUPutMouseEntry *s, *cursor;
535 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
536 if (!s)
537 return NULL;
539 s->qemu_put_mouse_event = func;
540 s->qemu_put_mouse_event_opaque = opaque;
541 s->qemu_put_mouse_event_absolute = absolute;
542 s->qemu_put_mouse_event_name = qemu_strdup(name);
543 s->next = NULL;
545 if (!qemu_put_mouse_event_head) {
546 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
547 return s;
550 cursor = qemu_put_mouse_event_head;
551 while (cursor->next != NULL)
552 cursor = cursor->next;
554 cursor->next = s;
555 qemu_put_mouse_event_current = s;
557 return s;
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
562 QEMUPutMouseEntry *prev = NULL, *cursor;
564 if (!qemu_put_mouse_event_head || entry == NULL)
565 return;
567 cursor = qemu_put_mouse_event_head;
568 while (cursor != NULL && cursor != entry) {
569 prev = cursor;
570 cursor = cursor->next;
573 if (cursor == NULL) // does not exist or list empty
574 return;
575 else if (prev == NULL) { // entry is head
576 qemu_put_mouse_event_head = cursor->next;
577 if (qemu_put_mouse_event_current == entry)
578 qemu_put_mouse_event_current = cursor->next;
579 qemu_free(entry->qemu_put_mouse_event_name);
580 qemu_free(entry);
581 return;
584 prev->next = entry->next;
586 if (qemu_put_mouse_event_current == entry)
587 qemu_put_mouse_event_current = prev;
589 qemu_free(entry->qemu_put_mouse_event_name);
590 qemu_free(entry);
593 void kbd_put_keycode(int keycode)
595 if (qemu_put_kbd_event) {
596 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
600 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
602 QEMUPutMouseEvent *mouse_event;
603 void *mouse_event_opaque;
604 int width;
606 if (!qemu_put_mouse_event_current) {
607 return;
610 mouse_event =
611 qemu_put_mouse_event_current->qemu_put_mouse_event;
612 mouse_event_opaque =
613 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
615 if (mouse_event) {
616 if (graphic_rotate) {
617 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
618 width = 0x7fff;
619 else
620 width = graphic_width;
621 mouse_event(mouse_event_opaque,
622 width - dy, dx, dz, buttons_state);
623 } else
624 mouse_event(mouse_event_opaque,
625 dx, dy, dz, buttons_state);
629 int kbd_mouse_is_absolute(void)
631 if (!qemu_put_mouse_event_current)
632 return 0;
634 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
637 void do_info_mice(void)
639 QEMUPutMouseEntry *cursor;
640 int index = 0;
642 if (!qemu_put_mouse_event_head) {
643 term_printf("No mouse devices connected\n");
644 return;
647 term_printf("Mouse devices available:\n");
648 cursor = qemu_put_mouse_event_head;
649 while (cursor != NULL) {
650 term_printf("%c Mouse #%d: %s\n",
651 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
652 index, cursor->qemu_put_mouse_event_name);
653 index++;
654 cursor = cursor->next;
658 void do_mouse_set(int index)
660 QEMUPutMouseEntry *cursor;
661 int i = 0;
663 if (!qemu_put_mouse_event_head) {
664 term_printf("No mouse devices connected\n");
665 return;
668 cursor = qemu_put_mouse_event_head;
669 while (cursor != NULL && index != i) {
670 i++;
671 cursor = cursor->next;
674 if (cursor != NULL)
675 qemu_put_mouse_event_current = cursor;
676 else
677 term_printf("Mouse at given index not found\n");
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
683 union {
684 uint64_t ll;
685 struct {
686 #ifdef WORDS_BIGENDIAN
687 uint32_t high, low;
688 #else
689 uint32_t low, high;
690 #endif
691 } l;
692 } u, res;
693 uint64_t rl, rh;
695 u.ll = a;
696 rl = (uint64_t)u.l.low * (uint64_t)b;
697 rh = (uint64_t)u.l.high * (uint64_t)b;
698 rh += (rl >> 32);
699 res.l.high = rh / c;
700 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
701 return res.ll;
704 /***********************************************************/
705 /* real time host monotonic timer */
707 #define QEMU_TIMER_BASE 1000000000LL
709 #ifdef WIN32
711 static int64_t clock_freq;
713 static void init_get_clock(void)
715 LARGE_INTEGER freq;
716 int ret;
717 ret = QueryPerformanceFrequency(&freq);
718 if (ret == 0) {
719 fprintf(stderr, "Could not calibrate ticks\n");
720 exit(1);
722 clock_freq = freq.QuadPart;
725 static int64_t get_clock(void)
727 LARGE_INTEGER ti;
728 QueryPerformanceCounter(&ti);
729 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
732 #else
734 static int use_rt_clock;
736 static void init_get_clock(void)
738 use_rt_clock = 0;
739 #if defined(__linux__)
741 struct timespec ts;
742 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
743 use_rt_clock = 1;
746 #endif
749 static int64_t get_clock(void)
751 #if defined(__linux__)
752 if (use_rt_clock) {
753 struct timespec ts;
754 clock_gettime(CLOCK_MONOTONIC, &ts);
755 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
756 } else
757 #endif
759 /* XXX: using gettimeofday leads to problems if the date
760 changes, so it should be avoided. */
761 struct timeval tv;
762 gettimeofday(&tv, NULL);
763 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
767 #endif
769 /***********************************************************/
770 /* guest cycle counter */
772 static int64_t cpu_ticks_prev;
773 static int64_t cpu_ticks_offset;
774 static int64_t cpu_clock_offset;
775 static int cpu_ticks_enabled;
777 /* return the host CPU cycle counter and handle stop/restart */
778 int64_t cpu_get_ticks(void)
780 if (!cpu_ticks_enabled) {
781 return cpu_ticks_offset;
782 } else {
783 int64_t ticks;
784 ticks = cpu_get_real_ticks();
785 if (cpu_ticks_prev > ticks) {
786 /* Note: non increasing ticks may happen if the host uses
787 software suspend */
788 cpu_ticks_offset += cpu_ticks_prev - ticks;
790 cpu_ticks_prev = ticks;
791 return ticks + cpu_ticks_offset;
795 /* return the host CPU monotonic timer and handle stop/restart */
796 static int64_t cpu_get_clock(void)
798 int64_t ti;
799 if (!cpu_ticks_enabled) {
800 return cpu_clock_offset;
801 } else {
802 ti = get_clock();
803 return ti + cpu_clock_offset;
807 /* enable cpu_get_ticks() */
808 void cpu_enable_ticks(void)
810 if (!cpu_ticks_enabled) {
811 cpu_ticks_offset -= cpu_get_real_ticks();
812 cpu_clock_offset -= get_clock();
813 cpu_ticks_enabled = 1;
817 /* disable cpu_get_ticks() : the clock is stopped. You must not call
818 cpu_get_ticks() after that. */
819 void cpu_disable_ticks(void)
821 if (cpu_ticks_enabled) {
822 cpu_ticks_offset = cpu_get_ticks();
823 cpu_clock_offset = cpu_get_clock();
824 cpu_ticks_enabled = 0;
828 /***********************************************************/
829 /* timers */
831 #define QEMU_TIMER_REALTIME 0
832 #define QEMU_TIMER_VIRTUAL 1
834 struct QEMUClock {
835 int type;
836 /* XXX: add frequency */
839 struct QEMUTimer {
840 QEMUClock *clock;
841 int64_t expire_time;
842 QEMUTimerCB *cb;
843 void *opaque;
844 struct QEMUTimer *next;
847 struct qemu_alarm_timer {
848 char const *name;
849 unsigned int flags;
851 int (*start)(struct qemu_alarm_timer *t);
852 void (*stop)(struct qemu_alarm_timer *t);
853 void (*rearm)(struct qemu_alarm_timer *t);
854 void *priv;
857 #define ALARM_FLAG_DYNTICKS 0x1
858 #define ALARM_FLAG_EXPIRED 0x2
860 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
862 return t->flags & ALARM_FLAG_DYNTICKS;
865 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
867 if (!alarm_has_dynticks(t))
868 return;
870 t->rearm(t);
873 /* TODO: MIN_TIMER_REARM_US should be optimized */
874 #define MIN_TIMER_REARM_US 250
876 static struct qemu_alarm_timer *alarm_timer;
878 #ifdef _WIN32
880 struct qemu_alarm_win32 {
881 MMRESULT timerId;
882 HANDLE host_alarm;
883 unsigned int period;
884 } alarm_win32_data = {0, NULL, -1};
886 static int win32_start_timer(struct qemu_alarm_timer *t);
887 static void win32_stop_timer(struct qemu_alarm_timer *t);
888 static void win32_rearm_timer(struct qemu_alarm_timer *t);
890 #else
892 static int unix_start_timer(struct qemu_alarm_timer *t);
893 static void unix_stop_timer(struct qemu_alarm_timer *t);
895 #ifdef __linux__
897 static int dynticks_start_timer(struct qemu_alarm_timer *t);
898 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
899 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
901 static int hpet_start_timer(struct qemu_alarm_timer *t);
902 static void hpet_stop_timer(struct qemu_alarm_timer *t);
904 static int rtc_start_timer(struct qemu_alarm_timer *t);
905 static void rtc_stop_timer(struct qemu_alarm_timer *t);
907 #endif /* __linux__ */
909 #endif /* _WIN32 */
911 static struct qemu_alarm_timer alarm_timers[] = {
912 #ifndef _WIN32
913 #ifdef __linux__
914 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
915 dynticks_stop_timer, dynticks_rearm_timer, NULL},
916 /* HPET - if available - is preferred */
917 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
918 /* ...otherwise try RTC */
919 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
920 #endif
921 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
922 #else
923 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
924 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
925 {"win32", 0, win32_start_timer,
926 win32_stop_timer, NULL, &alarm_win32_data},
927 #endif
928 {NULL, }
931 static void show_available_alarms()
933 int i;
935 printf("Available alarm timers, in order of precedence:\n");
936 for (i = 0; alarm_timers[i].name; i++)
937 printf("%s\n", alarm_timers[i].name);
940 static void configure_alarms(char const *opt)
942 int i;
943 int cur = 0;
944 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
945 char *arg;
946 char *name;
948 if (!strcmp(opt, "help")) {
949 show_available_alarms();
950 exit(0);
953 arg = strdup(opt);
955 /* Reorder the array */
956 name = strtok(arg, ",");
957 while (name) {
958 struct qemu_alarm_timer tmp;
960 for (i = 0; i < count && alarm_timers[i].name; i++) {
961 if (!strcmp(alarm_timers[i].name, name))
962 break;
965 if (i == count) {
966 fprintf(stderr, "Unknown clock %s\n", name);
967 goto next;
970 if (i < cur)
971 /* Ignore */
972 goto next;
974 /* Swap */
975 tmp = alarm_timers[i];
976 alarm_timers[i] = alarm_timers[cur];
977 alarm_timers[cur] = tmp;
979 cur++;
980 next:
981 name = strtok(NULL, ",");
984 free(arg);
986 if (cur) {
987 /* Disable remaining timers */
988 for (i = cur; i < count; i++)
989 alarm_timers[i].name = NULL;
992 /* debug */
993 show_available_alarms();
996 QEMUClock *rt_clock;
997 QEMUClock *vm_clock;
999 static QEMUTimer *active_timers[2];
1001 static QEMUClock *qemu_new_clock(int type)
1003 QEMUClock *clock;
1004 clock = qemu_mallocz(sizeof(QEMUClock));
1005 if (!clock)
1006 return NULL;
1007 clock->type = type;
1008 return clock;
1011 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1013 QEMUTimer *ts;
1015 ts = qemu_mallocz(sizeof(QEMUTimer));
1016 ts->clock = clock;
1017 ts->cb = cb;
1018 ts->opaque = opaque;
1019 return ts;
1022 void qemu_free_timer(QEMUTimer *ts)
1024 qemu_free(ts);
1027 /* stop a timer, but do not dealloc it */
1028 void qemu_del_timer(QEMUTimer *ts)
1030 QEMUTimer **pt, *t;
1032 /* NOTE: this code must be signal safe because
1033 qemu_timer_expired() can be called from a signal. */
1034 pt = &active_timers[ts->clock->type];
1035 for(;;) {
1036 t = *pt;
1037 if (!t)
1038 break;
1039 if (t == ts) {
1040 *pt = t->next;
1041 break;
1043 pt = &t->next;
1047 /* modify the current timer so that it will be fired when current_time
1048 >= expire_time. The corresponding callback will be called. */
1049 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1051 QEMUTimer **pt, *t;
1053 qemu_del_timer(ts);
1055 /* add the timer in the sorted list */
1056 /* NOTE: this code must be signal safe because
1057 qemu_timer_expired() can be called from a signal. */
1058 pt = &active_timers[ts->clock->type];
1059 for(;;) {
1060 t = *pt;
1061 if (!t)
1062 break;
1063 if (t->expire_time > expire_time)
1064 break;
1065 pt = &t->next;
1067 ts->expire_time = expire_time;
1068 ts->next = *pt;
1069 *pt = ts;
1071 /* Rearm if necessary */
1072 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1073 pt == &active_timers[ts->clock->type])
1074 qemu_rearm_alarm_timer(alarm_timer);
1077 int qemu_timer_pending(QEMUTimer *ts)
1079 QEMUTimer *t;
1080 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1081 if (t == ts)
1082 return 1;
1084 return 0;
1087 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1089 if (!timer_head)
1090 return 0;
1091 return (timer_head->expire_time <= current_time);
1094 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1096 QEMUTimer *ts;
1098 for(;;) {
1099 ts = *ptimer_head;
1100 if (!ts || ts->expire_time > current_time)
1101 break;
1102 /* remove timer from the list before calling the callback */
1103 *ptimer_head = ts->next;
1104 ts->next = NULL;
1106 /* run the callback (the timer list can be modified) */
1107 ts->cb(ts->opaque);
1111 int64_t qemu_get_clock(QEMUClock *clock)
1113 switch(clock->type) {
1114 case QEMU_TIMER_REALTIME:
1115 return get_clock() / 1000000;
1116 default:
1117 case QEMU_TIMER_VIRTUAL:
1118 return cpu_get_clock();
1122 static void init_timers(void)
1124 init_get_clock();
1125 ticks_per_sec = QEMU_TIMER_BASE;
1126 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1127 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1130 /* save a timer */
1131 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1133 uint64_t expire_time;
1135 if (qemu_timer_pending(ts)) {
1136 expire_time = ts->expire_time;
1137 } else {
1138 expire_time = -1;
1140 qemu_put_be64(f, expire_time);
1143 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1145 uint64_t expire_time;
1147 expire_time = qemu_get_be64(f);
1148 if (expire_time != -1) {
1149 qemu_mod_timer(ts, expire_time);
1150 } else {
1151 qemu_del_timer(ts);
1155 static void timer_save(QEMUFile *f, void *opaque)
1157 if (cpu_ticks_enabled) {
1158 hw_error("cannot save state if virtual timers are running");
1160 qemu_put_be64(f, cpu_ticks_offset);
1161 qemu_put_be64(f, ticks_per_sec);
1162 qemu_put_be64(f, cpu_clock_offset);
1165 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1167 if (version_id != 1 && version_id != 2)
1168 return -EINVAL;
1169 if (cpu_ticks_enabled) {
1170 return -EINVAL;
1172 cpu_ticks_offset=qemu_get_be64(f);
1173 ticks_per_sec=qemu_get_be64(f);
1174 if (version_id == 2) {
1175 cpu_clock_offset=qemu_get_be64(f);
1177 return 0;
1180 #ifdef _WIN32
1181 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1182 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1183 #else
1184 static void host_alarm_handler(int host_signum)
1185 #endif
1187 #if 0
1188 #define DISP_FREQ 1000
1190 static int64_t delta_min = INT64_MAX;
1191 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1192 static int count;
1193 ti = qemu_get_clock(vm_clock);
1194 if (last_clock != 0) {
1195 delta = ti - last_clock;
1196 if (delta < delta_min)
1197 delta_min = delta;
1198 if (delta > delta_max)
1199 delta_max = delta;
1200 delta_cum += delta;
1201 if (++count == DISP_FREQ) {
1202 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1203 muldiv64(delta_min, 1000000, ticks_per_sec),
1204 muldiv64(delta_max, 1000000, ticks_per_sec),
1205 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1206 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1207 count = 0;
1208 delta_min = INT64_MAX;
1209 delta_max = 0;
1210 delta_cum = 0;
1213 last_clock = ti;
1215 #endif
1216 if (1 ||
1217 alarm_has_dynticks(alarm_timer) ||
1218 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1219 qemu_get_clock(vm_clock)) ||
1220 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1221 qemu_get_clock(rt_clock))) {
1222 #ifdef _WIN32
1223 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1224 SetEvent(data->host_alarm);
1225 #endif
1226 CPUState *env = next_cpu;
1228 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1230 if (env) {
1231 /* stop the currently executing cpu because a timer occured */
1232 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1233 #ifdef USE_KQEMU
1234 if (env->kqemu_enabled) {
1235 kqemu_cpu_interrupt(env);
1237 #endif
1239 event_pending = 1;
1243 static uint64_t qemu_next_deadline(void)
1245 int64_t nearest_delta_us = INT64_MAX;
1246 int64_t vmdelta_us;
1248 if (active_timers[QEMU_TIMER_REALTIME])
1249 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1250 qemu_get_clock(rt_clock))*1000;
1252 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1253 /* round up */
1254 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1255 qemu_get_clock(vm_clock)+999)/1000;
1256 if (vmdelta_us < nearest_delta_us)
1257 nearest_delta_us = vmdelta_us;
1260 /* Avoid arming the timer to negative, zero, or too low values */
1261 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1262 nearest_delta_us = MIN_TIMER_REARM_US;
1264 return nearest_delta_us;
1267 #ifndef _WIN32
1269 #if defined(__linux__)
1271 #define RTC_FREQ 1024
1273 static void enable_sigio_timer(int fd)
1275 struct sigaction act;
1277 /* timer signal */
1278 sigfillset(&act.sa_mask);
1279 act.sa_flags = 0;
1280 act.sa_handler = host_alarm_handler;
1282 sigaction(SIGIO, &act, NULL);
1283 fcntl(fd, F_SETFL, O_ASYNC);
1284 fcntl(fd, F_SETOWN, getpid());
1287 static int hpet_start_timer(struct qemu_alarm_timer *t)
1289 struct hpet_info info;
1290 int r, fd;
1292 fd = open("/dev/hpet", O_RDONLY);
1293 if (fd < 0)
1294 return -1;
1296 /* Set frequency */
1297 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1298 if (r < 0) {
1299 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1300 "error, but for better emulation accuracy type:\n"
1301 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1302 goto fail;
1305 /* Check capabilities */
1306 r = ioctl(fd, HPET_INFO, &info);
1307 if (r < 0)
1308 goto fail;
1310 /* Enable periodic mode */
1311 r = ioctl(fd, HPET_EPI, 0);
1312 if (info.hi_flags && (r < 0))
1313 goto fail;
1315 /* Enable interrupt */
1316 r = ioctl(fd, HPET_IE_ON, 0);
1317 if (r < 0)
1318 goto fail;
1320 enable_sigio_timer(fd);
1321 t->priv = (void *)(long)fd;
1323 return 0;
1324 fail:
1325 close(fd);
1326 return -1;
1329 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1331 int fd = (long)t->priv;
1333 close(fd);
1336 static int rtc_start_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd;
1340 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1341 if (rtc_fd < 0)
1342 return -1;
1343 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1344 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1345 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1346 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1347 goto fail;
1349 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1350 fail:
1351 close(rtc_fd);
1352 return -1;
1355 enable_sigio_timer(rtc_fd);
1357 t->priv = (void *)(long)rtc_fd;
1359 return 0;
1362 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1364 int rtc_fd = (long)t->priv;
1366 close(rtc_fd);
1369 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1371 struct sigevent ev;
1372 timer_t host_timer;
1373 struct sigaction act;
1375 sigfillset(&act.sa_mask);
1376 act.sa_flags = 0;
1377 act.sa_handler = host_alarm_handler;
1379 sigaction(SIGALRM, &act, NULL);
1381 ev.sigev_value.sival_int = 0;
1382 ev.sigev_notify = SIGEV_SIGNAL;
1383 ev.sigev_signo = SIGALRM;
1385 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1386 perror("timer_create");
1388 /* disable dynticks */
1389 fprintf(stderr, "Dynamic Ticks disabled\n");
1391 return -1;
1394 t->priv = (void *)host_timer;
1396 return 0;
1399 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1401 timer_t host_timer = (timer_t)t->priv;
1403 timer_delete(host_timer);
1406 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1408 timer_t host_timer = (timer_t)t->priv;
1409 struct itimerspec timeout;
1410 int64_t nearest_delta_us = INT64_MAX;
1411 int64_t current_us;
1413 if (!active_timers[QEMU_TIMER_REALTIME] &&
1414 !active_timers[QEMU_TIMER_VIRTUAL])
1415 return;
1417 nearest_delta_us = qemu_next_deadline();
1419 /* check whether a timer is already running */
1420 if (timer_gettime(host_timer, &timeout)) {
1421 perror("gettime");
1422 fprintf(stderr, "Internal timer error: aborting\n");
1423 exit(1);
1425 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1426 if (current_us && current_us <= nearest_delta_us)
1427 return;
1429 timeout.it_interval.tv_sec = 0;
1430 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1431 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1432 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1433 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1434 perror("settime");
1435 fprintf(stderr, "Internal timer error: aborting\n");
1436 exit(1);
1440 #endif /* defined(__linux__) */
1442 static int unix_start_timer(struct qemu_alarm_timer *t)
1444 struct sigaction act;
1445 struct itimerval itv;
1446 int err;
1448 /* timer signal */
1449 sigfillset(&act.sa_mask);
1450 act.sa_flags = 0;
1451 act.sa_handler = host_alarm_handler;
1453 sigaction(SIGALRM, &act, NULL);
1455 itv.it_interval.tv_sec = 0;
1456 /* for i386 kernel 2.6 to get 1 ms */
1457 itv.it_interval.tv_usec = 999;
1458 itv.it_value.tv_sec = 0;
1459 itv.it_value.tv_usec = 10 * 1000;
1461 err = setitimer(ITIMER_REAL, &itv, NULL);
1462 if (err)
1463 return -1;
1465 return 0;
1468 static void unix_stop_timer(struct qemu_alarm_timer *t)
1470 struct itimerval itv;
1472 memset(&itv, 0, sizeof(itv));
1473 setitimer(ITIMER_REAL, &itv, NULL);
1476 #endif /* !defined(_WIN32) */
1478 #ifdef _WIN32
1480 static int win32_start_timer(struct qemu_alarm_timer *t)
1482 TIMECAPS tc;
1483 struct qemu_alarm_win32 *data = t->priv;
1484 UINT flags;
1486 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1487 if (!data->host_alarm) {
1488 perror("Failed CreateEvent");
1489 return -1;
1492 memset(&tc, 0, sizeof(tc));
1493 timeGetDevCaps(&tc, sizeof(tc));
1495 if (data->period < tc.wPeriodMin)
1496 data->period = tc.wPeriodMin;
1498 timeBeginPeriod(data->period);
1500 flags = TIME_CALLBACK_FUNCTION;
1501 if (alarm_has_dynticks(t))
1502 flags |= TIME_ONESHOT;
1503 else
1504 flags |= TIME_PERIODIC;
1506 data->timerId = timeSetEvent(1, // interval (ms)
1507 data->period, // resolution
1508 host_alarm_handler, // function
1509 (DWORD)t, // parameter
1510 flags);
1512 if (!data->timerId) {
1513 perror("Failed to initialize win32 alarm timer");
1515 timeEndPeriod(data->period);
1516 CloseHandle(data->host_alarm);
1517 return -1;
1520 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1522 return 0;
1525 static void win32_stop_timer(struct qemu_alarm_timer *t)
1527 struct qemu_alarm_win32 *data = t->priv;
1529 timeKillEvent(data->timerId);
1530 timeEndPeriod(data->period);
1532 CloseHandle(data->host_alarm);
1535 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1537 struct qemu_alarm_win32 *data = t->priv;
1538 uint64_t nearest_delta_us;
1540 if (!active_timers[QEMU_TIMER_REALTIME] &&
1541 !active_timers[QEMU_TIMER_VIRTUAL])
1542 return;
1544 nearest_delta_us = qemu_next_deadline();
1545 nearest_delta_us /= 1000;
1547 timeKillEvent(data->timerId);
1549 data->timerId = timeSetEvent(1,
1550 data->period,
1551 host_alarm_handler,
1552 (DWORD)t,
1553 TIME_ONESHOT | TIME_PERIODIC);
1555 if (!data->timerId) {
1556 perror("Failed to re-arm win32 alarm timer");
1558 timeEndPeriod(data->period);
1559 CloseHandle(data->host_alarm);
1560 exit(1);
1564 #endif /* _WIN32 */
1566 static void init_timer_alarm(void)
1568 struct qemu_alarm_timer *t;
1569 int i, err = -1;
1571 for (i = 0; alarm_timers[i].name; i++) {
1572 t = &alarm_timers[i];
1574 err = t->start(t);
1575 if (!err)
1576 break;
1579 if (err) {
1580 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1581 fprintf(stderr, "Terminating\n");
1582 exit(1);
1585 alarm_timer = t;
1588 static void quit_timers(void)
1590 alarm_timer->stop(alarm_timer);
1591 alarm_timer = NULL;
1594 /***********************************************************/
1595 /* character device */
1597 static void qemu_chr_event(CharDriverState *s, int event)
1599 if (!s->chr_event)
1600 return;
1601 s->chr_event(s->handler_opaque, event);
1604 static void qemu_chr_reset_bh(void *opaque)
1606 CharDriverState *s = opaque;
1607 qemu_chr_event(s, CHR_EVENT_RESET);
1608 qemu_bh_delete(s->bh);
1609 s->bh = NULL;
1612 void qemu_chr_reset(CharDriverState *s)
1614 if (s->bh == NULL) {
1615 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1616 qemu_bh_schedule(s->bh);
1620 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1622 return s->chr_write(s, buf, len);
1625 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1627 if (!s->chr_ioctl)
1628 return -ENOTSUP;
1629 return s->chr_ioctl(s, cmd, arg);
1632 int qemu_chr_can_read(CharDriverState *s)
1634 if (!s->chr_can_read)
1635 return 0;
1636 return s->chr_can_read(s->handler_opaque);
1639 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1641 s->chr_read(s->handler_opaque, buf, len);
1644 void qemu_chr_accept_input(CharDriverState *s)
1646 if (s->chr_accept_input)
1647 s->chr_accept_input(s);
1650 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1652 char buf[4096];
1653 va_list ap;
1654 va_start(ap, fmt);
1655 vsnprintf(buf, sizeof(buf), fmt, ap);
1656 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1657 va_end(ap);
1660 void qemu_chr_send_event(CharDriverState *s, int event)
1662 if (s->chr_send_event)
1663 s->chr_send_event(s, event);
1666 void qemu_chr_add_handlers(CharDriverState *s,
1667 IOCanRWHandler *fd_can_read,
1668 IOReadHandler *fd_read,
1669 IOEventHandler *fd_event,
1670 void *opaque)
1672 s->chr_can_read = fd_can_read;
1673 s->chr_read = fd_read;
1674 s->chr_event = fd_event;
1675 s->handler_opaque = opaque;
1676 if (s->chr_update_read_handler)
1677 s->chr_update_read_handler(s);
1680 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1682 return len;
1685 static CharDriverState *qemu_chr_open_null(void)
1687 CharDriverState *chr;
1689 chr = qemu_mallocz(sizeof(CharDriverState));
1690 if (!chr)
1691 return NULL;
1692 chr->chr_write = null_chr_write;
1693 return chr;
1696 /* MUX driver for serial I/O splitting */
1697 static int term_timestamps;
1698 static int64_t term_timestamps_start;
1699 #define MAX_MUX 4
1700 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1701 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1702 typedef struct {
1703 IOCanRWHandler *chr_can_read[MAX_MUX];
1704 IOReadHandler *chr_read[MAX_MUX];
1705 IOEventHandler *chr_event[MAX_MUX];
1706 void *ext_opaque[MAX_MUX];
1707 CharDriverState *drv;
1708 unsigned char buffer[MUX_BUFFER_SIZE];
1709 int prod;
1710 int cons;
1711 int mux_cnt;
1712 int term_got_escape;
1713 int max_size;
1714 } MuxDriver;
1717 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1719 MuxDriver *d = chr->opaque;
1720 int ret;
1721 if (!term_timestamps) {
1722 ret = d->drv->chr_write(d->drv, buf, len);
1723 } else {
1724 int i;
1726 ret = 0;
1727 for(i = 0; i < len; i++) {
1728 ret += d->drv->chr_write(d->drv, buf+i, 1);
1729 if (buf[i] == '\n') {
1730 char buf1[64];
1731 int64_t ti;
1732 int secs;
1734 ti = get_clock();
1735 if (term_timestamps_start == -1)
1736 term_timestamps_start = ti;
1737 ti -= term_timestamps_start;
1738 secs = ti / 1000000000;
1739 snprintf(buf1, sizeof(buf1),
1740 "[%02d:%02d:%02d.%03d] ",
1741 secs / 3600,
1742 (secs / 60) % 60,
1743 secs % 60,
1744 (int)((ti / 1000000) % 1000));
1745 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1749 return ret;
1752 static char *mux_help[] = {
1753 "% h print this help\n\r",
1754 "% x exit emulator\n\r",
1755 "% s save disk data back to file (if -snapshot)\n\r",
1756 "% t toggle console timestamps\n\r"
1757 "% b send break (magic sysrq)\n\r",
1758 "% c switch between console and monitor\n\r",
1759 "% % sends %\n\r",
1760 NULL
1763 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1764 static void mux_print_help(CharDriverState *chr)
1766 int i, j;
1767 char ebuf[15] = "Escape-Char";
1768 char cbuf[50] = "\n\r";
1770 if (term_escape_char > 0 && term_escape_char < 26) {
1771 sprintf(cbuf,"\n\r");
1772 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1773 } else {
1774 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1775 term_escape_char);
1777 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1778 for (i = 0; mux_help[i] != NULL; i++) {
1779 for (j=0; mux_help[i][j] != '\0'; j++) {
1780 if (mux_help[i][j] == '%')
1781 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1782 else
1783 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1788 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1790 if (d->term_got_escape) {
1791 d->term_got_escape = 0;
1792 if (ch == term_escape_char)
1793 goto send_char;
1794 switch(ch) {
1795 case '?':
1796 case 'h':
1797 mux_print_help(chr);
1798 break;
1799 case 'x':
1801 char *term = "QEMU: Terminated\n\r";
1802 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1803 exit(0);
1804 break;
1806 case 's':
1808 int i;
1809 for (i = 0; i < nb_drives; i++) {
1810 bdrv_commit(drives_table[i].bdrv);
1813 break;
1814 case 'b':
1815 qemu_chr_event(chr, CHR_EVENT_BREAK);
1816 break;
1817 case 'c':
1818 /* Switch to the next registered device */
1819 chr->focus++;
1820 if (chr->focus >= d->mux_cnt)
1821 chr->focus = 0;
1822 break;
1823 case 't':
1824 term_timestamps = !term_timestamps;
1825 term_timestamps_start = -1;
1826 break;
1828 } else if (ch == term_escape_char) {
1829 d->term_got_escape = 1;
1830 } else {
1831 send_char:
1832 return 1;
1834 return 0;
1837 static void mux_chr_accept_input(CharDriverState *chr)
1839 int m = chr->focus;
1840 MuxDriver *d = chr->opaque;
1842 while (d->prod != d->cons &&
1843 d->chr_can_read[m] &&
1844 d->chr_can_read[m](d->ext_opaque[m])) {
1845 d->chr_read[m](d->ext_opaque[m],
1846 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1850 static int mux_chr_can_read(void *opaque)
1852 CharDriverState *chr = opaque;
1853 MuxDriver *d = chr->opaque;
1855 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1856 return 1;
1857 if (d->chr_can_read[chr->focus])
1858 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1859 return 0;
1862 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1864 CharDriverState *chr = opaque;
1865 MuxDriver *d = chr->opaque;
1866 int m = chr->focus;
1867 int i;
1869 mux_chr_accept_input (opaque);
1871 for(i = 0; i < size; i++)
1872 if (mux_proc_byte(chr, d, buf[i])) {
1873 if (d->prod == d->cons &&
1874 d->chr_can_read[m] &&
1875 d->chr_can_read[m](d->ext_opaque[m]))
1876 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1877 else
1878 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1882 static void mux_chr_event(void *opaque, int event)
1884 CharDriverState *chr = opaque;
1885 MuxDriver *d = chr->opaque;
1886 int i;
1888 /* Send the event to all registered listeners */
1889 for (i = 0; i < d->mux_cnt; i++)
1890 if (d->chr_event[i])
1891 d->chr_event[i](d->ext_opaque[i], event);
1894 static void mux_chr_update_read_handler(CharDriverState *chr)
1896 MuxDriver *d = chr->opaque;
1898 if (d->mux_cnt >= MAX_MUX) {
1899 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1900 return;
1902 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1903 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1904 d->chr_read[d->mux_cnt] = chr->chr_read;
1905 d->chr_event[d->mux_cnt] = chr->chr_event;
1906 /* Fix up the real driver with mux routines */
1907 if (d->mux_cnt == 0) {
1908 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1909 mux_chr_event, chr);
1911 chr->focus = d->mux_cnt;
1912 d->mux_cnt++;
1915 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1917 CharDriverState *chr;
1918 MuxDriver *d;
1920 chr = qemu_mallocz(sizeof(CharDriverState));
1921 if (!chr)
1922 return NULL;
1923 d = qemu_mallocz(sizeof(MuxDriver));
1924 if (!d) {
1925 free(chr);
1926 return NULL;
1929 chr->opaque = d;
1930 d->drv = drv;
1931 chr->focus = -1;
1932 chr->chr_write = mux_chr_write;
1933 chr->chr_update_read_handler = mux_chr_update_read_handler;
1934 chr->chr_accept_input = mux_chr_accept_input;
1935 return chr;
1939 #ifdef _WIN32
1941 static void socket_cleanup(void)
1943 WSACleanup();
1946 static int socket_init(void)
1948 WSADATA Data;
1949 int ret, err;
1951 ret = WSAStartup(MAKEWORD(2,2), &Data);
1952 if (ret != 0) {
1953 err = WSAGetLastError();
1954 fprintf(stderr, "WSAStartup: %d\n", err);
1955 return -1;
1957 atexit(socket_cleanup);
1958 return 0;
1961 static int send_all(int fd, const uint8_t *buf, int len1)
1963 int ret, len;
1965 len = len1;
1966 while (len > 0) {
1967 ret = send(fd, buf, len, 0);
1968 if (ret < 0) {
1969 int errno;
1970 errno = WSAGetLastError();
1971 if (errno != WSAEWOULDBLOCK) {
1972 return -1;
1974 } else if (ret == 0) {
1975 break;
1976 } else {
1977 buf += ret;
1978 len -= ret;
1981 return len1 - len;
1984 void socket_set_nonblock(int fd)
1986 unsigned long opt = 1;
1987 ioctlsocket(fd, FIONBIO, &opt);
1990 #else
1992 static int unix_write(int fd, const uint8_t *buf, int len1)
1994 int ret, len;
1996 len = len1;
1997 while (len > 0) {
1998 ret = write(fd, buf, len);
1999 if (ret < 0) {
2000 if (errno != EINTR && errno != EAGAIN)
2001 return -1;
2002 } else if (ret == 0) {
2003 break;
2004 } else {
2005 buf += ret;
2006 len -= ret;
2009 return len1 - len;
2012 static inline int send_all(int fd, const uint8_t *buf, int len1)
2014 return unix_write(fd, buf, len1);
2017 void socket_set_nonblock(int fd)
2019 fcntl(fd, F_SETFL, O_NONBLOCK);
2021 #endif /* !_WIN32 */
2023 #ifndef _WIN32
2025 typedef struct {
2026 int fd_in, fd_out;
2027 int max_size;
2028 } FDCharDriver;
2030 #define STDIO_MAX_CLIENTS 1
2031 static int stdio_nb_clients = 0;
2033 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2035 FDCharDriver *s = chr->opaque;
2036 return unix_write(s->fd_out, buf, len);
2039 static int fd_chr_read_poll(void *opaque)
2041 CharDriverState *chr = opaque;
2042 FDCharDriver *s = chr->opaque;
2044 s->max_size = qemu_chr_can_read(chr);
2045 return s->max_size;
2048 static void fd_chr_read(void *opaque)
2050 CharDriverState *chr = opaque;
2051 FDCharDriver *s = chr->opaque;
2052 int size, len;
2053 uint8_t buf[1024];
2055 len = sizeof(buf);
2056 if (len > s->max_size)
2057 len = s->max_size;
2058 if (len == 0)
2059 return;
2060 size = read(s->fd_in, buf, len);
2061 if (size == 0) {
2062 /* FD has been closed. Remove it from the active list. */
2063 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2064 return;
2066 if (size > 0) {
2067 qemu_chr_read(chr, buf, size);
2071 static void fd_chr_update_read_handler(CharDriverState *chr)
2073 FDCharDriver *s = chr->opaque;
2075 if (s->fd_in >= 0) {
2076 if (nographic && s->fd_in == 0) {
2077 } else {
2078 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2079 fd_chr_read, NULL, chr);
2084 static void fd_chr_close(struct CharDriverState *chr)
2086 FDCharDriver *s = chr->opaque;
2088 if (s->fd_in >= 0) {
2089 if (nographic && s->fd_in == 0) {
2090 } else {
2091 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2095 qemu_free(s);
2098 /* open a character device to a unix fd */
2099 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2101 CharDriverState *chr;
2102 FDCharDriver *s;
2104 chr = qemu_mallocz(sizeof(CharDriverState));
2105 if (!chr)
2106 return NULL;
2107 s = qemu_mallocz(sizeof(FDCharDriver));
2108 if (!s) {
2109 free(chr);
2110 return NULL;
2112 s->fd_in = fd_in;
2113 s->fd_out = fd_out;
2114 chr->opaque = s;
2115 chr->chr_write = fd_chr_write;
2116 chr->chr_update_read_handler = fd_chr_update_read_handler;
2117 chr->chr_close = fd_chr_close;
2119 qemu_chr_reset(chr);
2121 return chr;
2124 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2126 int fd_out;
2128 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2129 if (fd_out < 0)
2130 return NULL;
2131 return qemu_chr_open_fd(-1, fd_out);
2134 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2136 int fd_in, fd_out;
2137 char filename_in[256], filename_out[256];
2139 snprintf(filename_in, 256, "%s.in", filename);
2140 snprintf(filename_out, 256, "%s.out", filename);
2141 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2142 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2143 if (fd_in < 0 || fd_out < 0) {
2144 if (fd_in >= 0)
2145 close(fd_in);
2146 if (fd_out >= 0)
2147 close(fd_out);
2148 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2149 if (fd_in < 0)
2150 return NULL;
2152 return qemu_chr_open_fd(fd_in, fd_out);
2156 /* for STDIO, we handle the case where several clients use it
2157 (nographic mode) */
2159 #define TERM_FIFO_MAX_SIZE 1
2161 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2162 static int term_fifo_size;
2164 static int stdio_read_poll(void *opaque)
2166 CharDriverState *chr = opaque;
2168 /* try to flush the queue if needed */
2169 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2170 qemu_chr_read(chr, term_fifo, 1);
2171 term_fifo_size = 0;
2173 /* see if we can absorb more chars */
2174 if (term_fifo_size == 0)
2175 return 1;
2176 else
2177 return 0;
2180 static void stdio_read(void *opaque)
2182 int size;
2183 uint8_t buf[1];
2184 CharDriverState *chr = opaque;
2186 size = read(0, buf, 1);
2187 if (size == 0) {
2188 /* stdin has been closed. Remove it from the active list. */
2189 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2190 return;
2192 if (size > 0) {
2193 if (qemu_chr_can_read(chr) > 0) {
2194 qemu_chr_read(chr, buf, 1);
2195 } else if (term_fifo_size == 0) {
2196 term_fifo[term_fifo_size++] = buf[0];
2201 /* init terminal so that we can grab keys */
2202 static struct termios oldtty;
2203 static int old_fd0_flags;
2204 static int term_atexit_done;
2206 static void term_exit(void)
2208 tcsetattr (0, TCSANOW, &oldtty);
2209 fcntl(0, F_SETFL, old_fd0_flags);
2212 static void term_init(void)
2214 struct termios tty;
2216 tcgetattr (0, &tty);
2217 oldtty = tty;
2218 old_fd0_flags = fcntl(0, F_GETFL);
2220 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2221 |INLCR|IGNCR|ICRNL|IXON);
2222 tty.c_oflag |= OPOST;
2223 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2224 /* if graphical mode, we allow Ctrl-C handling */
2225 if (nographic)
2226 tty.c_lflag &= ~ISIG;
2227 tty.c_cflag &= ~(CSIZE|PARENB);
2228 tty.c_cflag |= CS8;
2229 tty.c_cc[VMIN] = 1;
2230 tty.c_cc[VTIME] = 0;
2232 tcsetattr (0, TCSANOW, &tty);
2234 if (!term_atexit_done++)
2235 atexit(term_exit);
2237 fcntl(0, F_SETFL, O_NONBLOCK);
2240 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2242 term_exit();
2243 stdio_nb_clients--;
2244 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2245 fd_chr_close(chr);
2248 static CharDriverState *qemu_chr_open_stdio(void)
2250 CharDriverState *chr;
2252 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2253 return NULL;
2254 chr = qemu_chr_open_fd(0, 1);
2255 chr->chr_close = qemu_chr_close_stdio;
2256 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2257 stdio_nb_clients++;
2258 term_init();
2260 return chr;
2263 #if defined(__linux__) || defined(__sun__)
2264 static CharDriverState *qemu_chr_open_pty(void)
2266 struct termios tty;
2267 char slave_name[1024];
2268 int master_fd, slave_fd;
2270 #if defined(__linux__)
2271 /* Not satisfying */
2272 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2273 return NULL;
2275 #endif
2277 /* Disabling local echo and line-buffered output */
2278 tcgetattr (master_fd, &tty);
2279 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2280 tty.c_cc[VMIN] = 1;
2281 tty.c_cc[VTIME] = 0;
2282 tcsetattr (master_fd, TCSAFLUSH, &tty);
2284 fprintf(stderr, "char device redirected to %s\n", slave_name);
2285 return qemu_chr_open_fd(master_fd, master_fd);
2288 static void tty_serial_init(int fd, int speed,
2289 int parity, int data_bits, int stop_bits)
2291 struct termios tty;
2292 speed_t spd;
2294 #if 0
2295 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2296 speed, parity, data_bits, stop_bits);
2297 #endif
2298 tcgetattr (fd, &tty);
2300 #define MARGIN 1.1
2301 if (speed <= 50 * MARGIN)
2302 spd = B50;
2303 else if (speed <= 75 * MARGIN)
2304 spd = B75;
2305 else if (speed <= 300 * MARGIN)
2306 spd = B300;
2307 else if (speed <= 600 * MARGIN)
2308 spd = B600;
2309 else if (speed <= 1200 * MARGIN)
2310 spd = B1200;
2311 else if (speed <= 2400 * MARGIN)
2312 spd = B2400;
2313 else if (speed <= 4800 * MARGIN)
2314 spd = B4800;
2315 else if (speed <= 9600 * MARGIN)
2316 spd = B9600;
2317 else if (speed <= 19200 * MARGIN)
2318 spd = B19200;
2319 else if (speed <= 38400 * MARGIN)
2320 spd = B38400;
2321 else if (speed <= 57600 * MARGIN)
2322 spd = B57600;
2323 else if (speed <= 115200 * MARGIN)
2324 spd = B115200;
2325 else
2326 spd = B115200;
2328 cfsetispeed(&tty, spd);
2329 cfsetospeed(&tty, spd);
2331 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2332 |INLCR|IGNCR|ICRNL|IXON);
2333 tty.c_oflag |= OPOST;
2334 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2335 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2336 switch(data_bits) {
2337 default:
2338 case 8:
2339 tty.c_cflag |= CS8;
2340 break;
2341 case 7:
2342 tty.c_cflag |= CS7;
2343 break;
2344 case 6:
2345 tty.c_cflag |= CS6;
2346 break;
2347 case 5:
2348 tty.c_cflag |= CS5;
2349 break;
2351 switch(parity) {
2352 default:
2353 case 'N':
2354 break;
2355 case 'E':
2356 tty.c_cflag |= PARENB;
2357 break;
2358 case 'O':
2359 tty.c_cflag |= PARENB | PARODD;
2360 break;
2362 if (stop_bits == 2)
2363 tty.c_cflag |= CSTOPB;
2365 tcsetattr (fd, TCSANOW, &tty);
2368 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2370 FDCharDriver *s = chr->opaque;
2372 switch(cmd) {
2373 case CHR_IOCTL_SERIAL_SET_PARAMS:
2375 QEMUSerialSetParams *ssp = arg;
2376 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2377 ssp->data_bits, ssp->stop_bits);
2379 break;
2380 case CHR_IOCTL_SERIAL_SET_BREAK:
2382 int enable = *(int *)arg;
2383 if (enable)
2384 tcsendbreak(s->fd_in, 1);
2386 break;
2387 default:
2388 return -ENOTSUP;
2390 return 0;
2393 static CharDriverState *qemu_chr_open_tty(const char *filename)
2395 CharDriverState *chr;
2396 int fd;
2398 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2399 fcntl(fd, F_SETFL, O_NONBLOCK);
2400 tty_serial_init(fd, 115200, 'N', 8, 1);
2401 chr = qemu_chr_open_fd(fd, fd);
2402 if (!chr) {
2403 close(fd);
2404 return NULL;
2406 chr->chr_ioctl = tty_serial_ioctl;
2407 qemu_chr_reset(chr);
2408 return chr;
2410 #else /* ! __linux__ && ! __sun__ */
2411 static CharDriverState *qemu_chr_open_pty(void)
2413 return NULL;
2415 #endif /* __linux__ || __sun__ */
2417 #if defined(__linux__)
2418 typedef struct {
2419 int fd;
2420 int mode;
2421 } ParallelCharDriver;
2423 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2425 if (s->mode != mode) {
2426 int m = mode;
2427 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2428 return 0;
2429 s->mode = mode;
2431 return 1;
2434 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2436 ParallelCharDriver *drv = chr->opaque;
2437 int fd = drv->fd;
2438 uint8_t b;
2440 switch(cmd) {
2441 case CHR_IOCTL_PP_READ_DATA:
2442 if (ioctl(fd, PPRDATA, &b) < 0)
2443 return -ENOTSUP;
2444 *(uint8_t *)arg = b;
2445 break;
2446 case CHR_IOCTL_PP_WRITE_DATA:
2447 b = *(uint8_t *)arg;
2448 if (ioctl(fd, PPWDATA, &b) < 0)
2449 return -ENOTSUP;
2450 break;
2451 case CHR_IOCTL_PP_READ_CONTROL:
2452 if (ioctl(fd, PPRCONTROL, &b) < 0)
2453 return -ENOTSUP;
2454 /* Linux gives only the lowest bits, and no way to know data
2455 direction! For better compatibility set the fixed upper
2456 bits. */
2457 *(uint8_t *)arg = b | 0xc0;
2458 break;
2459 case CHR_IOCTL_PP_WRITE_CONTROL:
2460 b = *(uint8_t *)arg;
2461 if (ioctl(fd, PPWCONTROL, &b) < 0)
2462 return -ENOTSUP;
2463 break;
2464 case CHR_IOCTL_PP_READ_STATUS:
2465 if (ioctl(fd, PPRSTATUS, &b) < 0)
2466 return -ENOTSUP;
2467 *(uint8_t *)arg = b;
2468 break;
2469 case CHR_IOCTL_PP_EPP_READ_ADDR:
2470 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2471 struct ParallelIOArg *parg = arg;
2472 int n = read(fd, parg->buffer, parg->count);
2473 if (n != parg->count) {
2474 return -EIO;
2477 break;
2478 case CHR_IOCTL_PP_EPP_READ:
2479 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2480 struct ParallelIOArg *parg = arg;
2481 int n = read(fd, parg->buffer, parg->count);
2482 if (n != parg->count) {
2483 return -EIO;
2486 break;
2487 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2488 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2489 struct ParallelIOArg *parg = arg;
2490 int n = write(fd, parg->buffer, parg->count);
2491 if (n != parg->count) {
2492 return -EIO;
2495 break;
2496 case CHR_IOCTL_PP_EPP_WRITE:
2497 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2498 struct ParallelIOArg *parg = arg;
2499 int n = write(fd, parg->buffer, parg->count);
2500 if (n != parg->count) {
2501 return -EIO;
2504 break;
2505 default:
2506 return -ENOTSUP;
2508 return 0;
2511 static void pp_close(CharDriverState *chr)
2513 ParallelCharDriver *drv = chr->opaque;
2514 int fd = drv->fd;
2516 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2517 ioctl(fd, PPRELEASE);
2518 close(fd);
2519 qemu_free(drv);
2522 static CharDriverState *qemu_chr_open_pp(const char *filename)
2524 CharDriverState *chr;
2525 ParallelCharDriver *drv;
2526 int fd;
2528 TFR(fd = open(filename, O_RDWR));
2529 if (fd < 0)
2530 return NULL;
2532 if (ioctl(fd, PPCLAIM) < 0) {
2533 close(fd);
2534 return NULL;
2537 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2538 if (!drv) {
2539 close(fd);
2540 return NULL;
2542 drv->fd = fd;
2543 drv->mode = IEEE1284_MODE_COMPAT;
2545 chr = qemu_mallocz(sizeof(CharDriverState));
2546 if (!chr) {
2547 qemu_free(drv);
2548 close(fd);
2549 return NULL;
2551 chr->chr_write = null_chr_write;
2552 chr->chr_ioctl = pp_ioctl;
2553 chr->chr_close = pp_close;
2554 chr->opaque = drv;
2556 qemu_chr_reset(chr);
2558 return chr;
2560 #endif /* __linux__ */
2562 #else /* _WIN32 */
2564 typedef struct {
2565 int max_size;
2566 HANDLE hcom, hrecv, hsend;
2567 OVERLAPPED orecv, osend;
2568 BOOL fpipe;
2569 DWORD len;
2570 } WinCharState;
2572 #define NSENDBUF 2048
2573 #define NRECVBUF 2048
2574 #define MAXCONNECT 1
2575 #define NTIMEOUT 5000
2577 static int win_chr_poll(void *opaque);
2578 static int win_chr_pipe_poll(void *opaque);
2580 static void win_chr_close(CharDriverState *chr)
2582 WinCharState *s = chr->opaque;
2584 if (s->hsend) {
2585 CloseHandle(s->hsend);
2586 s->hsend = NULL;
2588 if (s->hrecv) {
2589 CloseHandle(s->hrecv);
2590 s->hrecv = NULL;
2592 if (s->hcom) {
2593 CloseHandle(s->hcom);
2594 s->hcom = NULL;
2596 if (s->fpipe)
2597 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2598 else
2599 qemu_del_polling_cb(win_chr_poll, chr);
2602 static int win_chr_init(CharDriverState *chr, const char *filename)
2604 WinCharState *s = chr->opaque;
2605 COMMCONFIG comcfg;
2606 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2607 COMSTAT comstat;
2608 DWORD size;
2609 DWORD err;
2611 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2612 if (!s->hsend) {
2613 fprintf(stderr, "Failed CreateEvent\n");
2614 goto fail;
2616 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2617 if (!s->hrecv) {
2618 fprintf(stderr, "Failed CreateEvent\n");
2619 goto fail;
2622 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2623 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2624 if (s->hcom == INVALID_HANDLE_VALUE) {
2625 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2626 s->hcom = NULL;
2627 goto fail;
2630 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2631 fprintf(stderr, "Failed SetupComm\n");
2632 goto fail;
2635 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2636 size = sizeof(COMMCONFIG);
2637 GetDefaultCommConfig(filename, &comcfg, &size);
2638 comcfg.dcb.DCBlength = sizeof(DCB);
2639 CommConfigDialog(filename, NULL, &comcfg);
2641 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2642 fprintf(stderr, "Failed SetCommState\n");
2643 goto fail;
2646 if (!SetCommMask(s->hcom, EV_ERR)) {
2647 fprintf(stderr, "Failed SetCommMask\n");
2648 goto fail;
2651 cto.ReadIntervalTimeout = MAXDWORD;
2652 if (!SetCommTimeouts(s->hcom, &cto)) {
2653 fprintf(stderr, "Failed SetCommTimeouts\n");
2654 goto fail;
2657 if (!ClearCommError(s->hcom, &err, &comstat)) {
2658 fprintf(stderr, "Failed ClearCommError\n");
2659 goto fail;
2661 qemu_add_polling_cb(win_chr_poll, chr);
2662 return 0;
2664 fail:
2665 win_chr_close(chr);
2666 return -1;
2669 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2671 WinCharState *s = chr->opaque;
2672 DWORD len, ret, size, err;
2674 len = len1;
2675 ZeroMemory(&s->osend, sizeof(s->osend));
2676 s->osend.hEvent = s->hsend;
2677 while (len > 0) {
2678 if (s->hsend)
2679 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2680 else
2681 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2682 if (!ret) {
2683 err = GetLastError();
2684 if (err == ERROR_IO_PENDING) {
2685 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2686 if (ret) {
2687 buf += size;
2688 len -= size;
2689 } else {
2690 break;
2692 } else {
2693 break;
2695 } else {
2696 buf += size;
2697 len -= size;
2700 return len1 - len;
2703 static int win_chr_read_poll(CharDriverState *chr)
2705 WinCharState *s = chr->opaque;
2707 s->max_size = qemu_chr_can_read(chr);
2708 return s->max_size;
2711 static void win_chr_readfile(CharDriverState *chr)
2713 WinCharState *s = chr->opaque;
2714 int ret, err;
2715 uint8_t buf[1024];
2716 DWORD size;
2718 ZeroMemory(&s->orecv, sizeof(s->orecv));
2719 s->orecv.hEvent = s->hrecv;
2720 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2721 if (!ret) {
2722 err = GetLastError();
2723 if (err == ERROR_IO_PENDING) {
2724 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2728 if (size > 0) {
2729 qemu_chr_read(chr, buf, size);
2733 static void win_chr_read(CharDriverState *chr)
2735 WinCharState *s = chr->opaque;
2737 if (s->len > s->max_size)
2738 s->len = s->max_size;
2739 if (s->len == 0)
2740 return;
2742 win_chr_readfile(chr);
2745 static int win_chr_poll(void *opaque)
2747 CharDriverState *chr = opaque;
2748 WinCharState *s = chr->opaque;
2749 COMSTAT status;
2750 DWORD comerr;
2752 ClearCommError(s->hcom, &comerr, &status);
2753 if (status.cbInQue > 0) {
2754 s->len = status.cbInQue;
2755 win_chr_read_poll(chr);
2756 win_chr_read(chr);
2757 return 1;
2759 return 0;
2762 static CharDriverState *qemu_chr_open_win(const char *filename)
2764 CharDriverState *chr;
2765 WinCharState *s;
2767 chr = qemu_mallocz(sizeof(CharDriverState));
2768 if (!chr)
2769 return NULL;
2770 s = qemu_mallocz(sizeof(WinCharState));
2771 if (!s) {
2772 free(chr);
2773 return NULL;
2775 chr->opaque = s;
2776 chr->chr_write = win_chr_write;
2777 chr->chr_close = win_chr_close;
2779 if (win_chr_init(chr, filename) < 0) {
2780 free(s);
2781 free(chr);
2782 return NULL;
2784 qemu_chr_reset(chr);
2785 return chr;
2788 static int win_chr_pipe_poll(void *opaque)
2790 CharDriverState *chr = opaque;
2791 WinCharState *s = chr->opaque;
2792 DWORD size;
2794 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2795 if (size > 0) {
2796 s->len = size;
2797 win_chr_read_poll(chr);
2798 win_chr_read(chr);
2799 return 1;
2801 return 0;
2804 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2806 WinCharState *s = chr->opaque;
2807 OVERLAPPED ov;
2808 int ret;
2809 DWORD size;
2810 char openname[256];
2812 s->fpipe = TRUE;
2814 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2815 if (!s->hsend) {
2816 fprintf(stderr, "Failed CreateEvent\n");
2817 goto fail;
2819 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2820 if (!s->hrecv) {
2821 fprintf(stderr, "Failed CreateEvent\n");
2822 goto fail;
2825 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2826 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2827 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2828 PIPE_WAIT,
2829 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2830 if (s->hcom == INVALID_HANDLE_VALUE) {
2831 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2832 s->hcom = NULL;
2833 goto fail;
2836 ZeroMemory(&ov, sizeof(ov));
2837 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2838 ret = ConnectNamedPipe(s->hcom, &ov);
2839 if (ret) {
2840 fprintf(stderr, "Failed ConnectNamedPipe\n");
2841 goto fail;
2844 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2845 if (!ret) {
2846 fprintf(stderr, "Failed GetOverlappedResult\n");
2847 if (ov.hEvent) {
2848 CloseHandle(ov.hEvent);
2849 ov.hEvent = NULL;
2851 goto fail;
2854 if (ov.hEvent) {
2855 CloseHandle(ov.hEvent);
2856 ov.hEvent = NULL;
2858 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2859 return 0;
2861 fail:
2862 win_chr_close(chr);
2863 return -1;
2867 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2869 CharDriverState *chr;
2870 WinCharState *s;
2872 chr = qemu_mallocz(sizeof(CharDriverState));
2873 if (!chr)
2874 return NULL;
2875 s = qemu_mallocz(sizeof(WinCharState));
2876 if (!s) {
2877 free(chr);
2878 return NULL;
2880 chr->opaque = s;
2881 chr->chr_write = win_chr_write;
2882 chr->chr_close = win_chr_close;
2884 if (win_chr_pipe_init(chr, filename) < 0) {
2885 free(s);
2886 free(chr);
2887 return NULL;
2889 qemu_chr_reset(chr);
2890 return chr;
2893 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2895 CharDriverState *chr;
2896 WinCharState *s;
2898 chr = qemu_mallocz(sizeof(CharDriverState));
2899 if (!chr)
2900 return NULL;
2901 s = qemu_mallocz(sizeof(WinCharState));
2902 if (!s) {
2903 free(chr);
2904 return NULL;
2906 s->hcom = fd_out;
2907 chr->opaque = s;
2908 chr->chr_write = win_chr_write;
2909 qemu_chr_reset(chr);
2910 return chr;
2913 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2915 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2918 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2920 HANDLE fd_out;
2922 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2923 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2924 if (fd_out == INVALID_HANDLE_VALUE)
2925 return NULL;
2927 return qemu_chr_open_win_file(fd_out);
2929 #endif /* !_WIN32 */
2931 /***********************************************************/
2932 /* UDP Net console */
2934 typedef struct {
2935 int fd;
2936 struct sockaddr_in daddr;
2937 uint8_t buf[1024];
2938 int bufcnt;
2939 int bufptr;
2940 int max_size;
2941 } NetCharDriver;
2943 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2945 NetCharDriver *s = chr->opaque;
2947 return sendto(s->fd, buf, len, 0,
2948 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2951 static int udp_chr_read_poll(void *opaque)
2953 CharDriverState *chr = opaque;
2954 NetCharDriver *s = chr->opaque;
2956 s->max_size = qemu_chr_can_read(chr);
2958 /* If there were any stray characters in the queue process them
2959 * first
2961 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2962 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2963 s->bufptr++;
2964 s->max_size = qemu_chr_can_read(chr);
2966 return s->max_size;
2969 static void udp_chr_read(void *opaque)
2971 CharDriverState *chr = opaque;
2972 NetCharDriver *s = chr->opaque;
2974 if (s->max_size == 0)
2975 return;
2976 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2977 s->bufptr = s->bufcnt;
2978 if (s->bufcnt <= 0)
2979 return;
2981 s->bufptr = 0;
2982 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2983 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2984 s->bufptr++;
2985 s->max_size = qemu_chr_can_read(chr);
2989 static void udp_chr_update_read_handler(CharDriverState *chr)
2991 NetCharDriver *s = chr->opaque;
2993 if (s->fd >= 0) {
2994 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2995 udp_chr_read, NULL, chr);
2999 #ifndef _WIN32
3000 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3001 #endif
3002 int parse_host_src_port(struct sockaddr_in *haddr,
3003 struct sockaddr_in *saddr,
3004 const char *str);
3006 static CharDriverState *qemu_chr_open_udp(const char *def)
3008 CharDriverState *chr = NULL;
3009 NetCharDriver *s = NULL;
3010 int fd = -1;
3011 struct sockaddr_in saddr;
3013 chr = qemu_mallocz(sizeof(CharDriverState));
3014 if (!chr)
3015 goto return_err;
3016 s = qemu_mallocz(sizeof(NetCharDriver));
3017 if (!s)
3018 goto return_err;
3020 fd = socket(PF_INET, SOCK_DGRAM, 0);
3021 if (fd < 0) {
3022 perror("socket(PF_INET, SOCK_DGRAM)");
3023 goto return_err;
3026 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3027 printf("Could not parse: %s\n", def);
3028 goto return_err;
3031 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3033 perror("bind");
3034 goto return_err;
3037 s->fd = fd;
3038 s->bufcnt = 0;
3039 s->bufptr = 0;
3040 chr->opaque = s;
3041 chr->chr_write = udp_chr_write;
3042 chr->chr_update_read_handler = udp_chr_update_read_handler;
3043 return chr;
3045 return_err:
3046 if (chr)
3047 free(chr);
3048 if (s)
3049 free(s);
3050 if (fd >= 0)
3051 closesocket(fd);
3052 return NULL;
3055 /***********************************************************/
3056 /* TCP Net console */
3058 typedef struct {
3059 int fd, listen_fd;
3060 int connected;
3061 int max_size;
3062 int do_telnetopt;
3063 int do_nodelay;
3064 int is_unix;
3065 } TCPCharDriver;
3067 static void tcp_chr_accept(void *opaque);
3069 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3071 TCPCharDriver *s = chr->opaque;
3072 if (s->connected) {
3073 return send_all(s->fd, buf, len);
3074 } else {
3075 /* XXX: indicate an error ? */
3076 return len;
3080 static int tcp_chr_read_poll(void *opaque)
3082 CharDriverState *chr = opaque;
3083 TCPCharDriver *s = chr->opaque;
3084 if (!s->connected)
3085 return 0;
3086 s->max_size = qemu_chr_can_read(chr);
3087 return s->max_size;
3090 #define IAC 255
3091 #define IAC_BREAK 243
3092 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3093 TCPCharDriver *s,
3094 uint8_t *buf, int *size)
3096 /* Handle any telnet client's basic IAC options to satisfy char by
3097 * char mode with no echo. All IAC options will be removed from
3098 * the buf and the do_telnetopt variable will be used to track the
3099 * state of the width of the IAC information.
3101 * IAC commands come in sets of 3 bytes with the exception of the
3102 * "IAC BREAK" command and the double IAC.
3105 int i;
3106 int j = 0;
3108 for (i = 0; i < *size; i++) {
3109 if (s->do_telnetopt > 1) {
3110 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3111 /* Double IAC means send an IAC */
3112 if (j != i)
3113 buf[j] = buf[i];
3114 j++;
3115 s->do_telnetopt = 1;
3116 } else {
3117 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3118 /* Handle IAC break commands by sending a serial break */
3119 qemu_chr_event(chr, CHR_EVENT_BREAK);
3120 s->do_telnetopt++;
3122 s->do_telnetopt++;
3124 if (s->do_telnetopt >= 4) {
3125 s->do_telnetopt = 1;
3127 } else {
3128 if ((unsigned char)buf[i] == IAC) {
3129 s->do_telnetopt = 2;
3130 } else {
3131 if (j != i)
3132 buf[j] = buf[i];
3133 j++;
3137 *size = j;
3140 static void tcp_chr_read(void *opaque)
3142 CharDriverState *chr = opaque;
3143 TCPCharDriver *s = chr->opaque;
3144 uint8_t buf[1024];
3145 int len, size;
3147 if (!s->connected || s->max_size <= 0)
3148 return;
3149 len = sizeof(buf);
3150 if (len > s->max_size)
3151 len = s->max_size;
3152 size = recv(s->fd, buf, len, 0);
3153 if (size == 0) {
3154 /* connection closed */
3155 s->connected = 0;
3156 if (s->listen_fd >= 0) {
3157 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3159 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3160 closesocket(s->fd);
3161 s->fd = -1;
3162 } else if (size > 0) {
3163 if (s->do_telnetopt)
3164 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3165 if (size > 0)
3166 qemu_chr_read(chr, buf, size);
3170 static void tcp_chr_connect(void *opaque)
3172 CharDriverState *chr = opaque;
3173 TCPCharDriver *s = chr->opaque;
3175 s->connected = 1;
3176 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3177 tcp_chr_read, NULL, chr);
3178 qemu_chr_reset(chr);
3181 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3182 static void tcp_chr_telnet_init(int fd)
3184 char buf[3];
3185 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3186 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3187 send(fd, (char *)buf, 3, 0);
3188 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3189 send(fd, (char *)buf, 3, 0);
3190 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3191 send(fd, (char *)buf, 3, 0);
3192 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3193 send(fd, (char *)buf, 3, 0);
3196 static void socket_set_nodelay(int fd)
3198 int val = 1;
3199 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3202 static void tcp_chr_accept(void *opaque)
3204 CharDriverState *chr = opaque;
3205 TCPCharDriver *s = chr->opaque;
3206 struct sockaddr_in saddr;
3207 #ifndef _WIN32
3208 struct sockaddr_un uaddr;
3209 #endif
3210 struct sockaddr *addr;
3211 socklen_t len;
3212 int fd;
3214 for(;;) {
3215 #ifndef _WIN32
3216 if (s->is_unix) {
3217 len = sizeof(uaddr);
3218 addr = (struct sockaddr *)&uaddr;
3219 } else
3220 #endif
3222 len = sizeof(saddr);
3223 addr = (struct sockaddr *)&saddr;
3225 fd = accept(s->listen_fd, addr, &len);
3226 if (fd < 0 && errno != EINTR) {
3227 return;
3228 } else if (fd >= 0) {
3229 if (s->do_telnetopt)
3230 tcp_chr_telnet_init(fd);
3231 break;
3234 socket_set_nonblock(fd);
3235 if (s->do_nodelay)
3236 socket_set_nodelay(fd);
3237 s->fd = fd;
3238 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3239 tcp_chr_connect(chr);
3242 static void tcp_chr_close(CharDriverState *chr)
3244 TCPCharDriver *s = chr->opaque;
3245 if (s->fd >= 0)
3246 closesocket(s->fd);
3247 if (s->listen_fd >= 0)
3248 closesocket(s->listen_fd);
3249 qemu_free(s);
3252 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3253 int is_telnet,
3254 int is_unix)
3256 CharDriverState *chr = NULL;
3257 TCPCharDriver *s = NULL;
3258 int fd = -1, ret, err, val;
3259 int is_listen = 0;
3260 int is_waitconnect = 1;
3261 int do_nodelay = 0;
3262 const char *ptr;
3263 struct sockaddr_in saddr;
3264 #ifndef _WIN32
3265 struct sockaddr_un uaddr;
3266 #endif
3267 struct sockaddr *addr;
3268 socklen_t addrlen;
3270 #ifndef _WIN32
3271 if (is_unix) {
3272 addr = (struct sockaddr *)&uaddr;
3273 addrlen = sizeof(uaddr);
3274 if (parse_unix_path(&uaddr, host_str) < 0)
3275 goto fail;
3276 } else
3277 #endif
3279 addr = (struct sockaddr *)&saddr;
3280 addrlen = sizeof(saddr);
3281 if (parse_host_port(&saddr, host_str) < 0)
3282 goto fail;
3285 ptr = host_str;
3286 while((ptr = strchr(ptr,','))) {
3287 ptr++;
3288 if (!strncmp(ptr,"server",6)) {
3289 is_listen = 1;
3290 } else if (!strncmp(ptr,"nowait",6)) {
3291 is_waitconnect = 0;
3292 } else if (!strncmp(ptr,"nodelay",6)) {
3293 do_nodelay = 1;
3294 } else {
3295 printf("Unknown option: %s\n", ptr);
3296 goto fail;
3299 if (!is_listen)
3300 is_waitconnect = 0;
3302 chr = qemu_mallocz(sizeof(CharDriverState));
3303 if (!chr)
3304 goto fail;
3305 s = qemu_mallocz(sizeof(TCPCharDriver));
3306 if (!s)
3307 goto fail;
3309 #ifndef _WIN32
3310 if (is_unix)
3311 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3312 else
3313 #endif
3314 fd = socket(PF_INET, SOCK_STREAM, 0);
3316 if (fd < 0)
3317 goto fail;
3319 if (!is_waitconnect)
3320 socket_set_nonblock(fd);
3322 s->connected = 0;
3323 s->fd = -1;
3324 s->listen_fd = -1;
3325 s->is_unix = is_unix;
3326 s->do_nodelay = do_nodelay && !is_unix;
3328 chr->opaque = s;
3329 chr->chr_write = tcp_chr_write;
3330 chr->chr_close = tcp_chr_close;
3332 if (is_listen) {
3333 /* allow fast reuse */
3334 #ifndef _WIN32
3335 if (is_unix) {
3336 char path[109];
3337 strncpy(path, uaddr.sun_path, 108);
3338 path[108] = 0;
3339 unlink(path);
3340 } else
3341 #endif
3343 val = 1;
3344 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3347 ret = bind(fd, addr, addrlen);
3348 if (ret < 0)
3349 goto fail;
3351 ret = listen(fd, 0);
3352 if (ret < 0)
3353 goto fail;
3355 s->listen_fd = fd;
3356 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3357 if (is_telnet)
3358 s->do_telnetopt = 1;
3359 } else {
3360 for(;;) {
3361 ret = connect(fd, addr, addrlen);
3362 if (ret < 0) {
3363 err = socket_error();
3364 if (err == EINTR || err == EWOULDBLOCK) {
3365 } else if (err == EINPROGRESS) {
3366 break;
3367 #ifdef _WIN32
3368 } else if (err == WSAEALREADY) {
3369 break;
3370 #endif
3371 } else {
3372 goto fail;
3374 } else {
3375 s->connected = 1;
3376 break;
3379 s->fd = fd;
3380 socket_set_nodelay(fd);
3381 if (s->connected)
3382 tcp_chr_connect(chr);
3383 else
3384 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3387 if (is_listen && is_waitconnect) {
3388 printf("QEMU waiting for connection on: %s\n", host_str);
3389 tcp_chr_accept(chr);
3390 socket_set_nonblock(s->listen_fd);
3393 return chr;
3394 fail:
3395 if (fd >= 0)
3396 closesocket(fd);
3397 qemu_free(s);
3398 qemu_free(chr);
3399 return NULL;
3402 CharDriverState *qemu_chr_open(const char *filename)
3404 const char *p;
3406 if (!strcmp(filename, "vc")) {
3407 return text_console_init(&display_state, 0);
3408 } else if (strstart(filename, "vc:", &p)) {
3409 return text_console_init(&display_state, p);
3410 } else if (!strcmp(filename, "null")) {
3411 return qemu_chr_open_null();
3412 } else
3413 if (strstart(filename, "tcp:", &p)) {
3414 return qemu_chr_open_tcp(p, 0, 0);
3415 } else
3416 if (strstart(filename, "telnet:", &p)) {
3417 return qemu_chr_open_tcp(p, 1, 0);
3418 } else
3419 if (strstart(filename, "udp:", &p)) {
3420 return qemu_chr_open_udp(p);
3421 } else
3422 if (strstart(filename, "mon:", &p)) {
3423 CharDriverState *drv = qemu_chr_open(p);
3424 if (drv) {
3425 drv = qemu_chr_open_mux(drv);
3426 monitor_init(drv, !nographic);
3427 return drv;
3429 printf("Unable to open driver: %s\n", p);
3430 return 0;
3431 } else
3432 #ifndef _WIN32
3433 if (strstart(filename, "unix:", &p)) {
3434 return qemu_chr_open_tcp(p, 0, 1);
3435 } else if (strstart(filename, "file:", &p)) {
3436 return qemu_chr_open_file_out(p);
3437 } else if (strstart(filename, "pipe:", &p)) {
3438 return qemu_chr_open_pipe(p);
3439 } else if (!strcmp(filename, "pty")) {
3440 return qemu_chr_open_pty();
3441 } else if (!strcmp(filename, "stdio")) {
3442 return qemu_chr_open_stdio();
3443 } else
3444 #if defined(__linux__)
3445 if (strstart(filename, "/dev/parport", NULL)) {
3446 return qemu_chr_open_pp(filename);
3447 } else
3448 #endif
3449 #if defined(__linux__) || defined(__sun__)
3450 if (strstart(filename, "/dev/", NULL)) {
3451 return qemu_chr_open_tty(filename);
3452 } else
3453 #endif
3454 #else /* !_WIN32 */
3455 if (strstart(filename, "COM", NULL)) {
3456 return qemu_chr_open_win(filename);
3457 } else
3458 if (strstart(filename, "pipe:", &p)) {
3459 return qemu_chr_open_win_pipe(p);
3460 } else
3461 if (strstart(filename, "con:", NULL)) {
3462 return qemu_chr_open_win_con(filename);
3463 } else
3464 if (strstart(filename, "file:", &p)) {
3465 return qemu_chr_open_win_file_out(p);
3467 #endif
3469 return NULL;
3473 void qemu_chr_close(CharDriverState *chr)
3475 if (chr->chr_close)
3476 chr->chr_close(chr);
3477 qemu_free(chr);
3480 /***********************************************************/
3481 /* network device redirectors */
3483 __attribute__ (( unused ))
3484 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3486 int len, i, j, c;
3488 for(i=0;i<size;i+=16) {
3489 len = size - i;
3490 if (len > 16)
3491 len = 16;
3492 fprintf(f, "%08x ", i);
3493 for(j=0;j<16;j++) {
3494 if (j < len)
3495 fprintf(f, " %02x", buf[i+j]);
3496 else
3497 fprintf(f, " ");
3499 fprintf(f, " ");
3500 for(j=0;j<len;j++) {
3501 c = buf[i+j];
3502 if (c < ' ' || c > '~')
3503 c = '.';
3504 fprintf(f, "%c", c);
3506 fprintf(f, "\n");
3510 static int parse_macaddr(uint8_t *macaddr, const char *p)
3512 int i;
3513 char *last_char;
3514 long int offset;
3516 errno = 0;
3517 offset = strtol(p, &last_char, 0);
3518 if (0 == errno && '\0' == *last_char &&
3519 offset >= 0 && offset <= 0xFFFFFF) {
3520 macaddr[3] = (offset & 0xFF0000) >> 16;
3521 macaddr[4] = (offset & 0xFF00) >> 8;
3522 macaddr[5] = offset & 0xFF;
3523 return 0;
3524 } else {
3525 for(i = 0; i < 6; i++) {
3526 macaddr[i] = strtol(p, (char **)&p, 16);
3527 if (i == 5) {
3528 if (*p != '\0')
3529 return -1;
3530 } else {
3531 if (*p != ':' && *p != '-')
3532 return -1;
3533 p++;
3536 return 0;
3539 return -1;
3542 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3544 const char *p, *p1;
3545 int len;
3546 p = *pp;
3547 p1 = strchr(p, sep);
3548 if (!p1)
3549 return -1;
3550 len = p1 - p;
3551 p1++;
3552 if (buf_size > 0) {
3553 if (len > buf_size - 1)
3554 len = buf_size - 1;
3555 memcpy(buf, p, len);
3556 buf[len] = '\0';
3558 *pp = p1;
3559 return 0;
3562 int parse_host_src_port(struct sockaddr_in *haddr,
3563 struct sockaddr_in *saddr,
3564 const char *input_str)
3566 char *str = strdup(input_str);
3567 char *host_str = str;
3568 char *src_str;
3569 char *ptr;
3572 * Chop off any extra arguments at the end of the string which
3573 * would start with a comma, then fill in the src port information
3574 * if it was provided else use the "any address" and "any port".
3576 if ((ptr = strchr(str,',')))
3577 *ptr = '\0';
3579 if ((src_str = strchr(input_str,'@'))) {
3580 *src_str = '\0';
3581 src_str++;
3584 if (parse_host_port(haddr, host_str) < 0)
3585 goto fail;
3587 if (!src_str || *src_str == '\0')
3588 src_str = ":0";
3590 if (parse_host_port(saddr, src_str) < 0)
3591 goto fail;
3593 free(str);
3594 return(0);
3596 fail:
3597 free(str);
3598 return -1;
3601 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3603 char buf[512];
3604 struct hostent *he;
3605 const char *p, *r;
3606 int port;
3608 p = str;
3609 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3610 return -1;
3611 saddr->sin_family = AF_INET;
3612 if (buf[0] == '\0') {
3613 saddr->sin_addr.s_addr = 0;
3614 } else {
3615 if (isdigit(buf[0])) {
3616 if (!inet_aton(buf, &saddr->sin_addr))
3617 return -1;
3618 } else {
3619 if ((he = gethostbyname(buf)) == NULL)
3620 return - 1;
3621 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3624 port = strtol(p, (char **)&r, 0);
3625 if (r == p)
3626 return -1;
3627 saddr->sin_port = htons(port);
3628 return 0;
3631 #ifndef _WIN32
3632 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3634 const char *p;
3635 int len;
3637 len = MIN(108, strlen(str));
3638 p = strchr(str, ',');
3639 if (p)
3640 len = MIN(len, p - str);
3642 memset(uaddr, 0, sizeof(*uaddr));
3644 uaddr->sun_family = AF_UNIX;
3645 memcpy(uaddr->sun_path, str, len);
3647 return 0;
3649 #endif
3651 /* find or alloc a new VLAN */
3652 VLANState *qemu_find_vlan(int id)
3654 VLANState **pvlan, *vlan;
3655 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3656 if (vlan->id == id)
3657 return vlan;
3659 vlan = qemu_mallocz(sizeof(VLANState));
3660 if (!vlan)
3661 return NULL;
3662 vlan->id = id;
3663 vlan->next = NULL;
3664 pvlan = &first_vlan;
3665 while (*pvlan != NULL)
3666 pvlan = &(*pvlan)->next;
3667 *pvlan = vlan;
3668 return vlan;
3671 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3672 IOReadHandler *fd_read,
3673 IOCanRWHandler *fd_can_read,
3674 void *opaque)
3676 VLANClientState *vc, **pvc;
3677 vc = qemu_mallocz(sizeof(VLANClientState));
3678 if (!vc)
3679 return NULL;
3680 vc->fd_read = fd_read;
3681 vc->fd_can_read = fd_can_read;
3682 vc->opaque = opaque;
3683 vc->vlan = vlan;
3685 vc->next = NULL;
3686 pvc = &vlan->first_client;
3687 while (*pvc != NULL)
3688 pvc = &(*pvc)->next;
3689 *pvc = vc;
3690 return vc;
3693 int qemu_can_send_packet(VLANClientState *vc1)
3695 VLANState *vlan = vc1->vlan;
3696 VLANClientState *vc;
3698 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3699 if (vc != vc1) {
3700 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3701 return 1;
3704 return 0;
3707 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3709 VLANState *vlan = vc1->vlan;
3710 VLANClientState *vc;
3712 #if 0
3713 printf("vlan %d send:\n", vlan->id);
3714 hex_dump(stdout, buf, size);
3715 #endif
3716 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3717 if (vc != vc1) {
3718 vc->fd_read(vc->opaque, buf, size);
3723 #if defined(CONFIG_SLIRP)
3725 /* slirp network adapter */
3727 static int slirp_inited;
3728 static VLANClientState *slirp_vc;
3730 int slirp_can_output(void)
3732 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3735 void slirp_output(const uint8_t *pkt, int pkt_len)
3737 #if 0
3738 printf("slirp output:\n");
3739 hex_dump(stdout, pkt, pkt_len);
3740 #endif
3741 if (!slirp_vc)
3742 return;
3743 qemu_send_packet(slirp_vc, pkt, pkt_len);
3746 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3748 #if 0
3749 printf("slirp input:\n");
3750 hex_dump(stdout, buf, size);
3751 #endif
3752 slirp_input(buf, size);
3755 static int net_slirp_init(VLANState *vlan)
3757 if (!slirp_inited) {
3758 slirp_inited = 1;
3759 slirp_init();
3761 slirp_vc = qemu_new_vlan_client(vlan,
3762 slirp_receive, NULL, NULL);
3763 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3764 return 0;
3767 static void net_slirp_redir(const char *redir_str)
3769 int is_udp;
3770 char buf[256], *r;
3771 const char *p;
3772 struct in_addr guest_addr;
3773 int host_port, guest_port;
3775 if (!slirp_inited) {
3776 slirp_inited = 1;
3777 slirp_init();
3780 p = redir_str;
3781 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3782 goto fail;
3783 if (!strcmp(buf, "tcp")) {
3784 is_udp = 0;
3785 } else if (!strcmp(buf, "udp")) {
3786 is_udp = 1;
3787 } else {
3788 goto fail;
3791 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3792 goto fail;
3793 host_port = strtol(buf, &r, 0);
3794 if (r == buf)
3795 goto fail;
3797 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3798 goto fail;
3799 if (buf[0] == '\0') {
3800 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3802 if (!inet_aton(buf, &guest_addr))
3803 goto fail;
3805 guest_port = strtol(p, &r, 0);
3806 if (r == p)
3807 goto fail;
3809 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3810 fprintf(stderr, "qemu: could not set up redirection\n");
3811 exit(1);
3813 return;
3814 fail:
3815 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3816 exit(1);
3819 #ifndef _WIN32
3821 char smb_dir[1024];
3823 static void erase_dir(char *dir_name)
3825 DIR *d;
3826 struct dirent *de;
3827 char filename[1024];
3829 /* erase all the files in the directory */
3830 if ((d = opendir(dir_name)) != 0) {
3831 for(;;) {
3832 de = readdir(d);
3833 if (!de)
3834 break;
3835 if (strcmp(de->d_name, ".") != 0 &&
3836 strcmp(de->d_name, "..") != 0) {
3837 snprintf(filename, sizeof(filename), "%s/%s",
3838 smb_dir, de->d_name);
3839 if (unlink(filename) != 0) /* is it a directory? */
3840 erase_dir(filename);
3843 closedir(d);
3844 rmdir(dir_name);
3848 /* automatic user mode samba server configuration */
3849 static void smb_exit(void)
3851 erase_dir(smb_dir);
3854 /* automatic user mode samba server configuration */
3855 static void net_slirp_smb(const char *exported_dir)
3857 char smb_conf[1024];
3858 char smb_cmdline[1024];
3859 FILE *f;
3861 if (!slirp_inited) {
3862 slirp_inited = 1;
3863 slirp_init();
3866 /* XXX: better tmp dir construction */
3867 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3868 if (mkdir(smb_dir, 0700) < 0) {
3869 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3870 exit(1);
3872 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3874 f = fopen(smb_conf, "w");
3875 if (!f) {
3876 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3877 exit(1);
3879 fprintf(f,
3880 "[global]\n"
3881 "private dir=%s\n"
3882 "smb ports=0\n"
3883 "socket address=127.0.0.1\n"
3884 "pid directory=%s\n"
3885 "lock directory=%s\n"
3886 "log file=%s/log.smbd\n"
3887 "smb passwd file=%s/smbpasswd\n"
3888 "security = share\n"
3889 "[qemu]\n"
3890 "path=%s\n"
3891 "read only=no\n"
3892 "guest ok=yes\n",
3893 smb_dir,
3894 smb_dir,
3895 smb_dir,
3896 smb_dir,
3897 smb_dir,
3898 exported_dir
3900 fclose(f);
3901 atexit(smb_exit);
3903 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3904 SMBD_COMMAND, smb_conf);
3906 slirp_add_exec(0, smb_cmdline, 4, 139);
3909 #endif /* !defined(_WIN32) */
3910 void do_info_slirp(void)
3912 slirp_stats();
3915 #endif /* CONFIG_SLIRP */
3917 #if !defined(_WIN32)
3919 typedef struct TAPState {
3920 VLANClientState *vc;
3921 int fd;
3922 char down_script[1024];
3923 int no_poll;
3924 } TAPState;
3926 static int tap_read_poll(void *opaque)
3928 TAPState *s = opaque;
3929 return (!s->no_poll);
3932 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3934 TAPState *s = opaque;
3935 int ret;
3936 for(;;) {
3937 ret = write(s->fd, buf, size);
3938 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3939 } else {
3940 break;
3945 static void tap_send(void *opaque)
3947 TAPState *s = opaque;
3948 uint8_t buf[4096];
3949 int size;
3951 #ifdef __sun__
3952 struct strbuf sbuf;
3953 int f = 0;
3954 sbuf.maxlen = sizeof(buf);
3955 sbuf.buf = buf;
3956 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3957 #else
3958 size = read(s->fd, buf, sizeof(buf));
3959 #endif
3960 if (size > 0) {
3961 qemu_send_packet(s->vc, buf, size);
3965 int hack_around_tap(void *opaque)
3967 VLANClientState *vc = opaque;
3968 TAPState *ts = vc->opaque;
3970 if (vc->fd_read != tap_receive)
3971 return -1;
3973 if (ts) {
3974 ts->no_poll = 1;
3975 return ts->fd;
3978 return -1;
3981 /* fd support */
3983 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3985 TAPState *s;
3987 s = qemu_mallocz(sizeof(TAPState));
3988 if (!s)
3989 return NULL;
3990 s->fd = fd;
3991 s->no_poll = 0;
3992 enable_sigio_timer(fd);
3993 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3994 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
3995 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3996 return s;
3999 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4000 static int tap_open(char *ifname, int ifname_size)
4002 int fd;
4003 char *dev;
4004 struct stat s;
4006 TFR(fd = open("/dev/tap", O_RDWR));
4007 if (fd < 0) {
4008 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4009 return -1;
4012 fstat(fd, &s);
4013 dev = devname(s.st_rdev, S_IFCHR);
4014 pstrcpy(ifname, ifname_size, dev);
4016 fcntl(fd, F_SETFL, O_NONBLOCK);
4017 return fd;
4019 #elif defined(__sun__)
4020 #define TUNNEWPPA (('T'<<16) | 0x0001)
4022 * Allocate TAP device, returns opened fd.
4023 * Stores dev name in the first arg(must be large enough).
4025 int tap_alloc(char *dev)
4027 int tap_fd, if_fd, ppa = -1;
4028 static int ip_fd = 0;
4029 char *ptr;
4031 static int arp_fd = 0;
4032 int ip_muxid, arp_muxid;
4033 struct strioctl strioc_if, strioc_ppa;
4034 int link_type = I_PLINK;;
4035 struct lifreq ifr;
4036 char actual_name[32] = "";
4038 memset(&ifr, 0x0, sizeof(ifr));
4040 if( *dev ){
4041 ptr = dev;
4042 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4043 ppa = atoi(ptr);
4046 /* Check if IP device was opened */
4047 if( ip_fd )
4048 close(ip_fd);
4050 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4051 if (ip_fd < 0) {
4052 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4053 return -1;
4056 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4057 if (tap_fd < 0) {
4058 syslog(LOG_ERR, "Can't open /dev/tap");
4059 return -1;
4062 /* Assign a new PPA and get its unit number. */
4063 strioc_ppa.ic_cmd = TUNNEWPPA;
4064 strioc_ppa.ic_timout = 0;
4065 strioc_ppa.ic_len = sizeof(ppa);
4066 strioc_ppa.ic_dp = (char *)&ppa;
4067 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4068 syslog (LOG_ERR, "Can't assign new interface");
4070 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4071 if (if_fd < 0) {
4072 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4073 return -1;
4075 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4076 syslog(LOG_ERR, "Can't push IP module");
4077 return -1;
4080 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4081 syslog(LOG_ERR, "Can't get flags\n");
4083 snprintf (actual_name, 32, "tap%d", ppa);
4084 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4086 ifr.lifr_ppa = ppa;
4087 /* Assign ppa according to the unit number returned by tun device */
4089 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4090 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4091 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4092 syslog (LOG_ERR, "Can't get flags\n");
4093 /* Push arp module to if_fd */
4094 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4095 syslog (LOG_ERR, "Can't push ARP module (2)");
4097 /* Push arp module to ip_fd */
4098 if (ioctl (ip_fd, I_POP, NULL) < 0)
4099 syslog (LOG_ERR, "I_POP failed\n");
4100 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4101 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4102 /* Open arp_fd */
4103 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4104 if (arp_fd < 0)
4105 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4107 /* Set ifname to arp */
4108 strioc_if.ic_cmd = SIOCSLIFNAME;
4109 strioc_if.ic_timout = 0;
4110 strioc_if.ic_len = sizeof(ifr);
4111 strioc_if.ic_dp = (char *)&ifr;
4112 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4113 syslog (LOG_ERR, "Can't set ifname to arp\n");
4116 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4117 syslog(LOG_ERR, "Can't link TAP device to IP");
4118 return -1;
4121 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4122 syslog (LOG_ERR, "Can't link TAP device to ARP");
4124 close (if_fd);
4126 memset(&ifr, 0x0, sizeof(ifr));
4127 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4128 ifr.lifr_ip_muxid = ip_muxid;
4129 ifr.lifr_arp_muxid = arp_muxid;
4131 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4133 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4134 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4135 syslog (LOG_ERR, "Can't set multiplexor id");
4138 sprintf(dev, "tap%d", ppa);
4139 return tap_fd;
4142 static int tap_open(char *ifname, int ifname_size)
4144 char dev[10]="";
4145 int fd;
4146 if( (fd = tap_alloc(dev)) < 0 ){
4147 fprintf(stderr, "Cannot allocate TAP device\n");
4148 return -1;
4150 pstrcpy(ifname, ifname_size, dev);
4151 fcntl(fd, F_SETFL, O_NONBLOCK);
4152 return fd;
4154 #else
4155 static int tap_open(char *ifname, int ifname_size)
4157 struct ifreq ifr;
4158 int fd, ret;
4160 TFR(fd = open("/dev/net/tun", O_RDWR));
4161 if (fd < 0) {
4162 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4163 return -1;
4165 memset(&ifr, 0, sizeof(ifr));
4166 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4167 if (ifname[0] != '\0')
4168 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4169 else
4170 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4171 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4172 if (ret != 0) {
4173 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4174 close(fd);
4175 return -1;
4177 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4178 fcntl(fd, F_SETFL, O_NONBLOCK);
4179 return fd;
4181 #endif
4183 static int launch_script(const char *setup_script, const char *ifname, int fd)
4185 int pid, status;
4186 char *args[3];
4187 char **parg;
4189 /* try to launch network script */
4190 pid = fork();
4191 if (pid >= 0) {
4192 if (pid == 0) {
4193 int open_max = sysconf (_SC_OPEN_MAX), i;
4194 for (i = 0; i < open_max; i++)
4195 if (i != STDIN_FILENO &&
4196 i != STDOUT_FILENO &&
4197 i != STDERR_FILENO &&
4198 i != fd)
4199 close(i);
4201 parg = args;
4202 *parg++ = (char *)setup_script;
4203 *parg++ = (char *)ifname;
4204 *parg++ = NULL;
4205 execv(setup_script, args);
4206 _exit(1);
4208 while (waitpid(pid, &status, 0) != pid);
4209 if (!WIFEXITED(status) ||
4210 WEXITSTATUS(status) != 0) {
4211 fprintf(stderr, "%s: could not launch network script\n",
4212 setup_script);
4213 return -1;
4216 return 0;
4219 static int net_tap_init(VLANState *vlan, const char *ifname1,
4220 const char *setup_script, const char *down_script)
4222 TAPState *s;
4223 int fd;
4224 char ifname[128];
4226 if (ifname1 != NULL)
4227 pstrcpy(ifname, sizeof(ifname), ifname1);
4228 else
4229 ifname[0] = '\0';
4230 TFR(fd = tap_open(ifname, sizeof(ifname)));
4231 if (fd < 0)
4232 return -1;
4234 if (!setup_script || !strcmp(setup_script, "no"))
4235 setup_script = "";
4236 if (setup_script[0] != '\0') {
4237 if (launch_script(setup_script, ifname, fd))
4238 return -1;
4240 s = net_tap_fd_init(vlan, fd);
4241 if (!s)
4242 return -1;
4243 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4244 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4245 if (down_script && strcmp(down_script, "no"))
4246 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4247 return 0;
4250 #endif /* !_WIN32 */
4252 /* network connection */
4253 typedef struct NetSocketState {
4254 VLANClientState *vc;
4255 int fd;
4256 int state; /* 0 = getting length, 1 = getting data */
4257 int index;
4258 int packet_len;
4259 uint8_t buf[4096];
4260 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4261 } NetSocketState;
4263 typedef struct NetSocketListenState {
4264 VLANState *vlan;
4265 int fd;
4266 } NetSocketListenState;
4268 /* XXX: we consider we can send the whole packet without blocking */
4269 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4271 NetSocketState *s = opaque;
4272 uint32_t len;
4273 len = htonl(size);
4275 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4276 send_all(s->fd, buf, size);
4279 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4281 NetSocketState *s = opaque;
4282 sendto(s->fd, buf, size, 0,
4283 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4286 static void net_socket_send(void *opaque)
4288 NetSocketState *s = opaque;
4289 int l, size, err;
4290 uint8_t buf1[4096];
4291 const uint8_t *buf;
4293 size = recv(s->fd, buf1, sizeof(buf1), 0);
4294 if (size < 0) {
4295 err = socket_error();
4296 if (err != EWOULDBLOCK)
4297 goto eoc;
4298 } else if (size == 0) {
4299 /* end of connection */
4300 eoc:
4301 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4302 closesocket(s->fd);
4303 return;
4305 buf = buf1;
4306 while (size > 0) {
4307 /* reassemble a packet from the network */
4308 switch(s->state) {
4309 case 0:
4310 l = 4 - s->index;
4311 if (l > size)
4312 l = size;
4313 memcpy(s->buf + s->index, buf, l);
4314 buf += l;
4315 size -= l;
4316 s->index += l;
4317 if (s->index == 4) {
4318 /* got length */
4319 s->packet_len = ntohl(*(uint32_t *)s->buf);
4320 s->index = 0;
4321 s->state = 1;
4323 break;
4324 case 1:
4325 l = s->packet_len - s->index;
4326 if (l > size)
4327 l = size;
4328 memcpy(s->buf + s->index, buf, l);
4329 s->index += l;
4330 buf += l;
4331 size -= l;
4332 if (s->index >= s->packet_len) {
4333 qemu_send_packet(s->vc, s->buf, s->packet_len);
4334 s->index = 0;
4335 s->state = 0;
4337 break;
4342 static void net_socket_send_dgram(void *opaque)
4344 NetSocketState *s = opaque;
4345 int size;
4347 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4348 if (size < 0)
4349 return;
4350 if (size == 0) {
4351 /* end of connection */
4352 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4353 return;
4355 qemu_send_packet(s->vc, s->buf, size);
4358 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4360 struct ip_mreq imr;
4361 int fd;
4362 int val, ret;
4363 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4364 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4365 inet_ntoa(mcastaddr->sin_addr),
4366 (int)ntohl(mcastaddr->sin_addr.s_addr));
4367 return -1;
4370 fd = socket(PF_INET, SOCK_DGRAM, 0);
4371 if (fd < 0) {
4372 perror("socket(PF_INET, SOCK_DGRAM)");
4373 return -1;
4376 val = 1;
4377 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4378 (const char *)&val, sizeof(val));
4379 if (ret < 0) {
4380 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4381 goto fail;
4384 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4385 if (ret < 0) {
4386 perror("bind");
4387 goto fail;
4390 /* Add host to multicast group */
4391 imr.imr_multiaddr = mcastaddr->sin_addr;
4392 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4394 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4395 (const char *)&imr, sizeof(struct ip_mreq));
4396 if (ret < 0) {
4397 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4398 goto fail;
4401 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4402 val = 1;
4403 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4404 (const char *)&val, sizeof(val));
4405 if (ret < 0) {
4406 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4407 goto fail;
4410 socket_set_nonblock(fd);
4411 return fd;
4412 fail:
4413 if (fd >= 0)
4414 closesocket(fd);
4415 return -1;
4418 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4419 int is_connected)
4421 struct sockaddr_in saddr;
4422 int newfd;
4423 socklen_t saddr_len;
4424 NetSocketState *s;
4426 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4427 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4428 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4431 if (is_connected) {
4432 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4433 /* must be bound */
4434 if (saddr.sin_addr.s_addr==0) {
4435 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4436 fd);
4437 return NULL;
4439 /* clone dgram socket */
4440 newfd = net_socket_mcast_create(&saddr);
4441 if (newfd < 0) {
4442 /* error already reported by net_socket_mcast_create() */
4443 close(fd);
4444 return NULL;
4446 /* clone newfd to fd, close newfd */
4447 dup2(newfd, fd);
4448 close(newfd);
4450 } else {
4451 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4452 fd, strerror(errno));
4453 return NULL;
4457 s = qemu_mallocz(sizeof(NetSocketState));
4458 if (!s)
4459 return NULL;
4460 s->fd = fd;
4462 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4463 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4465 /* mcast: save bound address as dst */
4466 if (is_connected) s->dgram_dst=saddr;
4468 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4469 "socket: fd=%d (%s mcast=%s:%d)",
4470 fd, is_connected? "cloned" : "",
4471 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4472 return s;
4475 static void net_socket_connect(void *opaque)
4477 NetSocketState *s = opaque;
4478 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4481 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4482 int is_connected)
4484 NetSocketState *s;
4485 s = qemu_mallocz(sizeof(NetSocketState));
4486 if (!s)
4487 return NULL;
4488 s->fd = fd;
4489 s->vc = qemu_new_vlan_client(vlan,
4490 net_socket_receive, NULL, s);
4491 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4492 "socket: fd=%d", fd);
4493 if (is_connected) {
4494 net_socket_connect(s);
4495 } else {
4496 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4498 return s;
4501 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4502 int is_connected)
4504 int so_type=-1, optlen=sizeof(so_type);
4506 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4507 (socklen_t *)&optlen)< 0) {
4508 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4509 return NULL;
4511 switch(so_type) {
4512 case SOCK_DGRAM:
4513 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4514 case SOCK_STREAM:
4515 return net_socket_fd_init_stream(vlan, fd, is_connected);
4516 default:
4517 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4518 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4519 return net_socket_fd_init_stream(vlan, fd, is_connected);
4521 return NULL;
4524 static void net_socket_accept(void *opaque)
4526 NetSocketListenState *s = opaque;
4527 NetSocketState *s1;
4528 struct sockaddr_in saddr;
4529 socklen_t len;
4530 int fd;
4532 for(;;) {
4533 len = sizeof(saddr);
4534 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4535 if (fd < 0 && errno != EINTR) {
4536 return;
4537 } else if (fd >= 0) {
4538 break;
4541 s1 = net_socket_fd_init(s->vlan, fd, 1);
4542 if (!s1) {
4543 closesocket(fd);
4544 } else {
4545 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4546 "socket: connection from %s:%d",
4547 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4551 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4553 NetSocketListenState *s;
4554 int fd, val, ret;
4555 struct sockaddr_in saddr;
4557 if (parse_host_port(&saddr, host_str) < 0)
4558 return -1;
4560 s = qemu_mallocz(sizeof(NetSocketListenState));
4561 if (!s)
4562 return -1;
4564 fd = socket(PF_INET, SOCK_STREAM, 0);
4565 if (fd < 0) {
4566 perror("socket");
4567 return -1;
4569 socket_set_nonblock(fd);
4571 /* allow fast reuse */
4572 val = 1;
4573 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4575 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4576 if (ret < 0) {
4577 perror("bind");
4578 return -1;
4580 ret = listen(fd, 0);
4581 if (ret < 0) {
4582 perror("listen");
4583 return -1;
4585 s->vlan = vlan;
4586 s->fd = fd;
4587 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4588 return 0;
4591 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4593 NetSocketState *s;
4594 int fd, connected, ret, err;
4595 struct sockaddr_in saddr;
4597 if (parse_host_port(&saddr, host_str) < 0)
4598 return -1;
4600 fd = socket(PF_INET, SOCK_STREAM, 0);
4601 if (fd < 0) {
4602 perror("socket");
4603 return -1;
4605 socket_set_nonblock(fd);
4607 connected = 0;
4608 for(;;) {
4609 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4610 if (ret < 0) {
4611 err = socket_error();
4612 if (err == EINTR || err == EWOULDBLOCK) {
4613 } else if (err == EINPROGRESS) {
4614 break;
4615 #ifdef _WIN32
4616 } else if (err == WSAEALREADY) {
4617 break;
4618 #endif
4619 } else {
4620 perror("connect");
4621 closesocket(fd);
4622 return -1;
4624 } else {
4625 connected = 1;
4626 break;
4629 s = net_socket_fd_init(vlan, fd, connected);
4630 if (!s)
4631 return -1;
4632 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4633 "socket: connect to %s:%d",
4634 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4635 return 0;
4638 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4640 NetSocketState *s;
4641 int fd;
4642 struct sockaddr_in saddr;
4644 if (parse_host_port(&saddr, host_str) < 0)
4645 return -1;
4648 fd = net_socket_mcast_create(&saddr);
4649 if (fd < 0)
4650 return -1;
4652 s = net_socket_fd_init(vlan, fd, 0);
4653 if (!s)
4654 return -1;
4656 s->dgram_dst = saddr;
4658 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4659 "socket: mcast=%s:%d",
4660 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4661 return 0;
4665 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4667 char *q;
4669 q = buf;
4670 while (*p != '\0' && *p != '=') {
4671 if (q && (q - buf) < buf_size - 1)
4672 *q++ = *p;
4673 p++;
4675 if (q)
4676 *q = '\0';
4678 return p;
4681 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4683 char *q;
4685 q = buf;
4686 while (*p != '\0') {
4687 if (*p == ',') {
4688 if (*(p + 1) != ',')
4689 break;
4690 p++;
4692 if (q && (q - buf) < buf_size - 1)
4693 *q++ = *p;
4694 p++;
4696 if (q)
4697 *q = '\0';
4699 return p;
4702 static int get_param_value(char *buf, int buf_size,
4703 const char *tag, const char *str)
4705 const char *p;
4706 char option[128];
4708 p = str;
4709 for(;;) {
4710 p = get_opt_name(option, sizeof(option), p);
4711 if (*p != '=')
4712 break;
4713 p++;
4714 if (!strcmp(tag, option)) {
4715 (void)get_opt_value(buf, buf_size, p);
4716 return strlen(buf);
4717 } else {
4718 p = get_opt_value(NULL, 0, p);
4720 if (*p != ',')
4721 break;
4722 p++;
4724 return 0;
4727 static int check_params(char *buf, int buf_size,
4728 char **params, const char *str)
4730 const char *p;
4731 int i;
4733 p = str;
4734 for(;;) {
4735 p = get_opt_name(buf, buf_size, p);
4736 if (*p != '=')
4737 return -1;
4738 p++;
4739 for(i = 0; params[i] != NULL; i++)
4740 if (!strcmp(params[i], buf))
4741 break;
4742 if (params[i] == NULL)
4743 return -1;
4744 p = get_opt_value(NULL, 0, p);
4745 if (*p != ',')
4746 break;
4747 p++;
4749 return 0;
4753 static int net_client_init(const char *str)
4755 const char *p;
4756 char *q;
4757 char device[64];
4758 char buf[1024];
4759 int vlan_id, ret;
4760 VLANState *vlan;
4762 p = str;
4763 q = device;
4764 while (*p != '\0' && *p != ',') {
4765 if ((q - device) < sizeof(device) - 1)
4766 *q++ = *p;
4767 p++;
4769 *q = '\0';
4770 if (*p == ',')
4771 p++;
4772 vlan_id = 0;
4773 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4774 vlan_id = strtol(buf, NULL, 0);
4776 vlan = qemu_find_vlan(vlan_id);
4777 if (!vlan) {
4778 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4779 return -1;
4781 if (!strcmp(device, "nic")) {
4782 NICInfo *nd;
4783 uint8_t *macaddr;
4785 if (nb_nics >= MAX_NICS) {
4786 fprintf(stderr, "Too Many NICs\n");
4787 return -1;
4789 nd = &nd_table[nb_nics];
4790 macaddr = nd->macaddr;
4791 macaddr[0] = 0x52;
4792 macaddr[1] = 0x54;
4793 macaddr[2] = 0x00;
4794 macaddr[3] = 0x12;
4795 macaddr[4] = 0x34;
4796 macaddr[5] = 0x56 + nb_nics;
4798 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4799 if (parse_macaddr(macaddr, buf) < 0) {
4800 fprintf(stderr, "invalid syntax for ethernet address\n");
4801 return -1;
4804 if (get_param_value(buf, sizeof(buf), "model", p)) {
4805 nd->model = strdup(buf);
4807 nd->vlan = vlan;
4808 nb_nics++;
4809 vlan->nb_guest_devs++;
4810 ret = 0;
4811 } else
4812 if (!strcmp(device, "none")) {
4813 /* does nothing. It is needed to signal that no network cards
4814 are wanted */
4815 ret = 0;
4816 } else
4817 #ifdef CONFIG_SLIRP
4818 if (!strcmp(device, "user")) {
4819 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4820 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4822 vlan->nb_host_devs++;
4823 ret = net_slirp_init(vlan);
4824 } else
4825 #endif
4826 #ifdef _WIN32
4827 if (!strcmp(device, "tap")) {
4828 char ifname[64];
4829 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4830 fprintf(stderr, "tap: no interface name\n");
4831 return -1;
4833 vlan->nb_host_devs++;
4834 ret = tap_win32_init(vlan, ifname);
4835 } else
4836 #else
4837 if (!strcmp(device, "tap")) {
4838 char ifname[64];
4839 char setup_script[1024], down_script[1024];
4840 int fd;
4841 vlan->nb_host_devs++;
4842 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4843 fd = strtol(buf, NULL, 0);
4844 ret = -1;
4845 if (net_tap_fd_init(vlan, fd))
4846 ret = 0;
4847 } else {
4848 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4849 ifname[0] = '\0';
4851 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4852 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4854 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4855 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4857 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4859 } else
4860 #endif
4861 if (!strcmp(device, "socket")) {
4862 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4863 int fd;
4864 fd = strtol(buf, NULL, 0);
4865 ret = -1;
4866 if (net_socket_fd_init(vlan, fd, 1))
4867 ret = 0;
4868 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4869 ret = net_socket_listen_init(vlan, buf);
4870 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4871 ret = net_socket_connect_init(vlan, buf);
4872 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4873 ret = net_socket_mcast_init(vlan, buf);
4874 } else {
4875 fprintf(stderr, "Unknown socket options: %s\n", p);
4876 return -1;
4878 vlan->nb_host_devs++;
4879 } else
4881 fprintf(stderr, "Unknown network device: %s\n", device);
4882 return -1;
4884 if (ret < 0) {
4885 fprintf(stderr, "Could not initialize device '%s'\n", device);
4888 return ret;
4891 void do_info_network(void)
4893 VLANState *vlan;
4894 VLANClientState *vc;
4896 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4897 term_printf("VLAN %d devices:\n", vlan->id);
4898 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4899 term_printf(" %s\n", vc->info_str);
4903 #define HD_ALIAS "index=%d,media=disk"
4904 #ifdef TARGET_PPC
4905 #define CDROM_ALIAS "index=1,media=cdrom"
4906 #else
4907 #define CDROM_ALIAS "index=2,media=cdrom"
4908 #endif
4909 #define FD_ALIAS "index=%d,if=floppy"
4910 #define PFLASH_ALIAS "if=pflash"
4911 #define MTD_ALIAS "if=mtd"
4912 #define SD_ALIAS "index=0,if=sd"
4914 static int drive_add(const char *file, const char *fmt, ...)
4916 va_list ap;
4918 if (nb_drives_opt >= MAX_DRIVES) {
4919 fprintf(stderr, "qemu: too many drives\n");
4920 exit(1);
4923 drives_opt[nb_drives_opt].file = file;
4924 va_start(ap, fmt);
4925 vsnprintf(drives_opt[nb_drives_opt].opt,
4926 sizeof(drives_opt[0].opt), fmt, ap);
4927 va_end(ap);
4929 return nb_drives_opt++;
4932 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4934 int index;
4936 /* seek interface, bus and unit */
4938 for (index = 0; index < nb_drives; index++)
4939 if (drives_table[index].type == type &&
4940 drives_table[index].bus == bus &&
4941 drives_table[index].unit == unit)
4942 return index;
4944 return -1;
4947 int drive_get_max_bus(BlockInterfaceType type)
4949 int max_bus;
4950 int index;
4952 max_bus = -1;
4953 for (index = 0; index < nb_drives; index++) {
4954 if(drives_table[index].type == type &&
4955 drives_table[index].bus > max_bus)
4956 max_bus = drives_table[index].bus;
4958 return max_bus;
4961 static int drive_init(struct drive_opt *arg, int snapshot,
4962 QEMUMachine *machine)
4964 char buf[128];
4965 char file[1024];
4966 char devname[128];
4967 const char *mediastr = "";
4968 BlockInterfaceType type;
4969 enum { MEDIA_DISK, MEDIA_CDROM } media;
4970 int bus_id, unit_id;
4971 int cyls, heads, secs, translation;
4972 BlockDriverState *bdrv;
4973 int max_devs;
4974 int index;
4975 int cache;
4976 int bdrv_flags;
4977 char *str = arg->opt;
4978 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4979 "secs", "trans", "media", "snapshot", "file",
4980 "cache", "boot", NULL };
4982 if (check_params(buf, sizeof(buf), params, str) < 0) {
4983 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4984 buf, str);
4985 return -1;
4988 file[0] = 0;
4989 cyls = heads = secs = 0;
4990 bus_id = 0;
4991 unit_id = -1;
4992 translation = BIOS_ATA_TRANSLATION_AUTO;
4993 index = -1;
4994 cache = 1;
4996 if (!strcmp(machine->name, "realview") ||
4997 !strcmp(machine->name, "SS-5") ||
4998 !strcmp(machine->name, "SS-10") ||
4999 !strcmp(machine->name, "SS-600MP") ||
5000 !strcmp(machine->name, "versatilepb") ||
5001 !strcmp(machine->name, "versatileab")) {
5002 type = IF_SCSI;
5003 max_devs = MAX_SCSI_DEVS;
5004 strcpy(devname, "scsi");
5005 } else {
5006 type = IF_IDE;
5007 max_devs = MAX_IDE_DEVS;
5008 strcpy(devname, "ide");
5010 media = MEDIA_DISK;
5012 /* extract parameters */
5014 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5015 bus_id = strtol(buf, NULL, 0);
5016 if (bus_id < 0) {
5017 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5018 return -1;
5022 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5023 unit_id = strtol(buf, NULL, 0);
5024 if (unit_id < 0) {
5025 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5026 return -1;
5030 if (get_param_value(buf, sizeof(buf), "if", str)) {
5031 strncpy(devname, buf, sizeof(devname));
5032 if (!strcmp(buf, "ide")) {
5033 type = IF_IDE;
5034 max_devs = MAX_IDE_DEVS;
5035 } else if (!strcmp(buf, "scsi")) {
5036 type = IF_SCSI;
5037 max_devs = MAX_SCSI_DEVS;
5038 } else if (!strcmp(buf, "floppy")) {
5039 type = IF_FLOPPY;
5040 max_devs = 0;
5041 } else if (!strcmp(buf, "pflash")) {
5042 type = IF_PFLASH;
5043 max_devs = 0;
5044 } else if (!strcmp(buf, "mtd")) {
5045 type = IF_MTD;
5046 max_devs = 0;
5047 } else if (!strcmp(buf, "sd")) {
5048 type = IF_SD;
5049 max_devs = 0;
5050 } else if (!strcmp(buf, "virtio")) {
5051 type = IF_VIRTIO;
5052 max_devs = 0;
5053 } else {
5054 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5055 return -1;
5059 if (get_param_value(buf, sizeof(buf), "index", str)) {
5060 index = strtol(buf, NULL, 0);
5061 if (index < 0) {
5062 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5063 return -1;
5067 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5068 cyls = strtol(buf, NULL, 0);
5071 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5072 heads = strtol(buf, NULL, 0);
5075 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5076 secs = strtol(buf, NULL, 0);
5079 if (cyls || heads || secs) {
5080 if (cyls < 1 || cyls > 16383) {
5081 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5082 return -1;
5084 if (heads < 1 || heads > 16) {
5085 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5086 return -1;
5088 if (secs < 1 || secs > 63) {
5089 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5090 return -1;
5094 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5095 if (!cyls) {
5096 fprintf(stderr,
5097 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5098 str);
5099 return -1;
5101 if (!strcmp(buf, "none"))
5102 translation = BIOS_ATA_TRANSLATION_NONE;
5103 else if (!strcmp(buf, "lba"))
5104 translation = BIOS_ATA_TRANSLATION_LBA;
5105 else if (!strcmp(buf, "auto"))
5106 translation = BIOS_ATA_TRANSLATION_AUTO;
5107 else {
5108 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5109 return -1;
5113 if (get_param_value(buf, sizeof(buf), "media", str)) {
5114 if (!strcmp(buf, "disk")) {
5115 media = MEDIA_DISK;
5116 } else if (!strcmp(buf, "cdrom")) {
5117 if (cyls || secs || heads) {
5118 fprintf(stderr,
5119 "qemu: '%s' invalid physical CHS format\n", str);
5120 return -1;
5122 media = MEDIA_CDROM;
5123 } else {
5124 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5125 return -1;
5129 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5130 if (!strcmp(buf, "on"))
5131 snapshot = 1;
5132 else if (!strcmp(buf, "off"))
5133 snapshot = 0;
5134 else {
5135 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5136 return -1;
5140 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5141 if (!strcmp(buf, "off"))
5142 cache = 0;
5143 else if (!strcmp(buf, "on"))
5144 cache = 1;
5145 else {
5146 fprintf(stderr, "qemu: invalid cache option\n");
5147 return -1;
5151 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5152 if (!strcmp(buf, "on")) {
5153 if (extboot_drive != -1) {
5154 fprintf(stderr, "qemu: two bootable drives specified\n");
5155 return -1;
5157 extboot_drive = nb_drives;
5158 } else if (strcmp(buf, "off")) {
5159 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5160 return -1;
5164 if (arg->file == NULL)
5165 get_param_value(file, sizeof(file), "file", str);
5166 else
5167 pstrcpy(file, sizeof(file), arg->file);
5169 /* compute bus and unit according index */
5171 if (index != -1) {
5172 if (bus_id != 0 || unit_id != -1) {
5173 fprintf(stderr,
5174 "qemu: '%s' index cannot be used with bus and unit\n", str);
5175 return -1;
5177 if (max_devs == 0)
5179 unit_id = index;
5180 bus_id = 0;
5181 } else {
5182 unit_id = index % max_devs;
5183 bus_id = index / max_devs;
5187 /* if user doesn't specify a unit_id,
5188 * try to find the first free
5191 if (unit_id == -1) {
5192 unit_id = 0;
5193 while (drive_get_index(type, bus_id, unit_id) != -1) {
5194 unit_id++;
5195 if (max_devs && unit_id >= max_devs) {
5196 unit_id -= max_devs;
5197 bus_id++;
5202 /* check unit id */
5204 if (max_devs && unit_id >= max_devs) {
5205 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5206 str, unit_id, max_devs - 1);
5207 return -1;
5211 * ignore multiple definitions
5214 if (drive_get_index(type, bus_id, unit_id) != -1)
5215 return 0;
5217 /* init */
5219 if (type == IF_IDE || type == IF_SCSI)
5220 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5221 if (max_devs)
5222 snprintf(buf, sizeof(buf), "%s%i%s%i",
5223 devname, bus_id, mediastr, unit_id);
5224 else
5225 snprintf(buf, sizeof(buf), "%s%s%i",
5226 devname, mediastr, unit_id);
5227 bdrv = bdrv_new(buf);
5228 drives_table[nb_drives].bdrv = bdrv;
5229 drives_table[nb_drives].type = type;
5230 drives_table[nb_drives].bus = bus_id;
5231 drives_table[nb_drives].unit = unit_id;
5232 nb_drives++;
5234 switch(type) {
5235 case IF_IDE:
5236 case IF_SCSI:
5237 switch(media) {
5238 case MEDIA_DISK:
5239 if (cyls != 0) {
5240 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5241 bdrv_set_translation_hint(bdrv, translation);
5243 break;
5244 case MEDIA_CDROM:
5245 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5246 break;
5248 break;
5249 case IF_SD:
5250 /* FIXME: This isn't really a floppy, but it's a reasonable
5251 approximation. */
5252 case IF_FLOPPY:
5253 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5254 break;
5255 case IF_PFLASH:
5256 case IF_MTD:
5257 case IF_VIRTIO:
5258 break;
5260 if (!file[0])
5261 return 0;
5262 bdrv_flags = 0;
5263 if (snapshot)
5264 bdrv_flags |= BDRV_O_SNAPSHOT;
5265 if (!cache)
5266 bdrv_flags |= BDRV_O_DIRECT;
5267 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5268 fprintf(stderr, "qemu: could not open disk image %s\n",
5269 file);
5270 return -1;
5272 return 0;
5275 /***********************************************************/
5276 /* USB devices */
5278 static USBPort *used_usb_ports;
5279 static USBPort *free_usb_ports;
5281 /* ??? Maybe change this to register a hub to keep track of the topology. */
5282 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5283 usb_attachfn attach)
5285 port->opaque = opaque;
5286 port->index = index;
5287 port->attach = attach;
5288 port->next = free_usb_ports;
5289 free_usb_ports = port;
5292 static int usb_device_add(const char *devname)
5294 const char *p;
5295 USBDevice *dev;
5296 USBPort *port;
5298 if (!free_usb_ports)
5299 return -1;
5301 if (strstart(devname, "host:", &p)) {
5302 dev = usb_host_device_open(p);
5303 } else if (!strcmp(devname, "mouse")) {
5304 dev = usb_mouse_init();
5305 } else if (!strcmp(devname, "tablet")) {
5306 dev = usb_tablet_init();
5307 } else if (!strcmp(devname, "keyboard")) {
5308 dev = usb_keyboard_init();
5309 } else if (strstart(devname, "disk:", &p)) {
5310 dev = usb_msd_init(p);
5311 } else if (!strcmp(devname, "wacom-tablet")) {
5312 dev = usb_wacom_init();
5313 } else if (strstart(devname, "serial:", &p)) {
5314 dev = usb_serial_init(p);
5315 } else {
5316 return -1;
5318 if (!dev)
5319 return -1;
5321 /* Find a USB port to add the device to. */
5322 port = free_usb_ports;
5323 if (!port->next) {
5324 USBDevice *hub;
5326 /* Create a new hub and chain it on. */
5327 free_usb_ports = NULL;
5328 port->next = used_usb_ports;
5329 used_usb_ports = port;
5331 hub = usb_hub_init(VM_USB_HUB_SIZE);
5332 usb_attach(port, hub);
5333 port = free_usb_ports;
5336 free_usb_ports = port->next;
5337 port->next = used_usb_ports;
5338 used_usb_ports = port;
5339 usb_attach(port, dev);
5340 return 0;
5343 static int usb_device_del(const char *devname)
5345 USBPort *port;
5346 USBPort **lastp;
5347 USBDevice *dev;
5348 int bus_num, addr;
5349 const char *p;
5351 if (!used_usb_ports)
5352 return -1;
5354 p = strchr(devname, '.');
5355 if (!p)
5356 return -1;
5357 bus_num = strtoul(devname, NULL, 0);
5358 addr = strtoul(p + 1, NULL, 0);
5359 if (bus_num != 0)
5360 return -1;
5362 lastp = &used_usb_ports;
5363 port = used_usb_ports;
5364 while (port && port->dev->addr != addr) {
5365 lastp = &port->next;
5366 port = port->next;
5369 if (!port)
5370 return -1;
5372 dev = port->dev;
5373 *lastp = port->next;
5374 usb_attach(port, NULL);
5375 dev->handle_destroy(dev);
5376 port->next = free_usb_ports;
5377 free_usb_ports = port;
5378 return 0;
5381 void do_usb_add(const char *devname)
5383 int ret;
5384 ret = usb_device_add(devname);
5385 if (ret < 0)
5386 term_printf("Could not add USB device '%s'\n", devname);
5389 void do_usb_del(const char *devname)
5391 int ret;
5392 ret = usb_device_del(devname);
5393 if (ret < 0)
5394 term_printf("Could not remove USB device '%s'\n", devname);
5397 void usb_info(void)
5399 USBDevice *dev;
5400 USBPort *port;
5401 const char *speed_str;
5403 if (!usb_enabled) {
5404 term_printf("USB support not enabled\n");
5405 return;
5408 for (port = used_usb_ports; port; port = port->next) {
5409 dev = port->dev;
5410 if (!dev)
5411 continue;
5412 switch(dev->speed) {
5413 case USB_SPEED_LOW:
5414 speed_str = "1.5";
5415 break;
5416 case USB_SPEED_FULL:
5417 speed_str = "12";
5418 break;
5419 case USB_SPEED_HIGH:
5420 speed_str = "480";
5421 break;
5422 default:
5423 speed_str = "?";
5424 break;
5426 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5427 0, dev->addr, speed_str, dev->devname);
5431 /***********************************************************/
5432 /* PCMCIA/Cardbus */
5434 static struct pcmcia_socket_entry_s {
5435 struct pcmcia_socket_s *socket;
5436 struct pcmcia_socket_entry_s *next;
5437 } *pcmcia_sockets = 0;
5439 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5441 struct pcmcia_socket_entry_s *entry;
5443 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5444 entry->socket = socket;
5445 entry->next = pcmcia_sockets;
5446 pcmcia_sockets = entry;
5449 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5451 struct pcmcia_socket_entry_s *entry, **ptr;
5453 ptr = &pcmcia_sockets;
5454 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5455 if (entry->socket == socket) {
5456 *ptr = entry->next;
5457 qemu_free(entry);
5461 void pcmcia_info(void)
5463 struct pcmcia_socket_entry_s *iter;
5464 if (!pcmcia_sockets)
5465 term_printf("No PCMCIA sockets\n");
5467 for (iter = pcmcia_sockets; iter; iter = iter->next)
5468 term_printf("%s: %s\n", iter->socket->slot_string,
5469 iter->socket->attached ? iter->socket->card_string :
5470 "Empty");
5473 /***********************************************************/
5474 /* dumb display */
5476 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5480 static void dumb_resize(DisplayState *ds, int w, int h)
5484 static void dumb_refresh(DisplayState *ds)
5486 #if defined(CONFIG_SDL)
5487 vga_hw_update();
5488 #endif
5491 static void dumb_display_init(DisplayState *ds)
5493 ds->data = NULL;
5494 ds->linesize = 0;
5495 ds->depth = 0;
5496 ds->dpy_update = dumb_update;
5497 ds->dpy_resize = dumb_resize;
5498 ds->dpy_refresh = dumb_refresh;
5501 /***********************************************************/
5502 /* I/O handling */
5504 #define MAX_IO_HANDLERS 64
5506 typedef struct IOHandlerRecord {
5507 int fd;
5508 IOCanRWHandler *fd_read_poll;
5509 IOHandler *fd_read;
5510 IOHandler *fd_write;
5511 int deleted;
5512 void *opaque;
5513 /* temporary data */
5514 struct pollfd *ufd;
5515 struct IOHandlerRecord *next;
5516 } IOHandlerRecord;
5518 static IOHandlerRecord *first_io_handler;
5520 /* XXX: fd_read_poll should be suppressed, but an API change is
5521 necessary in the character devices to suppress fd_can_read(). */
5522 int qemu_set_fd_handler2(int fd,
5523 IOCanRWHandler *fd_read_poll,
5524 IOHandler *fd_read,
5525 IOHandler *fd_write,
5526 void *opaque)
5528 IOHandlerRecord **pioh, *ioh;
5530 if (!fd_read && !fd_write) {
5531 pioh = &first_io_handler;
5532 for(;;) {
5533 ioh = *pioh;
5534 if (ioh == NULL)
5535 break;
5536 if (ioh->fd == fd) {
5537 ioh->deleted = 1;
5538 break;
5540 pioh = &ioh->next;
5542 } else {
5543 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5544 if (ioh->fd == fd)
5545 goto found;
5547 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5548 if (!ioh)
5549 return -1;
5550 ioh->next = first_io_handler;
5551 first_io_handler = ioh;
5552 found:
5553 ioh->fd = fd;
5554 ioh->fd_read_poll = fd_read_poll;
5555 ioh->fd_read = fd_read;
5556 ioh->fd_write = fd_write;
5557 ioh->opaque = opaque;
5558 ioh->deleted = 0;
5560 return 0;
5563 int qemu_set_fd_handler(int fd,
5564 IOHandler *fd_read,
5565 IOHandler *fd_write,
5566 void *opaque)
5568 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5571 /***********************************************************/
5572 /* Polling handling */
5574 typedef struct PollingEntry {
5575 PollingFunc *func;
5576 void *opaque;
5577 struct PollingEntry *next;
5578 } PollingEntry;
5580 static PollingEntry *first_polling_entry;
5582 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5584 PollingEntry **ppe, *pe;
5585 pe = qemu_mallocz(sizeof(PollingEntry));
5586 if (!pe)
5587 return -1;
5588 pe->func = func;
5589 pe->opaque = opaque;
5590 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5591 *ppe = pe;
5592 return 0;
5595 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5597 PollingEntry **ppe, *pe;
5598 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5599 pe = *ppe;
5600 if (pe->func == func && pe->opaque == opaque) {
5601 *ppe = pe->next;
5602 qemu_free(pe);
5603 break;
5608 #ifdef _WIN32
5609 /***********************************************************/
5610 /* Wait objects support */
5611 typedef struct WaitObjects {
5612 int num;
5613 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5614 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5615 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5616 } WaitObjects;
5618 static WaitObjects wait_objects = {0};
5620 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5622 WaitObjects *w = &wait_objects;
5624 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5625 return -1;
5626 w->events[w->num] = handle;
5627 w->func[w->num] = func;
5628 w->opaque[w->num] = opaque;
5629 w->num++;
5630 return 0;
5633 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5635 int i, found;
5636 WaitObjects *w = &wait_objects;
5638 found = 0;
5639 for (i = 0; i < w->num; i++) {
5640 if (w->events[i] == handle)
5641 found = 1;
5642 if (found) {
5643 w->events[i] = w->events[i + 1];
5644 w->func[i] = w->func[i + 1];
5645 w->opaque[i] = w->opaque[i + 1];
5648 if (found)
5649 w->num--;
5651 #endif
5653 #define SELF_ANNOUNCE_ROUNDS 5
5654 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5655 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5656 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5658 static int announce_self_create(uint8_t *buf,
5659 uint8_t *mac_addr)
5661 uint32_t magic = EXPERIMENTAL_MAGIC;
5662 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5664 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5666 memset(buf, 0xff, 6); /* h_dst */
5667 memcpy(buf + 6, mac_addr, 6); /* h_src */
5668 memcpy(buf + 12, &proto, 2); /* h_proto */
5669 memcpy(buf + 14, &magic, 4); /* magic */
5671 return 18; /* len */
5674 static void qemu_announce_self(void)
5676 int i, j, len;
5677 VLANState *vlan;
5678 VLANClientState *vc;
5679 uint8_t buf[256];
5681 for (i = 0; i < nb_nics; i++) {
5682 len = announce_self_create(buf, nd_table[i].macaddr);
5683 vlan = nd_table[i].vlan;
5684 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5685 if (vc->fd_read == tap_receive) /* send only if tap */
5686 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5687 vc->fd_read(vc->opaque, buf, len);
5692 /***********************************************************/
5693 /* savevm/loadvm support */
5695 #define IO_BUF_SIZE 32768
5697 struct QEMUFile {
5698 QEMUFilePutBufferFunc *put_buffer;
5699 QEMUFileGetBufferFunc *get_buffer;
5700 QEMUFileCloseFunc *close;
5701 void *opaque;
5703 int64_t buf_offset; /* start of buffer when writing, end of buffer
5704 when reading */
5705 int buf_index;
5706 int buf_size; /* 0 when writing */
5707 uint8_t buf[IO_BUF_SIZE];
5710 typedef struct QEMUFileFD
5712 int fd;
5713 } QEMUFileFD;
5715 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5717 QEMUFileFD *s = opaque;
5718 int offset = 0;
5719 ssize_t len;
5721 again:
5722 len = read(s->fd, buf + offset, size - offset);
5723 if (len == -1) {
5724 if (errno == EINTR || errno == EAGAIN)
5725 goto again;
5728 return len;
5731 QEMUFile *qemu_fopen_fd(int fd)
5733 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5734 s->fd = fd;
5735 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5738 typedef struct QEMUFileUnix
5740 FILE *outfile;
5741 } QEMUFileUnix;
5743 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5745 QEMUFileUnix *s = opaque;
5746 fseek(s->outfile, pos, SEEK_SET);
5747 fwrite(buf, 1, size, s->outfile);
5750 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5752 QEMUFileUnix *s = opaque;
5753 fseek(s->outfile, pos, SEEK_SET);
5754 return fread(buf, 1, size, s->outfile);
5757 static void file_close(void *opaque)
5759 QEMUFileUnix *s = opaque;
5760 fclose(s->outfile);
5761 qemu_free(s);
5764 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5766 QEMUFileUnix *s;
5768 s = qemu_mallocz(sizeof(QEMUFileUnix));
5769 if (!s)
5770 return NULL;
5772 s->outfile = fopen(filename, mode);
5773 if (!s->outfile)
5774 goto fail;
5776 if (!strcmp(mode, "wb"))
5777 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5778 else if (!strcmp(mode, "rb"))
5779 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5781 fail:
5782 if (s->outfile)
5783 fclose(s->outfile);
5784 qemu_free(s);
5785 return NULL;
5788 typedef struct QEMUFileBdrv
5790 BlockDriverState *bs;
5791 int64_t base_offset;
5792 } QEMUFileBdrv;
5794 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5796 QEMUFileBdrv *s = opaque;
5797 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5800 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5802 QEMUFileBdrv *s = opaque;
5803 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5806 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5808 QEMUFileBdrv *s;
5810 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5811 if (!s)
5812 return NULL;
5814 s->bs = bs;
5815 s->base_offset = offset;
5817 if (is_writable)
5818 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5820 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5823 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5824 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5826 QEMUFile *f;
5828 f = qemu_mallocz(sizeof(QEMUFile));
5829 if (!f)
5830 return NULL;
5832 f->opaque = opaque;
5833 f->put_buffer = put_buffer;
5834 f->get_buffer = get_buffer;
5835 f->close = close;
5837 return f;
5840 void qemu_fflush(QEMUFile *f)
5842 if (!f->put_buffer)
5843 return;
5845 if (f->buf_index > 0) {
5846 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5847 f->buf_offset += f->buf_index;
5848 f->buf_index = 0;
5852 static void qemu_fill_buffer(QEMUFile *f)
5854 int len;
5856 if (!f->get_buffer)
5857 return;
5859 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5860 if (len < 0)
5861 len = 0;
5863 f->buf_index = 0;
5864 f->buf_size = len;
5865 f->buf_offset += len;
5868 void qemu_fclose(QEMUFile *f)
5870 qemu_fflush(f);
5871 if (f->close)
5872 f->close(f->opaque);
5873 qemu_free(f);
5876 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5878 int l;
5879 while (size > 0) {
5880 l = IO_BUF_SIZE - f->buf_index;
5881 if (l > size)
5882 l = size;
5883 memcpy(f->buf + f->buf_index, buf, l);
5884 f->buf_index += l;
5885 buf += l;
5886 size -= l;
5887 if (f->buf_index >= IO_BUF_SIZE)
5888 qemu_fflush(f);
5892 void qemu_put_byte(QEMUFile *f, int v)
5894 f->buf[f->buf_index++] = v;
5895 if (f->buf_index >= IO_BUF_SIZE)
5896 qemu_fflush(f);
5899 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5901 int size, l;
5903 size = size1;
5904 while (size > 0) {
5905 l = f->buf_size - f->buf_index;
5906 if (l == 0) {
5907 qemu_fill_buffer(f);
5908 l = f->buf_size - f->buf_index;
5909 if (l == 0)
5910 break;
5912 if (l > size)
5913 l = size;
5914 memcpy(buf, f->buf + f->buf_index, l);
5915 f->buf_index += l;
5916 buf += l;
5917 size -= l;
5919 return size1 - size;
5922 int qemu_get_byte(QEMUFile *f)
5924 if (f->buf_index >= f->buf_size) {
5925 qemu_fill_buffer(f);
5926 if (f->buf_index >= f->buf_size)
5927 return 0;
5929 return f->buf[f->buf_index++];
5932 int64_t qemu_ftell(QEMUFile *f)
5934 return f->buf_offset - f->buf_size + f->buf_index;
5937 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5939 if (whence == SEEK_SET) {
5940 /* nothing to do */
5941 } else if (whence == SEEK_CUR) {
5942 pos += qemu_ftell(f);
5943 } else {
5944 /* SEEK_END not supported */
5945 return -1;
5947 if (f->put_buffer) {
5948 qemu_fflush(f);
5949 f->buf_offset = pos;
5950 } else {
5951 f->buf_offset = pos;
5952 f->buf_index = 0;
5953 f->buf_size = 0;
5955 return pos;
5958 void qemu_put_be16(QEMUFile *f, unsigned int v)
5960 qemu_put_byte(f, v >> 8);
5961 qemu_put_byte(f, v);
5964 void qemu_put_be32(QEMUFile *f, unsigned int v)
5966 qemu_put_byte(f, v >> 24);
5967 qemu_put_byte(f, v >> 16);
5968 qemu_put_byte(f, v >> 8);
5969 qemu_put_byte(f, v);
5972 void qemu_put_be64(QEMUFile *f, uint64_t v)
5974 qemu_put_be32(f, v >> 32);
5975 qemu_put_be32(f, v);
5978 unsigned int qemu_get_be16(QEMUFile *f)
5980 unsigned int v;
5981 v = qemu_get_byte(f) << 8;
5982 v |= qemu_get_byte(f);
5983 return v;
5986 unsigned int qemu_get_be32(QEMUFile *f)
5988 unsigned int v;
5989 v = qemu_get_byte(f) << 24;
5990 v |= qemu_get_byte(f) << 16;
5991 v |= qemu_get_byte(f) << 8;
5992 v |= qemu_get_byte(f);
5993 return v;
5996 uint64_t qemu_get_be64(QEMUFile *f)
5998 uint64_t v;
5999 v = (uint64_t)qemu_get_be32(f) << 32;
6000 v |= qemu_get_be32(f);
6001 return v;
6004 typedef struct SaveStateEntry {
6005 char idstr[256];
6006 int instance_id;
6007 int version_id;
6008 SaveStateHandler *save_state;
6009 LoadStateHandler *load_state;
6010 void *opaque;
6011 struct SaveStateEntry *next;
6012 } SaveStateEntry;
6014 static SaveStateEntry *first_se;
6016 int register_savevm(const char *idstr,
6017 int instance_id,
6018 int version_id,
6019 SaveStateHandler *save_state,
6020 LoadStateHandler *load_state,
6021 void *opaque)
6023 SaveStateEntry *se, **pse;
6025 se = qemu_malloc(sizeof(SaveStateEntry));
6026 if (!se)
6027 return -1;
6028 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6029 se->instance_id = instance_id;
6030 se->version_id = version_id;
6031 se->save_state = save_state;
6032 se->load_state = load_state;
6033 se->opaque = opaque;
6034 se->next = NULL;
6036 /* add at the end of list */
6037 pse = &first_se;
6038 while (*pse != NULL)
6039 pse = &(*pse)->next;
6040 *pse = se;
6041 return 0;
6044 #define QEMU_VM_FILE_MAGIC 0x5145564d
6045 #define QEMU_VM_FILE_VERSION 0x00000002
6047 static int qemu_savevm_state(QEMUFile *f)
6049 SaveStateEntry *se;
6050 int len, ret;
6051 int64_t cur_pos, len_pos, total_len_pos;
6053 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6054 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6055 total_len_pos = qemu_ftell(f);
6056 qemu_put_be64(f, 0); /* total size */
6058 for(se = first_se; se != NULL; se = se->next) {
6059 /* ID string */
6060 len = strlen(se->idstr);
6061 qemu_put_byte(f, len);
6062 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6064 qemu_put_be32(f, se->instance_id);
6065 qemu_put_be32(f, se->version_id);
6067 /* record size: filled later */
6068 len_pos = qemu_ftell(f);
6069 qemu_put_be32(f, 0);
6070 se->save_state(f, se->opaque);
6072 /* fill record size */
6073 cur_pos = qemu_ftell(f);
6074 len = cur_pos - len_pos - 4;
6075 qemu_fseek(f, len_pos, SEEK_SET);
6076 qemu_put_be32(f, len);
6077 qemu_fseek(f, cur_pos, SEEK_SET);
6079 cur_pos = qemu_ftell(f);
6080 qemu_fseek(f, total_len_pos, SEEK_SET);
6081 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6082 qemu_fseek(f, cur_pos, SEEK_SET);
6084 ret = 0;
6085 return ret;
6088 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6090 SaveStateEntry *se;
6092 for(se = first_se; se != NULL; se = se->next) {
6093 if (!strcmp(se->idstr, idstr) &&
6094 instance_id == se->instance_id)
6095 return se;
6097 return NULL;
6100 static int qemu_loadvm_state(QEMUFile *f)
6102 SaveStateEntry *se;
6103 int len, ret, instance_id, record_len, version_id;
6104 int64_t total_len, end_pos, cur_pos;
6105 unsigned int v;
6106 char idstr[256];
6108 v = qemu_get_be32(f);
6109 if (v != QEMU_VM_FILE_MAGIC)
6110 goto fail;
6111 v = qemu_get_be32(f);
6112 if (v != QEMU_VM_FILE_VERSION) {
6113 fail:
6114 ret = -1;
6115 goto the_end;
6117 total_len = qemu_get_be64(f);
6118 end_pos = total_len + qemu_ftell(f);
6119 for(;;) {
6120 if (qemu_ftell(f) >= end_pos)
6121 break;
6122 len = qemu_get_byte(f);
6123 qemu_get_buffer(f, (uint8_t *)idstr, len);
6124 idstr[len] = '\0';
6125 instance_id = qemu_get_be32(f);
6126 version_id = qemu_get_be32(f);
6127 record_len = qemu_get_be32(f);
6128 #if 0
6129 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6130 idstr, instance_id, version_id, record_len);
6131 #endif
6132 cur_pos = qemu_ftell(f);
6133 se = find_se(idstr, instance_id);
6134 if (!se) {
6135 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6136 instance_id, idstr);
6137 } else {
6138 ret = se->load_state(f, se->opaque, version_id);
6139 if (ret < 0) {
6140 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6141 instance_id, idstr);
6142 goto the_end;
6145 /* always seek to exact end of record */
6146 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6148 ret = 0;
6149 the_end:
6150 return ret;
6153 int qemu_live_savevm_state(QEMUFile *f)
6155 SaveStateEntry *se;
6156 int len, ret;
6158 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6159 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6161 for(se = first_se; se != NULL; se = se->next) {
6162 len = strlen(se->idstr);
6164 qemu_put_byte(f, len);
6165 qemu_put_buffer(f, se->idstr, len);
6166 qemu_put_be32(f, se->instance_id);
6167 qemu_put_be32(f, se->version_id);
6169 se->save_state(f, se->opaque);
6172 qemu_put_byte(f, 0);
6174 ret = 0;
6175 return ret;
6178 int qemu_live_loadvm_state(QEMUFile *f)
6180 SaveStateEntry *se;
6181 int len, ret, instance_id, version_id;
6182 unsigned int v;
6183 char idstr[256];
6185 v = qemu_get_be32(f);
6186 if (v != QEMU_VM_FILE_MAGIC)
6187 goto fail;
6188 v = qemu_get_be32(f);
6189 if (v != QEMU_VM_FILE_VERSION) {
6190 fail:
6191 ret = -1;
6192 goto the_end;
6195 for(;;) {
6196 len = qemu_get_byte(f);
6197 if (len == 0)
6198 break;
6199 qemu_get_buffer(f, idstr, len);
6200 idstr[len] = '\0';
6201 instance_id = qemu_get_be32(f);
6202 version_id = qemu_get_be32(f);
6203 se = find_se(idstr, instance_id);
6204 if (!se) {
6205 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6206 instance_id, idstr);
6207 } else {
6208 if (version_id > se->version_id) { /* src version > dst version */
6209 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6210 idstr, version_id, se->version_id);
6211 ret = -1;
6212 goto the_end;
6214 ret = se->load_state(f, se->opaque, version_id);
6215 if (ret < 0) {
6216 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6217 instance_id, idstr);
6218 goto the_end;
6222 ret = 0;
6224 qemu_announce_self();
6226 the_end:
6227 return ret;
6230 /* device can contain snapshots */
6231 static int bdrv_can_snapshot(BlockDriverState *bs)
6233 return (bs &&
6234 !bdrv_is_removable(bs) &&
6235 !bdrv_is_read_only(bs));
6238 /* device must be snapshots in order to have a reliable snapshot */
6239 static int bdrv_has_snapshot(BlockDriverState *bs)
6241 return (bs &&
6242 !bdrv_is_removable(bs) &&
6243 !bdrv_is_read_only(bs));
6246 static BlockDriverState *get_bs_snapshots(void)
6248 BlockDriverState *bs;
6249 int i;
6251 if (bs_snapshots)
6252 return bs_snapshots;
6253 for(i = 0; i <= nb_drives; i++) {
6254 bs = drives_table[i].bdrv;
6255 if (bdrv_can_snapshot(bs))
6256 goto ok;
6258 return NULL;
6260 bs_snapshots = bs;
6261 return bs;
6264 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6265 const char *name)
6267 QEMUSnapshotInfo *sn_tab, *sn;
6268 int nb_sns, i, ret;
6270 ret = -ENOENT;
6271 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6272 if (nb_sns < 0)
6273 return ret;
6274 for(i = 0; i < nb_sns; i++) {
6275 sn = &sn_tab[i];
6276 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6277 *sn_info = *sn;
6278 ret = 0;
6279 break;
6282 qemu_free(sn_tab);
6283 return ret;
6286 void do_savevm(const char *name)
6288 BlockDriverState *bs, *bs1;
6289 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6290 int must_delete, ret, i;
6291 BlockDriverInfo bdi1, *bdi = &bdi1;
6292 QEMUFile *f;
6293 int saved_vm_running;
6294 #ifdef _WIN32
6295 struct _timeb tb;
6296 #else
6297 struct timeval tv;
6298 #endif
6300 bs = get_bs_snapshots();
6301 if (!bs) {
6302 term_printf("No block device can accept snapshots\n");
6303 return;
6306 /* ??? Should this occur after vm_stop? */
6307 qemu_aio_flush();
6309 saved_vm_running = vm_running;
6310 vm_stop(0);
6312 must_delete = 0;
6313 if (name) {
6314 ret = bdrv_snapshot_find(bs, old_sn, name);
6315 if (ret >= 0) {
6316 must_delete = 1;
6319 memset(sn, 0, sizeof(*sn));
6320 if (must_delete) {
6321 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6322 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6323 } else {
6324 if (name)
6325 pstrcpy(sn->name, sizeof(sn->name), name);
6328 /* fill auxiliary fields */
6329 #ifdef _WIN32
6330 _ftime(&tb);
6331 sn->date_sec = tb.time;
6332 sn->date_nsec = tb.millitm * 1000000;
6333 #else
6334 gettimeofday(&tv, NULL);
6335 sn->date_sec = tv.tv_sec;
6336 sn->date_nsec = tv.tv_usec * 1000;
6337 #endif
6338 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6340 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6341 term_printf("Device %s does not support VM state snapshots\n",
6342 bdrv_get_device_name(bs));
6343 goto the_end;
6346 /* save the VM state */
6347 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6348 if (!f) {
6349 term_printf("Could not open VM state file\n");
6350 goto the_end;
6352 ret = qemu_savevm_state(f);
6353 sn->vm_state_size = qemu_ftell(f);
6354 qemu_fclose(f);
6355 if (ret < 0) {
6356 term_printf("Error %d while writing VM\n", ret);
6357 goto the_end;
6360 /* create the snapshots */
6362 for(i = 0; i < nb_drives; i++) {
6363 bs1 = drives_table[i].bdrv;
6364 if (bdrv_has_snapshot(bs1)) {
6365 if (must_delete) {
6366 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6367 if (ret < 0) {
6368 term_printf("Error while deleting snapshot on '%s'\n",
6369 bdrv_get_device_name(bs1));
6372 ret = bdrv_snapshot_create(bs1, sn);
6373 if (ret < 0) {
6374 term_printf("Error while creating snapshot on '%s'\n",
6375 bdrv_get_device_name(bs1));
6380 the_end:
6381 if (saved_vm_running)
6382 vm_start();
6385 void do_loadvm(const char *name)
6387 BlockDriverState *bs, *bs1;
6388 BlockDriverInfo bdi1, *bdi = &bdi1;
6389 QEMUFile *f;
6390 int i, ret;
6391 int saved_vm_running;
6393 bs = get_bs_snapshots();
6394 if (!bs) {
6395 term_printf("No block device supports snapshots\n");
6396 return;
6399 /* Flush all IO requests so they don't interfere with the new state. */
6400 qemu_aio_flush();
6402 saved_vm_running = vm_running;
6403 vm_stop(0);
6405 for(i = 0; i <= nb_drives; i++) {
6406 bs1 = drives_table[i].bdrv;
6407 if (bdrv_has_snapshot(bs1)) {
6408 ret = bdrv_snapshot_goto(bs1, name);
6409 if (ret < 0) {
6410 if (bs != bs1)
6411 term_printf("Warning: ");
6412 switch(ret) {
6413 case -ENOTSUP:
6414 term_printf("Snapshots not supported on device '%s'\n",
6415 bdrv_get_device_name(bs1));
6416 break;
6417 case -ENOENT:
6418 term_printf("Could not find snapshot '%s' on device '%s'\n",
6419 name, bdrv_get_device_name(bs1));
6420 break;
6421 default:
6422 term_printf("Error %d while activating snapshot on '%s'\n",
6423 ret, bdrv_get_device_name(bs1));
6424 break;
6426 /* fatal on snapshot block device */
6427 if (bs == bs1)
6428 goto the_end;
6433 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6434 term_printf("Device %s does not support VM state snapshots\n",
6435 bdrv_get_device_name(bs));
6436 return;
6439 /* restore the VM state */
6440 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6441 if (!f) {
6442 term_printf("Could not open VM state file\n");
6443 goto the_end;
6445 ret = qemu_loadvm_state(f);
6446 qemu_fclose(f);
6447 if (ret < 0) {
6448 term_printf("Error %d while loading VM state\n", ret);
6450 the_end:
6451 if (saved_vm_running)
6452 vm_start();
6455 void do_delvm(const char *name)
6457 BlockDriverState *bs, *bs1;
6458 int i, ret;
6460 bs = get_bs_snapshots();
6461 if (!bs) {
6462 term_printf("No block device supports snapshots\n");
6463 return;
6466 for(i = 0; i <= nb_drives; i++) {
6467 bs1 = drives_table[i].bdrv;
6468 if (bdrv_has_snapshot(bs1)) {
6469 ret = bdrv_snapshot_delete(bs1, name);
6470 if (ret < 0) {
6471 if (ret == -ENOTSUP)
6472 term_printf("Snapshots not supported on device '%s'\n",
6473 bdrv_get_device_name(bs1));
6474 else
6475 term_printf("Error %d while deleting snapshot on '%s'\n",
6476 ret, bdrv_get_device_name(bs1));
6482 void do_info_snapshots(void)
6484 BlockDriverState *bs, *bs1;
6485 QEMUSnapshotInfo *sn_tab, *sn;
6486 int nb_sns, i;
6487 char buf[256];
6489 bs = get_bs_snapshots();
6490 if (!bs) {
6491 term_printf("No available block device supports snapshots\n");
6492 return;
6494 term_printf("Snapshot devices:");
6495 for(i = 0; i <= nb_drives; i++) {
6496 bs1 = drives_table[i].bdrv;
6497 if (bdrv_has_snapshot(bs1)) {
6498 if (bs == bs1)
6499 term_printf(" %s", bdrv_get_device_name(bs1));
6502 term_printf("\n");
6504 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6505 if (nb_sns < 0) {
6506 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6507 return;
6509 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6510 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6511 for(i = 0; i < nb_sns; i++) {
6512 sn = &sn_tab[i];
6513 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6515 qemu_free(sn_tab);
6518 /***********************************************************/
6519 /* cpu save/restore */
6521 #if defined(TARGET_I386)
6523 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6525 qemu_put_be32(f, dt->selector);
6526 qemu_put_betl(f, dt->base);
6527 qemu_put_be32(f, dt->limit);
6528 qemu_put_be32(f, dt->flags);
6531 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6533 dt->selector = qemu_get_be32(f);
6534 dt->base = qemu_get_betl(f);
6535 dt->limit = qemu_get_be32(f);
6536 dt->flags = qemu_get_be32(f);
6539 void cpu_save(QEMUFile *f, void *opaque)
6541 CPUState *env = opaque;
6542 uint16_t fptag, fpus, fpuc, fpregs_format;
6543 uint32_t hflags;
6544 int i;
6546 if (kvm_enabled())
6547 kvm_save_registers(env);
6549 for(i = 0; i < CPU_NB_REGS; i++)
6550 qemu_put_betls(f, &env->regs[i]);
6551 qemu_put_betls(f, &env->eip);
6552 qemu_put_betls(f, &env->eflags);
6553 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6554 qemu_put_be32s(f, &hflags);
6556 /* FPU */
6557 fpuc = env->fpuc;
6558 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6559 fptag = 0;
6560 for(i = 0; i < 8; i++) {
6561 fptag |= ((!env->fptags[i]) << i);
6564 qemu_put_be16s(f, &fpuc);
6565 qemu_put_be16s(f, &fpus);
6566 qemu_put_be16s(f, &fptag);
6568 #ifdef USE_X86LDOUBLE
6569 fpregs_format = 0;
6570 #else
6571 fpregs_format = 1;
6572 #endif
6573 qemu_put_be16s(f, &fpregs_format);
6575 for(i = 0; i < 8; i++) {
6576 #ifdef USE_X86LDOUBLE
6578 uint64_t mant;
6579 uint16_t exp;
6580 /* we save the real CPU data (in case of MMX usage only 'mant'
6581 contains the MMX register */
6582 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6583 qemu_put_be64(f, mant);
6584 qemu_put_be16(f, exp);
6586 #else
6587 /* if we use doubles for float emulation, we save the doubles to
6588 avoid losing information in case of MMX usage. It can give
6589 problems if the image is restored on a CPU where long
6590 doubles are used instead. */
6591 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6592 #endif
6595 for(i = 0; i < 6; i++)
6596 cpu_put_seg(f, &env->segs[i]);
6597 cpu_put_seg(f, &env->ldt);
6598 cpu_put_seg(f, &env->tr);
6599 cpu_put_seg(f, &env->gdt);
6600 cpu_put_seg(f, &env->idt);
6602 qemu_put_be32s(f, &env->sysenter_cs);
6603 qemu_put_be32s(f, &env->sysenter_esp);
6604 qemu_put_be32s(f, &env->sysenter_eip);
6606 qemu_put_betls(f, &env->cr[0]);
6607 qemu_put_betls(f, &env->cr[2]);
6608 qemu_put_betls(f, &env->cr[3]);
6609 qemu_put_betls(f, &env->cr[4]);
6611 for(i = 0; i < 8; i++)
6612 qemu_put_betls(f, &env->dr[i]);
6614 /* MMU */
6615 qemu_put_be32s(f, &env->a20_mask);
6617 /* XMM */
6618 qemu_put_be32s(f, &env->mxcsr);
6619 for(i = 0; i < CPU_NB_REGS; i++) {
6620 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6621 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6624 #ifdef TARGET_X86_64
6625 qemu_put_be64s(f, &env->efer);
6626 qemu_put_be64s(f, &env->star);
6627 qemu_put_be64s(f, &env->lstar);
6628 qemu_put_be64s(f, &env->cstar);
6629 qemu_put_be64s(f, &env->fmask);
6630 qemu_put_be64s(f, &env->kernelgsbase);
6631 #endif
6632 qemu_put_be32s(f, &env->smbase);
6634 if (kvm_enabled()) {
6635 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6636 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6638 qemu_put_be64s(f, &env->tsc);
6642 #ifdef USE_X86LDOUBLE
6643 /* XXX: add that in a FPU generic layer */
6644 union x86_longdouble {
6645 uint64_t mant;
6646 uint16_t exp;
6649 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6650 #define EXPBIAS1 1023
6651 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6652 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6654 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6656 int e;
6657 /* mantissa */
6658 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6659 /* exponent + sign */
6660 e = EXPD1(temp) - EXPBIAS1 + 16383;
6661 e |= SIGND1(temp) >> 16;
6662 p->exp = e;
6664 #endif
6666 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6668 CPUState *env = opaque;
6669 int i, guess_mmx;
6670 uint32_t hflags;
6671 uint16_t fpus, fpuc, fptag, fpregs_format;
6673 if (version_id != 3 && version_id != 4)
6674 return -EINVAL;
6675 for(i = 0; i < CPU_NB_REGS; i++)
6676 qemu_get_betls(f, &env->regs[i]);
6677 qemu_get_betls(f, &env->eip);
6678 qemu_get_betls(f, &env->eflags);
6679 qemu_get_be32s(f, &hflags);
6681 qemu_get_be16s(f, &fpuc);
6682 qemu_get_be16s(f, &fpus);
6683 qemu_get_be16s(f, &fptag);
6684 qemu_get_be16s(f, &fpregs_format);
6686 /* NOTE: we cannot always restore the FPU state if the image come
6687 from a host with a different 'USE_X86LDOUBLE' define. We guess
6688 if we are in an MMX state to restore correctly in that case. */
6689 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6690 for(i = 0; i < 8; i++) {
6691 uint64_t mant;
6692 uint16_t exp;
6694 switch(fpregs_format) {
6695 case 0:
6696 mant = qemu_get_be64(f);
6697 exp = qemu_get_be16(f);
6698 #ifdef USE_X86LDOUBLE
6699 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6700 #else
6701 /* difficult case */
6702 if (guess_mmx)
6703 env->fpregs[i].mmx.MMX_Q(0) = mant;
6704 else
6705 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6706 #endif
6707 break;
6708 case 1:
6709 mant = qemu_get_be64(f);
6710 #ifdef USE_X86LDOUBLE
6712 union x86_longdouble *p;
6713 /* difficult case */
6714 p = (void *)&env->fpregs[i];
6715 if (guess_mmx) {
6716 p->mant = mant;
6717 p->exp = 0xffff;
6718 } else {
6719 fp64_to_fp80(p, mant);
6722 #else
6723 env->fpregs[i].mmx.MMX_Q(0) = mant;
6724 #endif
6725 break;
6726 default:
6727 return -EINVAL;
6731 env->fpuc = fpuc;
6732 /* XXX: restore FPU round state */
6733 env->fpstt = (fpus >> 11) & 7;
6734 env->fpus = fpus & ~0x3800;
6735 fptag ^= 0xff;
6736 for(i = 0; i < 8; i++) {
6737 env->fptags[i] = (fptag >> i) & 1;
6740 for(i = 0; i < 6; i++)
6741 cpu_get_seg(f, &env->segs[i]);
6742 cpu_get_seg(f, &env->ldt);
6743 cpu_get_seg(f, &env->tr);
6744 cpu_get_seg(f, &env->gdt);
6745 cpu_get_seg(f, &env->idt);
6747 qemu_get_be32s(f, &env->sysenter_cs);
6748 qemu_get_be32s(f, &env->sysenter_esp);
6749 qemu_get_be32s(f, &env->sysenter_eip);
6751 qemu_get_betls(f, &env->cr[0]);
6752 qemu_get_betls(f, &env->cr[2]);
6753 qemu_get_betls(f, &env->cr[3]);
6754 qemu_get_betls(f, &env->cr[4]);
6756 for(i = 0; i < 8; i++)
6757 qemu_get_betls(f, &env->dr[i]);
6759 /* MMU */
6760 qemu_get_be32s(f, &env->a20_mask);
6762 qemu_get_be32s(f, &env->mxcsr);
6763 for(i = 0; i < CPU_NB_REGS; i++) {
6764 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6765 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6768 #ifdef TARGET_X86_64
6769 qemu_get_be64s(f, &env->efer);
6770 qemu_get_be64s(f, &env->star);
6771 qemu_get_be64s(f, &env->lstar);
6772 qemu_get_be64s(f, &env->cstar);
6773 qemu_get_be64s(f, &env->fmask);
6774 qemu_get_be64s(f, &env->kernelgsbase);
6775 #endif
6776 if (version_id >= 4)
6777 qemu_get_be32s(f, &env->smbase);
6779 /* XXX: compute hflags from scratch, except for CPL and IIF */
6780 env->hflags = hflags;
6781 tlb_flush(env, 1);
6782 if (kvm_enabled()) {
6783 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6784 because no userspace IRQs will ever clear this flag */
6785 env->hflags &= ~HF_HALTED_MASK;
6786 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6787 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6789 qemu_get_be64s(f, &env->tsc);
6790 kvm_load_registers(env);
6792 return 0;
6795 #elif defined(TARGET_PPC)
6796 void cpu_save(QEMUFile *f, void *opaque)
6800 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6802 return 0;
6805 #elif defined(TARGET_MIPS)
6806 void cpu_save(QEMUFile *f, void *opaque)
6810 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6812 return 0;
6815 #elif defined(TARGET_SPARC)
6816 void cpu_save(QEMUFile *f, void *opaque)
6818 CPUState *env = opaque;
6819 int i;
6820 uint32_t tmp;
6822 for(i = 0; i < 8; i++)
6823 qemu_put_betls(f, &env->gregs[i]);
6824 for(i = 0; i < NWINDOWS * 16; i++)
6825 qemu_put_betls(f, &env->regbase[i]);
6827 /* FPU */
6828 for(i = 0; i < TARGET_FPREGS; i++) {
6829 union {
6830 float32 f;
6831 uint32_t i;
6832 } u;
6833 u.f = env->fpr[i];
6834 qemu_put_be32(f, u.i);
6837 qemu_put_betls(f, &env->pc);
6838 qemu_put_betls(f, &env->npc);
6839 qemu_put_betls(f, &env->y);
6840 tmp = GET_PSR(env);
6841 qemu_put_be32(f, tmp);
6842 qemu_put_betls(f, &env->fsr);
6843 qemu_put_betls(f, &env->tbr);
6844 #ifndef TARGET_SPARC64
6845 qemu_put_be32s(f, &env->wim);
6846 /* MMU */
6847 for(i = 0; i < 16; i++)
6848 qemu_put_be32s(f, &env->mmuregs[i]);
6849 #endif
6852 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6854 CPUState *env = opaque;
6855 int i;
6856 uint32_t tmp;
6858 for(i = 0; i < 8; i++)
6859 qemu_get_betls(f, &env->gregs[i]);
6860 for(i = 0; i < NWINDOWS * 16; i++)
6861 qemu_get_betls(f, &env->regbase[i]);
6863 /* FPU */
6864 for(i = 0; i < TARGET_FPREGS; i++) {
6865 union {
6866 float32 f;
6867 uint32_t i;
6868 } u;
6869 u.i = qemu_get_be32(f);
6870 env->fpr[i] = u.f;
6873 qemu_get_betls(f, &env->pc);
6874 qemu_get_betls(f, &env->npc);
6875 qemu_get_betls(f, &env->y);
6876 tmp = qemu_get_be32(f);
6877 env->cwp = 0; /* needed to ensure that the wrapping registers are
6878 correctly updated */
6879 PUT_PSR(env, tmp);
6880 qemu_get_betls(f, &env->fsr);
6881 qemu_get_betls(f, &env->tbr);
6882 #ifndef TARGET_SPARC64
6883 qemu_get_be32s(f, &env->wim);
6884 /* MMU */
6885 for(i = 0; i < 16; i++)
6886 qemu_get_be32s(f, &env->mmuregs[i]);
6887 #endif
6888 tlb_flush(env, 1);
6889 return 0;
6892 #elif defined(TARGET_ARM)
6894 void cpu_save(QEMUFile *f, void *opaque)
6896 int i;
6897 CPUARMState *env = (CPUARMState *)opaque;
6899 for (i = 0; i < 16; i++) {
6900 qemu_put_be32(f, env->regs[i]);
6902 qemu_put_be32(f, cpsr_read(env));
6903 qemu_put_be32(f, env->spsr);
6904 for (i = 0; i < 6; i++) {
6905 qemu_put_be32(f, env->banked_spsr[i]);
6906 qemu_put_be32(f, env->banked_r13[i]);
6907 qemu_put_be32(f, env->banked_r14[i]);
6909 for (i = 0; i < 5; i++) {
6910 qemu_put_be32(f, env->usr_regs[i]);
6911 qemu_put_be32(f, env->fiq_regs[i]);
6913 qemu_put_be32(f, env->cp15.c0_cpuid);
6914 qemu_put_be32(f, env->cp15.c0_cachetype);
6915 qemu_put_be32(f, env->cp15.c1_sys);
6916 qemu_put_be32(f, env->cp15.c1_coproc);
6917 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6918 qemu_put_be32(f, env->cp15.c2_base0);
6919 qemu_put_be32(f, env->cp15.c2_base1);
6920 qemu_put_be32(f, env->cp15.c2_mask);
6921 qemu_put_be32(f, env->cp15.c2_data);
6922 qemu_put_be32(f, env->cp15.c2_insn);
6923 qemu_put_be32(f, env->cp15.c3);
6924 qemu_put_be32(f, env->cp15.c5_insn);
6925 qemu_put_be32(f, env->cp15.c5_data);
6926 for (i = 0; i < 8; i++) {
6927 qemu_put_be32(f, env->cp15.c6_region[i]);
6929 qemu_put_be32(f, env->cp15.c6_insn);
6930 qemu_put_be32(f, env->cp15.c6_data);
6931 qemu_put_be32(f, env->cp15.c9_insn);
6932 qemu_put_be32(f, env->cp15.c9_data);
6933 qemu_put_be32(f, env->cp15.c13_fcse);
6934 qemu_put_be32(f, env->cp15.c13_context);
6935 qemu_put_be32(f, env->cp15.c13_tls1);
6936 qemu_put_be32(f, env->cp15.c13_tls2);
6937 qemu_put_be32(f, env->cp15.c13_tls3);
6938 qemu_put_be32(f, env->cp15.c15_cpar);
6940 qemu_put_be32(f, env->features);
6942 if (arm_feature(env, ARM_FEATURE_VFP)) {
6943 for (i = 0; i < 16; i++) {
6944 CPU_DoubleU u;
6945 u.d = env->vfp.regs[i];
6946 qemu_put_be32(f, u.l.upper);
6947 qemu_put_be32(f, u.l.lower);
6949 for (i = 0; i < 16; i++) {
6950 qemu_put_be32(f, env->vfp.xregs[i]);
6953 /* TODO: Should use proper FPSCR access functions. */
6954 qemu_put_be32(f, env->vfp.vec_len);
6955 qemu_put_be32(f, env->vfp.vec_stride);
6957 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6958 for (i = 16; i < 32; i++) {
6959 CPU_DoubleU u;
6960 u.d = env->vfp.regs[i];
6961 qemu_put_be32(f, u.l.upper);
6962 qemu_put_be32(f, u.l.lower);
6967 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6968 for (i = 0; i < 16; i++) {
6969 qemu_put_be64(f, env->iwmmxt.regs[i]);
6971 for (i = 0; i < 16; i++) {
6972 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6976 if (arm_feature(env, ARM_FEATURE_M)) {
6977 qemu_put_be32(f, env->v7m.other_sp);
6978 qemu_put_be32(f, env->v7m.vecbase);
6979 qemu_put_be32(f, env->v7m.basepri);
6980 qemu_put_be32(f, env->v7m.control);
6981 qemu_put_be32(f, env->v7m.current_sp);
6982 qemu_put_be32(f, env->v7m.exception);
6986 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6988 CPUARMState *env = (CPUARMState *)opaque;
6989 int i;
6991 if (version_id != ARM_CPU_SAVE_VERSION)
6992 return -EINVAL;
6994 for (i = 0; i < 16; i++) {
6995 env->regs[i] = qemu_get_be32(f);
6997 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6998 env->spsr = qemu_get_be32(f);
6999 for (i = 0; i < 6; i++) {
7000 env->banked_spsr[i] = qemu_get_be32(f);
7001 env->banked_r13[i] = qemu_get_be32(f);
7002 env->banked_r14[i] = qemu_get_be32(f);
7004 for (i = 0; i < 5; i++) {
7005 env->usr_regs[i] = qemu_get_be32(f);
7006 env->fiq_regs[i] = qemu_get_be32(f);
7008 env->cp15.c0_cpuid = qemu_get_be32(f);
7009 env->cp15.c0_cachetype = qemu_get_be32(f);
7010 env->cp15.c1_sys = qemu_get_be32(f);
7011 env->cp15.c1_coproc = qemu_get_be32(f);
7012 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7013 env->cp15.c2_base0 = qemu_get_be32(f);
7014 env->cp15.c2_base1 = qemu_get_be32(f);
7015 env->cp15.c2_mask = qemu_get_be32(f);
7016 env->cp15.c2_data = qemu_get_be32(f);
7017 env->cp15.c2_insn = qemu_get_be32(f);
7018 env->cp15.c3 = qemu_get_be32(f);
7019 env->cp15.c5_insn = qemu_get_be32(f);
7020 env->cp15.c5_data = qemu_get_be32(f);
7021 for (i = 0; i < 8; i++) {
7022 env->cp15.c6_region[i] = qemu_get_be32(f);
7024 env->cp15.c6_insn = qemu_get_be32(f);
7025 env->cp15.c6_data = qemu_get_be32(f);
7026 env->cp15.c9_insn = qemu_get_be32(f);
7027 env->cp15.c9_data = qemu_get_be32(f);
7028 env->cp15.c13_fcse = qemu_get_be32(f);
7029 env->cp15.c13_context = qemu_get_be32(f);
7030 env->cp15.c13_tls1 = qemu_get_be32(f);
7031 env->cp15.c13_tls2 = qemu_get_be32(f);
7032 env->cp15.c13_tls3 = qemu_get_be32(f);
7033 env->cp15.c15_cpar = qemu_get_be32(f);
7035 env->features = qemu_get_be32(f);
7037 if (arm_feature(env, ARM_FEATURE_VFP)) {
7038 for (i = 0; i < 16; i++) {
7039 CPU_DoubleU u;
7040 u.l.upper = qemu_get_be32(f);
7041 u.l.lower = qemu_get_be32(f);
7042 env->vfp.regs[i] = u.d;
7044 for (i = 0; i < 16; i++) {
7045 env->vfp.xregs[i] = qemu_get_be32(f);
7048 /* TODO: Should use proper FPSCR access functions. */
7049 env->vfp.vec_len = qemu_get_be32(f);
7050 env->vfp.vec_stride = qemu_get_be32(f);
7052 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7053 for (i = 0; i < 16; i++) {
7054 CPU_DoubleU u;
7055 u.l.upper = qemu_get_be32(f);
7056 u.l.lower = qemu_get_be32(f);
7057 env->vfp.regs[i] = u.d;
7062 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7063 for (i = 0; i < 16; i++) {
7064 env->iwmmxt.regs[i] = qemu_get_be64(f);
7066 for (i = 0; i < 16; i++) {
7067 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7071 if (arm_feature(env, ARM_FEATURE_M)) {
7072 env->v7m.other_sp = qemu_get_be32(f);
7073 env->v7m.vecbase = qemu_get_be32(f);
7074 env->v7m.basepri = qemu_get_be32(f);
7075 env->v7m.control = qemu_get_be32(f);
7076 env->v7m.current_sp = qemu_get_be32(f);
7077 env->v7m.exception = qemu_get_be32(f);
7080 return 0;
7083 #elif defined(TARGET_IA64)
7084 void cpu_save(QEMUFile *f, void *opaque)
7088 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7090 return 0;
7092 #else
7094 //#warning No CPU save/restore functions
7096 #endif
7098 /***********************************************************/
7099 /* ram save/restore */
7101 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7103 int v;
7105 v = qemu_get_byte(f);
7106 switch(v) {
7107 case 0:
7108 if (qemu_get_buffer(f, buf, len) != len)
7109 return -EIO;
7110 break;
7111 case 1:
7112 v = qemu_get_byte(f);
7113 memset(buf, v, len);
7114 break;
7115 default:
7116 return -EINVAL;
7118 return 0;
7121 static int ram_load_v1(QEMUFile *f, void *opaque)
7123 int i, ret;
7125 if (qemu_get_be32(f) != phys_ram_size)
7126 return -EINVAL;
7127 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7128 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7129 continue;
7130 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7131 if (ret)
7132 return ret;
7134 return 0;
7137 #define BDRV_HASH_BLOCK_SIZE 1024
7138 #define IOBUF_SIZE 4096
7139 #define RAM_CBLOCK_MAGIC 0xfabe
7141 typedef struct RamCompressState {
7142 z_stream zstream;
7143 QEMUFile *f;
7144 uint8_t buf[IOBUF_SIZE];
7145 } RamCompressState;
7147 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7149 int ret;
7150 memset(s, 0, sizeof(*s));
7151 s->f = f;
7152 ret = deflateInit2(&s->zstream, 1,
7153 Z_DEFLATED, 15,
7154 9, Z_DEFAULT_STRATEGY);
7155 if (ret != Z_OK)
7156 return -1;
7157 s->zstream.avail_out = IOBUF_SIZE;
7158 s->zstream.next_out = s->buf;
7159 return 0;
7162 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7164 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7165 qemu_put_be16(s->f, len);
7166 qemu_put_buffer(s->f, buf, len);
7169 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7171 int ret;
7173 s->zstream.avail_in = len;
7174 s->zstream.next_in = (uint8_t *)buf;
7175 while (s->zstream.avail_in > 0) {
7176 ret = deflate(&s->zstream, Z_NO_FLUSH);
7177 if (ret != Z_OK)
7178 return -1;
7179 if (s->zstream.avail_out == 0) {
7180 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7181 s->zstream.avail_out = IOBUF_SIZE;
7182 s->zstream.next_out = s->buf;
7185 return 0;
7188 static void ram_compress_close(RamCompressState *s)
7190 int len, ret;
7192 /* compress last bytes */
7193 for(;;) {
7194 ret = deflate(&s->zstream, Z_FINISH);
7195 if (ret == Z_OK || ret == Z_STREAM_END) {
7196 len = IOBUF_SIZE - s->zstream.avail_out;
7197 if (len > 0) {
7198 ram_put_cblock(s, s->buf, len);
7200 s->zstream.avail_out = IOBUF_SIZE;
7201 s->zstream.next_out = s->buf;
7202 if (ret == Z_STREAM_END)
7203 break;
7204 } else {
7205 goto fail;
7208 fail:
7209 deflateEnd(&s->zstream);
7212 typedef struct RamDecompressState {
7213 z_stream zstream;
7214 QEMUFile *f;
7215 uint8_t buf[IOBUF_SIZE];
7216 } RamDecompressState;
7218 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7220 int ret;
7221 memset(s, 0, sizeof(*s));
7222 s->f = f;
7223 ret = inflateInit(&s->zstream);
7224 if (ret != Z_OK)
7225 return -1;
7226 return 0;
7229 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7231 int ret, clen;
7233 s->zstream.avail_out = len;
7234 s->zstream.next_out = buf;
7235 while (s->zstream.avail_out > 0) {
7236 if (s->zstream.avail_in == 0) {
7237 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7238 return -1;
7239 clen = qemu_get_be16(s->f);
7240 if (clen > IOBUF_SIZE)
7241 return -1;
7242 qemu_get_buffer(s->f, s->buf, clen);
7243 s->zstream.avail_in = clen;
7244 s->zstream.next_in = s->buf;
7246 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7247 if (ret != Z_OK && ret != Z_STREAM_END) {
7248 return -1;
7251 return 0;
7254 static void ram_decompress_close(RamDecompressState *s)
7256 inflateEnd(&s->zstream);
7259 static void ram_save_live(QEMUFile *f, void *opaque)
7261 target_ulong addr;
7263 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7264 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7265 continue;
7266 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7267 qemu_put_be32(f, addr);
7268 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7271 qemu_put_be32(f, 1);
7274 static void ram_save_static(QEMUFile *f, void *opaque)
7276 int i;
7277 RamCompressState s1, *s = &s1;
7278 uint8_t buf[10];
7280 qemu_put_be32(f, phys_ram_size);
7281 if (ram_compress_open(s, f) < 0)
7282 return;
7283 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7284 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7285 continue;
7286 #if 0
7287 if (tight_savevm_enabled) {
7288 int64_t sector_num;
7289 int j;
7291 /* find if the memory block is available on a virtual
7292 block device */
7293 sector_num = -1;
7294 for(j = 0; j < nb_drives; j++) {
7295 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7296 phys_ram_base + i,
7297 BDRV_HASH_BLOCK_SIZE);
7298 if (sector_num >= 0)
7299 break;
7301 if (j == nb_drives)
7302 goto normal_compress;
7303 buf[0] = 1;
7304 buf[1] = j;
7305 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7306 ram_compress_buf(s, buf, 10);
7307 } else
7308 #endif
7310 // normal_compress:
7311 buf[0] = 0;
7312 ram_compress_buf(s, buf, 1);
7313 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7316 ram_compress_close(s);
7319 static void ram_save(QEMUFile *f, void *opaque)
7321 int in_migration = cpu_physical_memory_get_dirty_tracking();
7323 qemu_put_byte(f, in_migration);
7325 if (in_migration)
7326 ram_save_live(f, opaque);
7327 else
7328 ram_save_static(f, opaque);
7331 static int ram_load_live(QEMUFile *f, void *opaque)
7333 target_ulong addr;
7335 do {
7336 addr = qemu_get_be32(f);
7337 if (addr == 1)
7338 break;
7340 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7341 } while (1);
7343 return 0;
7346 static int ram_load_static(QEMUFile *f, void *opaque)
7348 RamDecompressState s1, *s = &s1;
7349 uint8_t buf[10];
7350 int i;
7352 if (qemu_get_be32(f) != phys_ram_size)
7353 return -EINVAL;
7354 if (ram_decompress_open(s, f) < 0)
7355 return -EINVAL;
7356 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7357 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7358 continue;
7359 if (ram_decompress_buf(s, buf, 1) < 0) {
7360 fprintf(stderr, "Error while reading ram block header\n");
7361 goto error;
7363 if (buf[0] == 0) {
7364 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7365 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7366 goto error;
7368 } else
7369 #if 0
7370 if (buf[0] == 1) {
7371 int bs_index;
7372 int64_t sector_num;
7374 ram_decompress_buf(s, buf + 1, 9);
7375 bs_index = buf[1];
7376 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7377 if (bs_index >= nb_drives) {
7378 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7379 goto error;
7381 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7382 phys_ram_base + i,
7383 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7384 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7385 bs_index, sector_num);
7386 goto error;
7388 } else
7389 #endif
7391 error:
7392 printf("Error block header\n");
7393 return -EINVAL;
7396 ram_decompress_close(s);
7397 return 0;
7400 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7402 int ret;
7404 switch (version_id) {
7405 case 1:
7406 ret = ram_load_v1(f, opaque);
7407 break;
7408 case 3:
7409 if (qemu_get_byte(f)) {
7410 ret = ram_load_live(f, opaque);
7411 break;
7413 case 2:
7414 ret = ram_load_static(f, opaque);
7415 break;
7416 default:
7417 ret = -EINVAL;
7418 break;
7421 return ret;
7424 /***********************************************************/
7425 /* bottom halves (can be seen as timers which expire ASAP) */
7427 struct QEMUBH {
7428 QEMUBHFunc *cb;
7429 void *opaque;
7430 int scheduled;
7431 QEMUBH *next;
7434 static QEMUBH *first_bh = NULL;
7436 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7438 QEMUBH *bh;
7439 bh = qemu_mallocz(sizeof(QEMUBH));
7440 if (!bh)
7441 return NULL;
7442 bh->cb = cb;
7443 bh->opaque = opaque;
7444 return bh;
7447 int qemu_bh_poll(void)
7449 QEMUBH *bh, **pbh;
7450 int ret;
7452 ret = 0;
7453 for(;;) {
7454 pbh = &first_bh;
7455 bh = *pbh;
7456 if (!bh)
7457 break;
7458 ret = 1;
7459 *pbh = bh->next;
7460 bh->scheduled = 0;
7461 bh->cb(bh->opaque);
7463 return ret;
7466 void qemu_bh_schedule(QEMUBH *bh)
7468 CPUState *env = cpu_single_env;
7469 if (bh->scheduled)
7470 return;
7471 bh->scheduled = 1;
7472 bh->next = first_bh;
7473 first_bh = bh;
7475 /* stop the currently executing CPU to execute the BH ASAP */
7476 if (env) {
7477 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7481 void qemu_bh_cancel(QEMUBH *bh)
7483 QEMUBH **pbh;
7484 if (bh->scheduled) {
7485 pbh = &first_bh;
7486 while (*pbh != bh)
7487 pbh = &(*pbh)->next;
7488 *pbh = bh->next;
7489 bh->scheduled = 0;
7493 void qemu_bh_delete(QEMUBH *bh)
7495 qemu_bh_cancel(bh);
7496 qemu_free(bh);
7499 /***********************************************************/
7500 /* machine registration */
7502 QEMUMachine *first_machine = NULL;
7504 int qemu_register_machine(QEMUMachine *m)
7506 QEMUMachine **pm;
7507 pm = &first_machine;
7508 while (*pm != NULL)
7509 pm = &(*pm)->next;
7510 m->next = NULL;
7511 *pm = m;
7512 return 0;
7515 static QEMUMachine *find_machine(const char *name)
7517 QEMUMachine *m;
7519 for(m = first_machine; m != NULL; m = m->next) {
7520 if (!strcmp(m->name, name))
7521 return m;
7523 return NULL;
7526 /***********************************************************/
7527 /* main execution loop */
7529 static void gui_update(void *opaque)
7531 DisplayState *ds = opaque;
7532 ds->dpy_refresh(ds);
7533 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7536 struct vm_change_state_entry {
7537 VMChangeStateHandler *cb;
7538 void *opaque;
7539 LIST_ENTRY (vm_change_state_entry) entries;
7542 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7544 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7545 void *opaque)
7547 VMChangeStateEntry *e;
7549 e = qemu_mallocz(sizeof (*e));
7550 if (!e)
7551 return NULL;
7553 e->cb = cb;
7554 e->opaque = opaque;
7555 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7556 return e;
7559 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7561 LIST_REMOVE (e, entries);
7562 qemu_free (e);
7565 static void vm_state_notify(int running)
7567 VMChangeStateEntry *e;
7569 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7570 e->cb(e->opaque, running);
7574 /* XXX: support several handlers */
7575 static VMStopHandler *vm_stop_cb;
7576 static void *vm_stop_opaque;
7578 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7580 vm_stop_cb = cb;
7581 vm_stop_opaque = opaque;
7582 return 0;
7585 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7587 vm_stop_cb = NULL;
7590 void vm_start(void)
7592 if (!vm_running) {
7593 cpu_enable_ticks();
7594 vm_running = 1;
7595 vm_state_notify(1);
7596 qemu_rearm_alarm_timer(alarm_timer);
7600 void vm_stop(int reason)
7602 if (vm_running) {
7603 cpu_disable_ticks();
7604 vm_running = 0;
7605 if (reason != 0) {
7606 if (vm_stop_cb) {
7607 vm_stop_cb(vm_stop_opaque, reason);
7610 vm_state_notify(0);
7614 /* reset/shutdown handler */
7616 typedef struct QEMUResetEntry {
7617 QEMUResetHandler *func;
7618 void *opaque;
7619 struct QEMUResetEntry *next;
7620 } QEMUResetEntry;
7622 static QEMUResetEntry *first_reset_entry;
7623 static int reset_requested;
7624 static int shutdown_requested;
7625 static int powerdown_requested;
7627 int qemu_shutdown_requested(void)
7629 int r = shutdown_requested;
7630 shutdown_requested = 0;
7631 return r;
7634 int qemu_reset_requested(void)
7636 int r = reset_requested;
7637 reset_requested = 0;
7638 return r;
7641 int qemu_powerdown_requested(void)
7643 int r = powerdown_requested;
7644 powerdown_requested = 0;
7645 return r;
7648 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7650 QEMUResetEntry **pre, *re;
7652 pre = &first_reset_entry;
7653 while (*pre != NULL)
7654 pre = &(*pre)->next;
7655 re = qemu_mallocz(sizeof(QEMUResetEntry));
7656 re->func = func;
7657 re->opaque = opaque;
7658 re->next = NULL;
7659 *pre = re;
7662 void qemu_system_reset(void)
7664 QEMUResetEntry *re;
7666 /* reset all devices */
7667 for(re = first_reset_entry; re != NULL; re = re->next) {
7668 re->func(re->opaque);
7672 void qemu_system_reset_request(void)
7674 if (no_reboot) {
7675 shutdown_requested = 1;
7676 } else {
7677 reset_requested = 1;
7679 if (cpu_single_env)
7680 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7683 void qemu_system_shutdown_request(void)
7685 shutdown_requested = 1;
7686 if (cpu_single_env)
7687 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7690 void qemu_system_powerdown_request(void)
7692 powerdown_requested = 1;
7693 if (cpu_single_env)
7694 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7697 void main_loop_wait(int timeout)
7699 IOHandlerRecord *ioh;
7700 fd_set rfds, wfds, xfds;
7701 int ret, nfds;
7702 #ifdef _WIN32
7703 int ret2, i;
7704 #endif
7705 struct timeval tv;
7706 PollingEntry *pe;
7709 /* XXX: need to suppress polling by better using win32 events */
7710 ret = 0;
7711 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7712 ret |= pe->func(pe->opaque);
7714 #ifdef _WIN32
7715 if (ret == 0) {
7716 int err;
7717 WaitObjects *w = &wait_objects;
7719 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7720 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7721 if (w->func[ret - WAIT_OBJECT_0])
7722 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7724 /* Check for additional signaled events */
7725 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7727 /* Check if event is signaled */
7728 ret2 = WaitForSingleObject(w->events[i], 0);
7729 if(ret2 == WAIT_OBJECT_0) {
7730 if (w->func[i])
7731 w->func[i](w->opaque[i]);
7732 } else if (ret2 == WAIT_TIMEOUT) {
7733 } else {
7734 err = GetLastError();
7735 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7738 } else if (ret == WAIT_TIMEOUT) {
7739 } else {
7740 err = GetLastError();
7741 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7744 #endif
7745 /* poll any events */
7746 /* XXX: separate device handlers from system ones */
7747 nfds = -1;
7748 FD_ZERO(&rfds);
7749 FD_ZERO(&wfds);
7750 FD_ZERO(&xfds);
7751 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7752 if (ioh->deleted)
7753 continue;
7754 if (ioh->fd_read &&
7755 (!ioh->fd_read_poll ||
7756 ioh->fd_read_poll(ioh->opaque) != 0)) {
7757 FD_SET(ioh->fd, &rfds);
7758 if (ioh->fd > nfds)
7759 nfds = ioh->fd;
7761 if (ioh->fd_write) {
7762 FD_SET(ioh->fd, &wfds);
7763 if (ioh->fd > nfds)
7764 nfds = ioh->fd;
7768 tv.tv_sec = 0;
7769 #ifdef _WIN32
7770 tv.tv_usec = 0;
7771 #else
7772 tv.tv_usec = timeout * 1000;
7773 #endif
7774 #if defined(CONFIG_SLIRP)
7775 if (slirp_inited) {
7776 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7778 #endif
7779 moreio:
7780 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7781 if (ret > 0) {
7782 IOHandlerRecord **pioh;
7783 int more = 0;
7785 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7786 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7787 ioh->fd_read(ioh->opaque);
7788 more = 1;
7790 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7791 ioh->fd_write(ioh->opaque);
7792 more = 1;
7796 /* remove deleted IO handlers */
7797 pioh = &first_io_handler;
7798 while (*pioh) {
7799 ioh = *pioh;
7800 if (ioh->deleted) {
7801 *pioh = ioh->next;
7802 qemu_free(ioh);
7803 } else
7804 pioh = &ioh->next;
7806 if (more)
7807 goto moreio;
7809 #if defined(CONFIG_SLIRP)
7810 if (slirp_inited) {
7811 if (ret < 0) {
7812 FD_ZERO(&rfds);
7813 FD_ZERO(&wfds);
7814 FD_ZERO(&xfds);
7816 slirp_select_poll(&rfds, &wfds, &xfds);
7818 #endif
7819 virtio_net_poll();
7821 qemu_aio_poll();
7823 if (vm_running) {
7824 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7825 qemu_get_clock(vm_clock));
7826 /* run dma transfers, if any */
7827 DMA_run();
7830 /* real time timers */
7831 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7832 qemu_get_clock(rt_clock));
7834 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7835 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7836 qemu_rearm_alarm_timer(alarm_timer);
7839 /* Check bottom-halves last in case any of the earlier events triggered
7840 them. */
7841 qemu_bh_poll();
7845 static int main_loop(void)
7847 int ret, timeout;
7848 #ifdef CONFIG_PROFILER
7849 int64_t ti;
7850 #endif
7851 CPUState *env;
7854 if (kvm_enabled()) {
7855 kvm_main_loop();
7856 cpu_disable_ticks();
7857 return 0;
7860 cur_cpu = first_cpu;
7861 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7862 for(;;) {
7863 if (vm_running) {
7865 for(;;) {
7866 /* get next cpu */
7867 env = next_cpu;
7868 #ifdef CONFIG_PROFILER
7869 ti = profile_getclock();
7870 #endif
7871 ret = cpu_exec(env);
7872 #ifdef CONFIG_PROFILER
7873 qemu_time += profile_getclock() - ti;
7874 #endif
7875 next_cpu = env->next_cpu ?: first_cpu;
7876 if (event_pending) {
7877 ret = EXCP_INTERRUPT;
7878 event_pending = 0;
7879 break;
7881 if (ret == EXCP_HLT) {
7882 /* Give the next CPU a chance to run. */
7883 cur_cpu = env;
7884 continue;
7886 if (ret != EXCP_HALTED)
7887 break;
7888 /* all CPUs are halted ? */
7889 if (env == cur_cpu)
7890 break;
7892 cur_cpu = env;
7894 if (shutdown_requested) {
7895 ret = EXCP_INTERRUPT;
7896 break;
7898 if (reset_requested) {
7899 reset_requested = 0;
7900 qemu_system_reset();
7901 if (kvm_enabled())
7902 kvm_load_registers(env);
7903 ret = EXCP_INTERRUPT;
7905 if (powerdown_requested) {
7906 powerdown_requested = 0;
7907 qemu_system_powerdown();
7908 ret = EXCP_INTERRUPT;
7910 if (ret == EXCP_DEBUG) {
7911 vm_stop(EXCP_DEBUG);
7913 /* If all cpus are halted then wait until the next IRQ */
7914 /* XXX: use timeout computed from timers */
7915 if (ret == EXCP_HALTED)
7916 timeout = 10;
7917 else
7918 timeout = 0;
7919 } else {
7920 timeout = 10;
7922 #ifdef CONFIG_PROFILER
7923 ti = profile_getclock();
7924 #endif
7925 main_loop_wait(timeout);
7926 #ifdef CONFIG_PROFILER
7927 dev_time += profile_getclock() - ti;
7928 #endif
7930 cpu_disable_ticks();
7931 return ret;
7934 static void help(int exitcode)
7936 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7937 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7938 "usage: %s [options] [disk_image]\n"
7939 "\n"
7940 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7941 "\n"
7942 "Standard options:\n"
7943 "-M machine select emulated machine (-M ? for list)\n"
7944 "-cpu cpu select CPU (-cpu ? for list)\n"
7945 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7946 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7947 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7948 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7949 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7950 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7951 " [,cache=on|off][,boot=on|off]\n"
7952 " use 'file' as a drive image\n"
7953 "-mtdblock file use 'file' as on-board Flash memory image\n"
7954 "-sd file use 'file' as SecureDigital card image\n"
7955 "-pflash file use 'file' as a parallel flash image\n"
7956 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7957 "-snapshot write to temporary files instead of disk image files\n"
7958 #ifdef CONFIG_SDL
7959 "-no-frame open SDL window without a frame and window decorations\n"
7960 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7961 "-no-quit disable SDL window close capability\n"
7962 #endif
7963 #ifdef TARGET_I386
7964 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7965 #endif
7966 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7967 "-smp n set the number of CPUs to 'n' [default=1]\n"
7968 "-nographic disable graphical output and redirect serial I/Os to console\n"
7969 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7970 #ifndef _WIN32
7971 "-k language use keyboard layout (for example \"fr\" for French)\n"
7972 #endif
7973 #ifdef HAS_AUDIO
7974 "-audio-help print list of audio drivers and their options\n"
7975 "-soundhw c1,... enable audio support\n"
7976 " and only specified sound cards (comma separated list)\n"
7977 " use -soundhw ? to get the list of supported cards\n"
7978 " use -soundhw all to enable all of them\n"
7979 #endif
7980 "-localtime set the real time clock to local time [default=utc]\n"
7981 "-full-screen start in full screen\n"
7982 #ifdef TARGET_I386
7983 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7984 #endif
7985 "-usb enable the USB driver (will be the default soon)\n"
7986 "-usbdevice name add the host or guest USB device 'name'\n"
7987 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7988 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7989 #endif
7990 "-name string set the name of the guest\n"
7991 "\n"
7992 "Network options:\n"
7993 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7994 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7995 #ifdef CONFIG_SLIRP
7996 "-net user[,vlan=n][,hostname=host]\n"
7997 " connect the user mode network stack to VLAN 'n' and send\n"
7998 " hostname 'host' to DHCP clients\n"
7999 #endif
8000 #ifdef _WIN32
8001 "-net tap[,vlan=n],ifname=name\n"
8002 " connect the host TAP network interface to VLAN 'n'\n"
8003 #else
8004 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8005 " connect the host TAP network interface to VLAN 'n' and use the\n"
8006 " network scripts 'file' (default=%s)\n"
8007 " and 'dfile' (default=%s);\n"
8008 " use '[down]script=no' to disable script execution;\n"
8009 " use 'fd=h' to connect to an already opened TAP interface\n"
8010 #endif
8011 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8012 " connect the vlan 'n' to another VLAN using a socket connection\n"
8013 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8014 " connect the vlan 'n' to multicast maddr and port\n"
8015 "-net none use it alone to have zero network devices; if no -net option\n"
8016 " is provided, the default is '-net nic -net user'\n"
8017 "\n"
8018 #ifdef CONFIG_SLIRP
8019 "-tftp dir allow tftp access to files in dir [-net user]\n"
8020 "-bootp file advertise file in BOOTP replies\n"
8021 #ifndef _WIN32
8022 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8023 #endif
8024 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8025 " redirect TCP or UDP connections from host to guest [-net user]\n"
8026 #endif
8027 "\n"
8028 "Linux boot specific:\n"
8029 "-kernel bzImage use 'bzImage' as kernel image\n"
8030 "-append cmdline use 'cmdline' as kernel command line\n"
8031 "-initrd file use 'file' as initial ram disk\n"
8032 "\n"
8033 "Debug/Expert options:\n"
8034 "-monitor dev redirect the monitor to char device 'dev'\n"
8035 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8036 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8037 "-serial dev redirect the serial port to char device 'dev'\n"
8038 "-parallel dev redirect the parallel port to char device 'dev'\n"
8039 "-pidfile file Write PID to 'file'\n"
8040 "-S freeze CPU at startup (use 'c' to start execution)\n"
8041 "-s wait gdb connection to port\n"
8042 "-p port set gdb connection port [default=%s]\n"
8043 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8044 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8045 " translation (t=none or lba) (usually qemu can guess them)\n"
8046 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8047 #ifdef USE_KQEMU
8048 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8049 "-no-kqemu disable KQEMU kernel module usage\n"
8050 #endif
8051 #ifdef USE_KVM
8052 "-no-kvm disable KVM hardware virtualization\n"
8053 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8054 #endif
8055 #ifdef TARGET_I386
8056 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8057 " (default is CL-GD5446 PCI VGA)\n"
8058 "-no-acpi disable ACPI\n"
8059 #endif
8060 "-no-reboot exit instead of rebooting\n"
8061 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8062 "-vnc display start a VNC server on display\n"
8063 #ifndef _WIN32
8064 "-daemonize daemonize QEMU after initializing\n"
8065 #endif
8066 "-tdf inject timer interrupts that got lost\n"
8067 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8068 "-option-rom rom load a file, rom, into the option ROM space\n"
8069 #ifdef TARGET_SPARC
8070 "-prom-env variable=value set OpenBIOS nvram variables\n"
8071 #endif
8072 "-clock force the use of the given methods for timer alarm.\n"
8073 " To see what timers are available use -clock help\n"
8074 "-startdate select initial date of the Qemu clock\n"
8075 "-translation setting1,... configures code translation\n"
8076 " (use -translation ? for a list of settings)\n"
8077 "\n"
8078 "During emulation, the following keys are useful:\n"
8079 "ctrl-alt-f toggle full screen\n"
8080 "ctrl-alt-n switch to virtual console 'n'\n"
8081 "ctrl-alt toggle mouse and keyboard grab\n"
8082 "\n"
8083 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8085 "qemu",
8086 DEFAULT_RAM_SIZE,
8087 #ifndef _WIN32
8088 DEFAULT_NETWORK_SCRIPT,
8089 DEFAULT_NETWORK_DOWN_SCRIPT,
8090 #endif
8091 DEFAULT_GDBSTUB_PORT,
8092 logfilename);
8093 exit(exitcode);
8096 #define HAS_ARG 0x0001
8098 enum {
8099 QEMU_OPTION_h,
8101 QEMU_OPTION_M,
8102 QEMU_OPTION_cpu,
8103 QEMU_OPTION_fda,
8104 QEMU_OPTION_fdb,
8105 QEMU_OPTION_hda,
8106 QEMU_OPTION_hdb,
8107 QEMU_OPTION_hdc,
8108 QEMU_OPTION_hdd,
8109 QEMU_OPTION_drive,
8110 QEMU_OPTION_cdrom,
8111 QEMU_OPTION_mtdblock,
8112 QEMU_OPTION_sd,
8113 QEMU_OPTION_pflash,
8114 QEMU_OPTION_boot,
8115 QEMU_OPTION_snapshot,
8116 #ifdef TARGET_I386
8117 QEMU_OPTION_no_fd_bootchk,
8118 #endif
8119 QEMU_OPTION_m,
8120 QEMU_OPTION_nographic,
8121 QEMU_OPTION_portrait,
8122 #ifdef HAS_AUDIO
8123 QEMU_OPTION_audio_help,
8124 QEMU_OPTION_soundhw,
8125 #endif
8127 QEMU_OPTION_net,
8128 QEMU_OPTION_tftp,
8129 QEMU_OPTION_bootp,
8130 QEMU_OPTION_smb,
8131 QEMU_OPTION_redir,
8133 QEMU_OPTION_kernel,
8134 QEMU_OPTION_append,
8135 QEMU_OPTION_initrd,
8137 QEMU_OPTION_S,
8138 QEMU_OPTION_s,
8139 QEMU_OPTION_p,
8140 QEMU_OPTION_d,
8141 QEMU_OPTION_hdachs,
8142 QEMU_OPTION_L,
8143 QEMU_OPTION_bios,
8144 QEMU_OPTION_no_code_copy,
8145 QEMU_OPTION_k,
8146 QEMU_OPTION_localtime,
8147 QEMU_OPTION_cirrusvga,
8148 QEMU_OPTION_vmsvga,
8149 QEMU_OPTION_g,
8150 QEMU_OPTION_std_vga,
8151 QEMU_OPTION_echr,
8152 QEMU_OPTION_monitor,
8153 QEMU_OPTION_balloon,
8154 QEMU_OPTION_vmchannel,
8155 QEMU_OPTION_serial,
8156 QEMU_OPTION_parallel,
8157 QEMU_OPTION_loadvm,
8158 QEMU_OPTION_full_screen,
8159 QEMU_OPTION_no_frame,
8160 QEMU_OPTION_alt_grab,
8161 QEMU_OPTION_no_quit,
8162 QEMU_OPTION_pidfile,
8163 QEMU_OPTION_no_kqemu,
8164 QEMU_OPTION_kernel_kqemu,
8165 QEMU_OPTION_win2k_hack,
8166 QEMU_OPTION_usb,
8167 QEMU_OPTION_usbdevice,
8168 QEMU_OPTION_smp,
8169 QEMU_OPTION_vnc,
8170 QEMU_OPTION_no_acpi,
8171 QEMU_OPTION_no_kvm,
8172 QEMU_OPTION_no_kvm_irqchip,
8173 QEMU_OPTION_no_reboot,
8174 QEMU_OPTION_show_cursor,
8175 QEMU_OPTION_daemonize,
8176 QEMU_OPTION_option_rom,
8177 QEMU_OPTION_semihosting,
8178 QEMU_OPTION_cpu_vendor,
8179 QEMU_OPTION_name,
8180 QEMU_OPTION_prom_env,
8181 QEMU_OPTION_old_param,
8182 QEMU_OPTION_clock,
8183 QEMU_OPTION_startdate,
8184 QEMU_OPTION_translation,
8185 QEMU_OPTION_incoming,
8186 QEMU_OPTION_tdf,
8187 QEMU_OPTION_kvm_shadow_memory,
8190 typedef struct QEMUOption {
8191 const char *name;
8192 int flags;
8193 int index;
8194 } QEMUOption;
8196 const QEMUOption qemu_options[] = {
8197 { "h", 0, QEMU_OPTION_h },
8198 { "help", 0, QEMU_OPTION_h },
8200 { "M", HAS_ARG, QEMU_OPTION_M },
8201 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8202 { "fda", HAS_ARG, QEMU_OPTION_fda },
8203 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8204 { "hda", HAS_ARG, QEMU_OPTION_hda },
8205 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8206 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8207 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8208 { "drive", HAS_ARG, QEMU_OPTION_drive },
8209 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8210 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8211 { "sd", HAS_ARG, QEMU_OPTION_sd },
8212 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8213 { "boot", HAS_ARG, QEMU_OPTION_boot },
8214 { "snapshot", 0, QEMU_OPTION_snapshot },
8215 #ifdef TARGET_I386
8216 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8217 #endif
8218 { "m", HAS_ARG, QEMU_OPTION_m },
8219 { "nographic", 0, QEMU_OPTION_nographic },
8220 { "portrait", 0, QEMU_OPTION_portrait },
8221 { "k", HAS_ARG, QEMU_OPTION_k },
8222 #ifdef HAS_AUDIO
8223 { "audio-help", 0, QEMU_OPTION_audio_help },
8224 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8225 #endif
8227 { "net", HAS_ARG, QEMU_OPTION_net},
8228 #ifdef CONFIG_SLIRP
8229 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8230 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8231 #ifndef _WIN32
8232 { "smb", HAS_ARG, QEMU_OPTION_smb },
8233 #endif
8234 { "redir", HAS_ARG, QEMU_OPTION_redir },
8235 #endif
8237 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8238 { "append", HAS_ARG, QEMU_OPTION_append },
8239 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8241 { "S", 0, QEMU_OPTION_S },
8242 { "s", 0, QEMU_OPTION_s },
8243 { "p", HAS_ARG, QEMU_OPTION_p },
8244 { "d", HAS_ARG, QEMU_OPTION_d },
8245 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8246 { "L", HAS_ARG, QEMU_OPTION_L },
8247 { "bios", HAS_ARG, QEMU_OPTION_bios },
8248 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8249 #ifdef USE_KQEMU
8250 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8251 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8252 #endif
8253 #ifdef USE_KVM
8254 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8255 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8256 #endif
8257 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8258 { "g", 1, QEMU_OPTION_g },
8259 #endif
8260 { "localtime", 0, QEMU_OPTION_localtime },
8261 { "std-vga", 0, QEMU_OPTION_std_vga },
8262 { "monitor", 1, QEMU_OPTION_monitor },
8263 { "balloon", 1, QEMU_OPTION_balloon },
8264 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8265 { "echr", HAS_ARG, QEMU_OPTION_echr },
8266 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8267 { "serial", HAS_ARG, QEMU_OPTION_serial },
8268 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8269 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8270 { "incoming", 1, QEMU_OPTION_incoming },
8271 { "full-screen", 0, QEMU_OPTION_full_screen },
8272 #ifdef CONFIG_SDL
8273 { "no-frame", 0, QEMU_OPTION_no_frame },
8274 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8275 { "no-quit", 0, QEMU_OPTION_no_quit },
8276 #endif
8277 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8278 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8279 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8280 { "smp", HAS_ARG, QEMU_OPTION_smp },
8281 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8283 /* temporary options */
8284 { "usb", 0, QEMU_OPTION_usb },
8285 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8286 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8287 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8288 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8289 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8290 { "daemonize", 0, QEMU_OPTION_daemonize },
8291 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8292 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8293 { "semihosting", 0, QEMU_OPTION_semihosting },
8294 #endif
8295 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8296 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8297 { "name", HAS_ARG, QEMU_OPTION_name },
8298 #if defined(TARGET_SPARC)
8299 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8300 #endif
8301 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8302 #if defined(TARGET_ARM)
8303 { "old-param", 0, QEMU_OPTION_old_param },
8304 #endif
8305 { "clock", HAS_ARG, QEMU_OPTION_clock },
8306 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8307 { "translation", HAS_ARG, QEMU_OPTION_translation },
8308 { NULL },
8311 /* password input */
8313 int qemu_key_check(BlockDriverState *bs, const char *name)
8315 char password[256];
8316 int i;
8318 if (!bdrv_is_encrypted(bs))
8319 return 0;
8321 term_printf("%s is encrypted.\n", name);
8322 for(i = 0; i < 3; i++) {
8323 monitor_readline("Password: ", 1, password, sizeof(password));
8324 if (bdrv_set_key(bs, password) == 0)
8325 return 0;
8326 term_printf("invalid password\n");
8328 return -EPERM;
8331 static BlockDriverState *get_bdrv(int index)
8333 if (index > nb_drives)
8334 return NULL;
8335 return drives_table[index].bdrv;
8338 static void read_passwords(void)
8340 BlockDriverState *bs;
8341 int i;
8343 for(i = 0; i < 6; i++) {
8344 bs = get_bdrv(i);
8345 if (bs)
8346 qemu_key_check(bs, bdrv_get_device_name(bs));
8350 /* XXX: currently we cannot use simultaneously different CPUs */
8351 static void register_machines(void)
8353 #if defined(TARGET_I386)
8354 qemu_register_machine(&pc_machine);
8355 qemu_register_machine(&isapc_machine);
8356 #elif defined(TARGET_PPC)
8357 qemu_register_machine(&heathrow_machine);
8358 qemu_register_machine(&core99_machine);
8359 qemu_register_machine(&prep_machine);
8360 qemu_register_machine(&ref405ep_machine);
8361 qemu_register_machine(&taihu_machine);
8362 qemu_register_machine(&bamboo_machine);
8363 #elif defined(TARGET_MIPS)
8364 qemu_register_machine(&mips_machine);
8365 qemu_register_machine(&mips_malta_machine);
8366 qemu_register_machine(&mips_pica61_machine);
8367 qemu_register_machine(&mips_mipssim_machine);
8368 #elif defined(TARGET_SPARC)
8369 #ifdef TARGET_SPARC64
8370 qemu_register_machine(&sun4u_machine);
8371 #else
8372 qemu_register_machine(&ss5_machine);
8373 qemu_register_machine(&ss10_machine);
8374 qemu_register_machine(&ss600mp_machine);
8375 qemu_register_machine(&ss20_machine);
8376 qemu_register_machine(&ss2_machine);
8377 qemu_register_machine(&ss1000_machine);
8378 qemu_register_machine(&ss2000_machine);
8379 #endif
8380 #elif defined(TARGET_ARM)
8381 qemu_register_machine(&integratorcp_machine);
8382 qemu_register_machine(&versatilepb_machine);
8383 qemu_register_machine(&versatileab_machine);
8384 qemu_register_machine(&realview_machine);
8385 qemu_register_machine(&akitapda_machine);
8386 qemu_register_machine(&spitzpda_machine);
8387 qemu_register_machine(&borzoipda_machine);
8388 qemu_register_machine(&terrierpda_machine);
8389 qemu_register_machine(&palmte_machine);
8390 qemu_register_machine(&lm3s811evb_machine);
8391 qemu_register_machine(&lm3s6965evb_machine);
8392 qemu_register_machine(&connex_machine);
8393 qemu_register_machine(&verdex_machine);
8394 qemu_register_machine(&mainstone2_machine);
8395 #elif defined(TARGET_SH4)
8396 qemu_register_machine(&shix_machine);
8397 qemu_register_machine(&r2d_machine);
8398 #elif defined(TARGET_ALPHA)
8399 /* XXX: TODO */
8400 #elif defined(TARGET_M68K)
8401 qemu_register_machine(&mcf5208evb_machine);
8402 qemu_register_machine(&an5206_machine);
8403 qemu_register_machine(&dummy_m68k_machine);
8404 #elif defined(TARGET_CRIS)
8405 qemu_register_machine(&bareetraxfs_machine);
8406 #elif defined(TARGET_IA64)
8407 qemu_register_machine(&ipf_machine);
8408 #else
8409 #error unsupported CPU
8410 #endif
8413 #ifdef HAS_AUDIO
8414 struct soundhw soundhw[] = {
8415 #ifdef HAS_AUDIO_CHOICE
8416 #ifdef TARGET_I386
8418 "pcspk",
8419 "PC speaker",
8422 { .init_isa = pcspk_audio_init }
8424 #endif
8426 "sb16",
8427 "Creative Sound Blaster 16",
8430 { .init_isa = SB16_init }
8433 #ifdef CONFIG_ADLIB
8435 "adlib",
8436 #ifdef HAS_YMF262
8437 "Yamaha YMF262 (OPL3)",
8438 #else
8439 "Yamaha YM3812 (OPL2)",
8440 #endif
8443 { .init_isa = Adlib_init }
8445 #endif
8447 #ifdef CONFIG_GUS
8449 "gus",
8450 "Gravis Ultrasound GF1",
8453 { .init_isa = GUS_init }
8455 #endif
8457 #ifdef CONFIG_AC97
8459 "ac97",
8460 "Intel 82801AA AC97 Audio",
8463 { .init_pci = ac97_init }
8465 #endif
8468 "es1370",
8469 "ENSONIQ AudioPCI ES1370",
8472 { .init_pci = es1370_init }
8474 #endif
8476 { NULL, NULL, 0, 0, { NULL } }
8479 static void select_soundhw (const char *optarg)
8481 struct soundhw *c;
8483 if (*optarg == '?') {
8484 show_valid_cards:
8486 printf ("Valid sound card names (comma separated):\n");
8487 for (c = soundhw; c->name; ++c) {
8488 printf ("%-11s %s\n", c->name, c->descr);
8490 printf ("\n-soundhw all will enable all of the above\n");
8491 exit (*optarg != '?');
8493 else {
8494 size_t l;
8495 const char *p;
8496 char *e;
8497 int bad_card = 0;
8499 if (!strcmp (optarg, "all")) {
8500 for (c = soundhw; c->name; ++c) {
8501 c->enabled = 1;
8503 return;
8506 p = optarg;
8507 while (*p) {
8508 e = strchr (p, ',');
8509 l = !e ? strlen (p) : (size_t) (e - p);
8511 for (c = soundhw; c->name; ++c) {
8512 if (!strncmp (c->name, p, l)) {
8513 c->enabled = 1;
8514 break;
8518 if (!c->name) {
8519 if (l > 80) {
8520 fprintf (stderr,
8521 "Unknown sound card name (too big to show)\n");
8523 else {
8524 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8525 (int) l, p);
8527 bad_card = 1;
8529 p += l + (e != NULL);
8532 if (bad_card)
8533 goto show_valid_cards;
8536 #endif
8538 #ifdef _WIN32
8539 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8541 exit(STATUS_CONTROL_C_EXIT);
8542 return TRUE;
8544 #endif
8546 #define MAX_NET_CLIENTS 32
8548 static int saved_argc;
8549 static char **saved_argv;
8551 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8553 *argc = saved_argc;
8554 *argv = saved_argv;
8555 *opt_daemonize = daemonize;
8556 *opt_incoming = incoming;
8559 int main(int argc, char **argv)
8561 #ifdef CONFIG_GDBSTUB
8562 int use_gdbstub;
8563 const char *gdbstub_port;
8564 #endif
8565 uint32_t boot_devices_bitmap = 0;
8566 int i;
8567 int snapshot, linux_boot, net_boot;
8568 const char *initrd_filename;
8569 const char *kernel_filename, *kernel_cmdline;
8570 const char *boot_devices = "";
8571 DisplayState *ds = &display_state;
8572 int cyls, heads, secs, translation;
8573 char net_clients[MAX_NET_CLIENTS][256];
8574 int nb_net_clients;
8575 int hda_index;
8576 int optind;
8577 const char *r, *optarg;
8578 CharDriverState *monitor_hd;
8579 char monitor_device[128];
8580 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8581 int vmchannel_device_index;
8582 char serial_devices[MAX_SERIAL_PORTS][128];
8583 int serial_device_index;
8584 char parallel_devices[MAX_PARALLEL_PORTS][128];
8585 int parallel_device_index;
8586 const char *loadvm = NULL;
8587 QEMUMachine *machine;
8588 const char *cpu_model;
8589 char usb_devices[MAX_USB_CMDLINE][128];
8590 int usb_devices_index;
8591 int fds[2];
8592 const char *pid_file = NULL;
8593 VLANState *vlan;
8595 saved_argc = argc;
8596 saved_argv = argv;
8598 LIST_INIT (&vm_change_state_head);
8599 #ifndef _WIN32
8601 struct sigaction act;
8602 sigfillset(&act.sa_mask);
8603 act.sa_flags = 0;
8604 act.sa_handler = SIG_IGN;
8605 sigaction(SIGPIPE, &act, NULL);
8607 #else
8608 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8609 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8610 QEMU to run on a single CPU */
8612 HANDLE h;
8613 DWORD mask, smask;
8614 int i;
8615 h = GetCurrentProcess();
8616 if (GetProcessAffinityMask(h, &mask, &smask)) {
8617 for(i = 0; i < 32; i++) {
8618 if (mask & (1 << i))
8619 break;
8621 if (i != 32) {
8622 mask = 1 << i;
8623 SetProcessAffinityMask(h, mask);
8627 #endif
8629 register_machines();
8630 machine = first_machine;
8631 cpu_model = NULL;
8632 initrd_filename = NULL;
8633 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8634 vga_ram_size = VGA_RAM_SIZE;
8635 #ifdef CONFIG_GDBSTUB
8636 use_gdbstub = 0;
8637 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8638 #endif
8639 snapshot = 0;
8640 nographic = 0;
8641 kernel_filename = NULL;
8642 kernel_cmdline = "";
8643 cyls = heads = secs = 0;
8644 translation = BIOS_ATA_TRANSLATION_AUTO;
8645 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8647 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8648 vmchannel_devices[i][0] = '\0';
8649 vmchannel_device_index = 0;
8651 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8652 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8653 serial_devices[i][0] = '\0';
8654 serial_device_index = 0;
8656 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8657 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8658 parallel_devices[i][0] = '\0';
8659 parallel_device_index = 0;
8661 usb_devices_index = 0;
8663 nb_net_clients = 0;
8664 nb_drives = 0;
8665 nb_drives_opt = 0;
8666 hda_index = -1;
8668 nb_nics = 0;
8669 /* default mac address of the first network interface */
8671 optind = 1;
8672 for(;;) {
8673 if (optind >= argc)
8674 break;
8675 r = argv[optind];
8676 if (r[0] != '-') {
8677 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8678 } else {
8679 const QEMUOption *popt;
8681 optind++;
8682 /* Treat --foo the same as -foo. */
8683 if (r[1] == '-')
8684 r++;
8685 popt = qemu_options;
8686 for(;;) {
8687 if (!popt->name) {
8688 fprintf(stderr, "%s: invalid option -- '%s'\n",
8689 argv[0], r);
8690 exit(1);
8692 if (!strcmp(popt->name, r + 1))
8693 break;
8694 popt++;
8696 if (popt->flags & HAS_ARG) {
8697 if (optind >= argc) {
8698 fprintf(stderr, "%s: option '%s' requires an argument\n",
8699 argv[0], r);
8700 exit(1);
8702 optarg = argv[optind++];
8703 } else {
8704 optarg = NULL;
8707 switch(popt->index) {
8708 case QEMU_OPTION_M:
8709 machine = find_machine(optarg);
8710 if (!machine) {
8711 QEMUMachine *m;
8712 printf("Supported machines are:\n");
8713 for(m = first_machine; m != NULL; m = m->next) {
8714 printf("%-10s %s%s\n",
8715 m->name, m->desc,
8716 m == first_machine ? " (default)" : "");
8718 exit(*optarg != '?');
8720 break;
8721 case QEMU_OPTION_cpu:
8722 /* hw initialization will check this */
8723 if (*optarg == '?') {
8724 /* XXX: implement xxx_cpu_list for targets that still miss it */
8725 #if defined(cpu_list)
8726 cpu_list(stdout, &fprintf);
8727 #endif
8728 exit(0);
8729 } else {
8730 cpu_model = optarg;
8732 break;
8733 case QEMU_OPTION_initrd:
8734 initrd_filename = optarg;
8735 break;
8736 case QEMU_OPTION_hda:
8737 if (cyls == 0)
8738 hda_index = drive_add(optarg, HD_ALIAS, 0);
8739 else
8740 hda_index = drive_add(optarg, HD_ALIAS
8741 ",cyls=%d,heads=%d,secs=%d%s",
8742 0, cyls, heads, secs,
8743 translation == BIOS_ATA_TRANSLATION_LBA ?
8744 ",trans=lba" :
8745 translation == BIOS_ATA_TRANSLATION_NONE ?
8746 ",trans=none" : "");
8747 break;
8748 case QEMU_OPTION_hdb:
8749 case QEMU_OPTION_hdc:
8750 case QEMU_OPTION_hdd:
8751 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8752 break;
8753 case QEMU_OPTION_drive:
8754 drive_add(NULL, "%s", optarg);
8755 break;
8756 case QEMU_OPTION_mtdblock:
8757 drive_add(optarg, MTD_ALIAS);
8758 break;
8759 case QEMU_OPTION_sd:
8760 drive_add(optarg, SD_ALIAS);
8761 break;
8762 case QEMU_OPTION_pflash:
8763 drive_add(optarg, PFLASH_ALIAS);
8764 break;
8765 case QEMU_OPTION_snapshot:
8766 snapshot = 1;
8767 break;
8768 case QEMU_OPTION_hdachs:
8770 const char *p;
8771 p = optarg;
8772 cyls = strtol(p, (char **)&p, 0);
8773 if (cyls < 1 || cyls > 16383)
8774 goto chs_fail;
8775 if (*p != ',')
8776 goto chs_fail;
8777 p++;
8778 heads = strtol(p, (char **)&p, 0);
8779 if (heads < 1 || heads > 16)
8780 goto chs_fail;
8781 if (*p != ',')
8782 goto chs_fail;
8783 p++;
8784 secs = strtol(p, (char **)&p, 0);
8785 if (secs < 1 || secs > 63)
8786 goto chs_fail;
8787 if (*p == ',') {
8788 p++;
8789 if (!strcmp(p, "none"))
8790 translation = BIOS_ATA_TRANSLATION_NONE;
8791 else if (!strcmp(p, "lba"))
8792 translation = BIOS_ATA_TRANSLATION_LBA;
8793 else if (!strcmp(p, "auto"))
8794 translation = BIOS_ATA_TRANSLATION_AUTO;
8795 else
8796 goto chs_fail;
8797 } else if (*p != '\0') {
8798 chs_fail:
8799 fprintf(stderr, "qemu: invalid physical CHS format\n");
8800 exit(1);
8802 if (hda_index != -1)
8803 snprintf(drives_opt[hda_index].opt,
8804 sizeof(drives_opt[hda_index].opt),
8805 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8806 0, cyls, heads, secs,
8807 translation == BIOS_ATA_TRANSLATION_LBA ?
8808 ",trans=lba" :
8809 translation == BIOS_ATA_TRANSLATION_NONE ?
8810 ",trans=none" : "");
8812 break;
8813 case QEMU_OPTION_nographic:
8814 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8815 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8816 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8817 nographic = 1;
8818 break;
8819 case QEMU_OPTION_portrait:
8820 graphic_rotate = 1;
8821 break;
8822 case QEMU_OPTION_kernel:
8823 kernel_filename = optarg;
8824 break;
8825 case QEMU_OPTION_append:
8826 kernel_cmdline = optarg;
8827 break;
8828 case QEMU_OPTION_cdrom:
8829 drive_add(optarg, CDROM_ALIAS);
8830 break;
8831 case QEMU_OPTION_boot:
8832 boot_devices = optarg;
8833 /* We just do some generic consistency checks */
8835 /* Could easily be extended to 64 devices if needed */
8836 const char *p;
8838 boot_devices_bitmap = 0;
8839 for (p = boot_devices; *p != '\0'; p++) {
8840 /* Allowed boot devices are:
8841 * a b : floppy disk drives
8842 * c ... f : IDE disk drives
8843 * g ... m : machine implementation dependant drives
8844 * n ... p : network devices
8845 * It's up to each machine implementation to check
8846 * if the given boot devices match the actual hardware
8847 * implementation and firmware features.
8849 if (*p < 'a' || *p > 'q') {
8850 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8851 exit(1);
8853 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8854 fprintf(stderr,
8855 "Boot device '%c' was given twice\n",*p);
8856 exit(1);
8858 boot_devices_bitmap |= 1 << (*p - 'a');
8861 break;
8862 case QEMU_OPTION_fda:
8863 case QEMU_OPTION_fdb:
8864 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8865 break;
8866 #ifdef TARGET_I386
8867 case QEMU_OPTION_no_fd_bootchk:
8868 fd_bootchk = 0;
8869 break;
8870 #endif
8871 case QEMU_OPTION_no_code_copy:
8872 code_copy_enabled = 0;
8873 break;
8874 case QEMU_OPTION_net:
8875 if (nb_net_clients >= MAX_NET_CLIENTS) {
8876 fprintf(stderr, "qemu: too many network clients\n");
8877 exit(1);
8879 pstrcpy(net_clients[nb_net_clients],
8880 sizeof(net_clients[0]),
8881 optarg);
8882 nb_net_clients++;
8883 break;
8884 #ifdef CONFIG_SLIRP
8885 case QEMU_OPTION_tftp:
8886 tftp_prefix = optarg;
8887 break;
8888 case QEMU_OPTION_bootp:
8889 bootp_filename = optarg;
8890 break;
8891 #ifndef _WIN32
8892 case QEMU_OPTION_smb:
8893 net_slirp_smb(optarg);
8894 break;
8895 #endif
8896 case QEMU_OPTION_redir:
8897 net_slirp_redir(optarg);
8898 break;
8899 #endif
8900 #ifdef HAS_AUDIO
8901 case QEMU_OPTION_audio_help:
8902 AUD_help ();
8903 exit (0);
8904 break;
8905 case QEMU_OPTION_soundhw:
8906 select_soundhw (optarg);
8907 break;
8908 #endif
8909 case QEMU_OPTION_h:
8910 help(0);
8911 break;
8912 case QEMU_OPTION_m:
8913 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
8914 if (ram_size <= 0)
8915 help(1);
8916 if (ram_size > PHYS_RAM_MAX_SIZE) {
8917 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8918 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8919 exit(1);
8921 break;
8922 case QEMU_OPTION_d:
8924 int mask;
8925 CPULogItem *item;
8927 mask = cpu_str_to_log_mask(optarg);
8928 if (!mask) {
8929 printf("Log items (comma separated):\n");
8930 for(item = cpu_log_items; item->mask != 0; item++) {
8931 printf("%-10s %s\n", item->name, item->help);
8933 exit(1);
8935 cpu_set_log(mask);
8937 break;
8938 #ifdef CONFIG_GDBSTUB
8939 case QEMU_OPTION_s:
8940 use_gdbstub = 1;
8941 break;
8942 case QEMU_OPTION_p:
8943 gdbstub_port = optarg;
8944 break;
8945 #endif
8946 case QEMU_OPTION_L:
8947 bios_dir = optarg;
8948 break;
8949 case QEMU_OPTION_bios:
8950 bios_name = optarg;
8951 break;
8952 case QEMU_OPTION_S:
8953 autostart = 0;
8954 break;
8955 case QEMU_OPTION_k:
8956 keyboard_layout = optarg;
8957 break;
8958 case QEMU_OPTION_localtime:
8959 rtc_utc = 0;
8960 break;
8961 case QEMU_OPTION_cirrusvga:
8962 cirrus_vga_enabled = 1;
8963 vmsvga_enabled = 0;
8964 break;
8965 case QEMU_OPTION_vmsvga:
8966 cirrus_vga_enabled = 0;
8967 vmsvga_enabled = 1;
8968 break;
8969 case QEMU_OPTION_std_vga:
8970 cirrus_vga_enabled = 0;
8971 vmsvga_enabled = 0;
8972 break;
8973 case QEMU_OPTION_g:
8975 const char *p;
8976 int w, h, depth;
8977 p = optarg;
8978 w = strtol(p, (char **)&p, 10);
8979 if (w <= 0) {
8980 graphic_error:
8981 fprintf(stderr, "qemu: invalid resolution or depth\n");
8982 exit(1);
8984 if (*p != 'x')
8985 goto graphic_error;
8986 p++;
8987 h = strtol(p, (char **)&p, 10);
8988 if (h <= 0)
8989 goto graphic_error;
8990 if (*p == 'x') {
8991 p++;
8992 depth = strtol(p, (char **)&p, 10);
8993 if (depth != 8 && depth != 15 && depth != 16 &&
8994 depth != 24 && depth != 32)
8995 goto graphic_error;
8996 } else if (*p == '\0') {
8997 depth = graphic_depth;
8998 } else {
8999 goto graphic_error;
9002 graphic_width = w;
9003 graphic_height = h;
9004 graphic_depth = depth;
9006 break;
9007 case QEMU_OPTION_echr:
9009 char *r;
9010 term_escape_char = strtol(optarg, &r, 0);
9011 if (r == optarg)
9012 printf("Bad argument to echr\n");
9013 break;
9015 case QEMU_OPTION_monitor:
9016 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9017 break;
9018 case QEMU_OPTION_balloon:
9019 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9020 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9021 exit(1);
9023 if (balloon_used) {
9024 fprintf(stderr, "qemu: only one balloon device can be used\n");
9025 exit(1);
9027 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9028 vmchannel_device_index++;
9029 balloon_used = 1;
9030 break;
9031 case QEMU_OPTION_vmchannel:
9032 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9033 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9034 exit(1);
9036 pstrcpy(vmchannel_devices[vmchannel_device_index],
9037 sizeof(vmchannel_devices[0]), optarg);
9038 vmchannel_device_index++;
9039 break;
9040 case QEMU_OPTION_serial:
9041 if (serial_device_index >= MAX_SERIAL_PORTS) {
9042 fprintf(stderr, "qemu: too many serial ports\n");
9043 exit(1);
9045 pstrcpy(serial_devices[serial_device_index],
9046 sizeof(serial_devices[0]), optarg);
9047 serial_device_index++;
9048 break;
9049 case QEMU_OPTION_parallel:
9050 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9051 fprintf(stderr, "qemu: too many parallel ports\n");
9052 exit(1);
9054 pstrcpy(parallel_devices[parallel_device_index],
9055 sizeof(parallel_devices[0]), optarg);
9056 parallel_device_index++;
9057 break;
9058 case QEMU_OPTION_loadvm:
9059 loadvm = optarg;
9060 break;
9061 case QEMU_OPTION_incoming:
9062 incoming = optarg;
9063 break;
9064 case QEMU_OPTION_full_screen:
9065 full_screen = 1;
9066 break;
9067 #ifdef CONFIG_SDL
9068 case QEMU_OPTION_no_frame:
9069 no_frame = 1;
9070 break;
9071 case QEMU_OPTION_alt_grab:
9072 alt_grab = 1;
9073 break;
9074 case QEMU_OPTION_no_quit:
9075 no_quit = 1;
9076 break;
9077 #endif
9078 case QEMU_OPTION_pidfile:
9079 pid_file = optarg;
9080 break;
9081 #ifdef TARGET_I386
9082 case QEMU_OPTION_win2k_hack:
9083 win2k_install_hack = 1;
9084 break;
9085 #endif
9086 #ifdef USE_KQEMU
9087 case QEMU_OPTION_no_kqemu:
9088 kqemu_allowed = 0;
9089 break;
9090 case QEMU_OPTION_kernel_kqemu:
9091 kqemu_allowed = 2;
9092 break;
9093 #endif
9094 #ifdef USE_KVM
9095 case QEMU_OPTION_no_kvm:
9096 kvm_allowed = 0;
9097 break;
9098 case QEMU_OPTION_no_kvm_irqchip: {
9099 extern int kvm_irqchip;
9100 kvm_irqchip = 0;
9101 break;
9103 #endif
9104 case QEMU_OPTION_usb:
9105 usb_enabled = 1;
9106 break;
9107 case QEMU_OPTION_usbdevice:
9108 usb_enabled = 1;
9109 if (usb_devices_index >= MAX_USB_CMDLINE) {
9110 fprintf(stderr, "Too many USB devices\n");
9111 exit(1);
9113 pstrcpy(usb_devices[usb_devices_index],
9114 sizeof(usb_devices[usb_devices_index]),
9115 optarg);
9116 usb_devices_index++;
9117 break;
9118 case QEMU_OPTION_smp:
9119 smp_cpus = atoi(optarg);
9120 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9121 fprintf(stderr, "Invalid number of CPUs\n");
9122 exit(1);
9124 break;
9125 case QEMU_OPTION_vnc:
9126 vnc_display = optarg;
9127 break;
9128 case QEMU_OPTION_no_acpi:
9129 acpi_enabled = 0;
9130 break;
9131 case QEMU_OPTION_no_reboot:
9132 no_reboot = 1;
9133 break;
9134 case QEMU_OPTION_show_cursor:
9135 cursor_hide = 0;
9136 break;
9137 case QEMU_OPTION_daemonize:
9138 daemonize = 1;
9139 break;
9140 case QEMU_OPTION_option_rom:
9141 if (nb_option_roms >= MAX_OPTION_ROMS) {
9142 fprintf(stderr, "Too many option ROMs\n");
9143 exit(1);
9145 option_rom[nb_option_roms] = optarg;
9146 nb_option_roms++;
9147 break;
9148 case QEMU_OPTION_semihosting:
9149 semihosting_enabled = 1;
9150 break;
9151 case QEMU_OPTION_tdf:
9152 time_drift_fix = 1;
9153 break;
9154 case QEMU_OPTION_kvm_shadow_memory:
9155 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9156 break;
9157 case QEMU_OPTION_name:
9158 qemu_name = optarg;
9159 break;
9160 #ifdef TARGET_SPARC
9161 case QEMU_OPTION_prom_env:
9162 if (nb_prom_envs >= MAX_PROM_ENVS) {
9163 fprintf(stderr, "Too many prom variables\n");
9164 exit(1);
9166 prom_envs[nb_prom_envs] = optarg;
9167 nb_prom_envs++;
9168 break;
9169 #endif
9170 case QEMU_OPTION_cpu_vendor:
9171 cpu_vendor_string = optarg;
9172 break;
9173 #ifdef TARGET_ARM
9174 case QEMU_OPTION_old_param:
9175 old_param = 1;
9176 break;
9177 #endif
9178 case QEMU_OPTION_clock:
9179 configure_alarms(optarg);
9180 break;
9181 case QEMU_OPTION_startdate:
9183 struct tm tm;
9184 if (!strcmp(optarg, "now")) {
9185 rtc_start_date = -1;
9186 } else {
9187 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9188 &tm.tm_year,
9189 &tm.tm_mon,
9190 &tm.tm_mday,
9191 &tm.tm_hour,
9192 &tm.tm_min,
9193 &tm.tm_sec) == 6) {
9194 /* OK */
9195 } else if (sscanf(optarg, "%d-%d-%d",
9196 &tm.tm_year,
9197 &tm.tm_mon,
9198 &tm.tm_mday) == 3) {
9199 tm.tm_hour = 0;
9200 tm.tm_min = 0;
9201 tm.tm_sec = 0;
9202 } else {
9203 goto date_fail;
9205 tm.tm_year -= 1900;
9206 tm.tm_mon--;
9207 rtc_start_date = mktimegm(&tm);
9208 if (rtc_start_date == -1) {
9209 date_fail:
9210 fprintf(stderr, "Invalid date format. Valid format are:\n"
9211 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9212 exit(1);
9216 break;
9217 case QEMU_OPTION_translation:
9219 int mask;
9220 CPUTranslationSetting *setting;
9222 mask = cpu_str_to_translation_mask(optarg);
9223 if (!mask) {
9224 printf("Translation settings (comma separated):\n");
9225 for(setting = cpu_translation_settings; setting->mask != 0; setting++) {
9226 printf("%-10s %s\n", setting->name, setting->help);
9228 exit(1);
9230 cpu_set_translation_settings(mask);
9232 break;
9237 #ifndef _WIN32
9238 if (daemonize) {
9239 pid_t pid;
9241 if (pipe(fds) == -1)
9242 exit(1);
9244 pid = fork();
9245 if (pid > 0) {
9246 uint8_t status;
9247 ssize_t len;
9249 close(fds[1]);
9251 again:
9252 len = read(fds[0], &status, 1);
9253 if (len == -1 && (errno == EINTR))
9254 goto again;
9256 if (len != 1)
9257 exit(1);
9258 else if (status == 1) {
9259 fprintf(stderr, "Could not acquire pidfile\n");
9260 exit(1);
9261 } else
9262 exit(0);
9263 } else if (pid < 0)
9264 exit(1);
9266 setsid();
9268 pid = fork();
9269 if (pid > 0)
9270 exit(0);
9271 else if (pid < 0)
9272 exit(1);
9274 umask(027);
9276 signal(SIGTSTP, SIG_IGN);
9277 signal(SIGTTOU, SIG_IGN);
9278 signal(SIGTTIN, SIG_IGN);
9280 #endif
9282 #if USE_KVM
9283 if (kvm_enabled()) {
9284 if (kvm_qemu_init() < 0) {
9285 extern int kvm_allowed;
9286 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9287 kvm_allowed = 0;
9290 #endif
9292 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9293 if (daemonize) {
9294 uint8_t status = 1;
9295 write(fds[1], &status, 1);
9296 } else
9297 fprintf(stderr, "Could not acquire pid file\n");
9298 exit(1);
9301 #ifdef USE_KQEMU
9302 if (smp_cpus > 1)
9303 kqemu_allowed = 0;
9304 #endif
9305 linux_boot = (kernel_filename != NULL);
9306 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9308 /* XXX: this should not be: some embedded targets just have flash */
9309 if (!linux_boot && net_boot == 0 &&
9310 nb_drives_opt == 0)
9311 help(1);
9313 /* boot to floppy or the default cd if no hard disk defined yet */
9314 if (!boot_devices[0]) {
9315 boot_devices = "cad";
9317 setvbuf(stdout, NULL, _IOLBF, 0);
9319 init_timers();
9320 init_timer_alarm();
9321 qemu_aio_init();
9323 #ifdef _WIN32
9324 socket_init();
9325 #endif
9327 /* init network clients */
9328 if (nb_net_clients == 0) {
9329 /* if no clients, we use a default config */
9330 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9331 "nic");
9332 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9333 "user");
9334 nb_net_clients = 2;
9337 for(i = 0;i < nb_net_clients; i++) {
9338 if (net_client_init(net_clients[i]) < 0)
9339 exit(1);
9341 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9342 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9343 continue;
9344 if (vlan->nb_guest_devs == 0) {
9345 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9346 exit(1);
9348 if (vlan->nb_host_devs == 0)
9349 fprintf(stderr,
9350 "Warning: vlan %d is not connected to host network\n",
9351 vlan->id);
9354 #ifdef TARGET_I386
9355 /* XXX: this should be moved in the PC machine instantiation code */
9356 if (net_boot != 0) {
9357 int netroms = 0;
9358 for (i = 0; i < nb_nics && i < 4; i++) {
9359 const char *model = nd_table[i].model;
9360 char buf[1024];
9361 if (net_boot & (1 << i)) {
9362 if (model == NULL)
9363 model = "rtl8139";
9364 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9365 if (get_image_size(buf) > 0) {
9366 if (nb_option_roms >= MAX_OPTION_ROMS) {
9367 fprintf(stderr, "Too many option ROMs\n");
9368 exit(1);
9370 option_rom[nb_option_roms] = strdup(buf);
9371 nb_option_roms++;
9372 netroms++;
9376 if (netroms == 0) {
9377 fprintf(stderr, "No valid PXE rom found for network device\n");
9378 exit(1);
9381 #endif
9383 /* init the memory */
9384 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9386 /* Initialize kvm */
9387 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9388 #define KVM_EXTRA_PAGES 3
9389 #else
9390 #define KVM_EXTRA_PAGES 0
9391 #endif
9392 if (kvm_enabled()) {
9393 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9394 if (kvm_qemu_create_context() < 0) {
9395 fprintf(stderr, "Could not create KVM context\n");
9396 exit(1);
9398 #ifdef KVM_CAP_USER_MEMORY
9400 int ret;
9402 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9403 if (ret) {
9404 phys_ram_base = qemu_vmalloc(phys_ram_size);
9405 if (!phys_ram_base) {
9406 fprintf(stderr, "Could not allocate physical memory\n");
9407 exit(1);
9411 #endif
9412 } else {
9413 phys_ram_base = qemu_vmalloc(phys_ram_size);
9414 if (!phys_ram_base) {
9415 fprintf(stderr, "Could not allocate physical memory\n");
9416 exit(1);
9420 bdrv_init();
9422 /* we always create the cdrom drive, even if no disk is there */
9424 if (nb_drives_opt < MAX_DRIVES)
9425 drive_add(NULL, CDROM_ALIAS);
9427 /* we always create at least one floppy */
9429 if (nb_drives_opt < MAX_DRIVES)
9430 drive_add(NULL, FD_ALIAS, 0);
9432 /* we always create one sd slot, even if no card is in it */
9434 if (nb_drives_opt < MAX_DRIVES)
9435 drive_add(NULL, SD_ALIAS);
9437 /* open the virtual block devices */
9439 for(i = 0; i < nb_drives_opt; i++)
9440 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9441 exit(1);
9443 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9444 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9446 init_ioports();
9448 /* terminal init */
9449 memset(&display_state, 0, sizeof(display_state));
9450 if (nographic) {
9451 /* nearly nothing to do */
9452 dumb_display_init(ds);
9453 } else if (vnc_display != NULL) {
9454 vnc_display_init(ds);
9455 if (vnc_display_open(ds, vnc_display) < 0)
9456 exit(1);
9457 } else {
9458 #if defined(CONFIG_SDL)
9459 sdl_display_init(ds, full_screen, no_frame);
9460 #elif defined(CONFIG_COCOA)
9461 cocoa_display_init(ds, full_screen);
9462 #else
9463 dumb_display_init(ds);
9464 #endif
9467 /* Maintain compatibility with multiple stdio monitors */
9468 if (!strcmp(monitor_device,"stdio")) {
9469 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9470 if (!strcmp(serial_devices[i],"mon:stdio")) {
9471 monitor_device[0] = '\0';
9472 break;
9473 } else if (!strcmp(serial_devices[i],"stdio")) {
9474 monitor_device[0] = '\0';
9475 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9476 break;
9480 if (monitor_device[0] != '\0') {
9481 monitor_hd = qemu_chr_open(monitor_device);
9482 if (!monitor_hd) {
9483 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9484 exit(1);
9486 monitor_init(monitor_hd, !nographic);
9489 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9490 const char *devname = vmchannel_devices[i];
9491 if (devname[0] != '\0' && strcmp(devname, "none")) {
9492 int devid;
9493 char *termn;
9495 if (strstart(devname, "di:", &devname)) {
9496 devid = strtol(devname, &termn, 16);
9497 devname = termn + 1;
9499 else {
9500 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9501 devname);
9502 exit(1);
9504 vmchannel_hds[i] = qemu_chr_open(devname);
9505 if (!vmchannel_hds[i]) {
9506 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9507 devname);
9508 exit(1);
9510 vmchannel_init(vmchannel_hds[i], devid, i);
9514 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9515 const char *devname = serial_devices[i];
9516 if (devname[0] != '\0' && strcmp(devname, "none")) {
9517 serial_hds[i] = qemu_chr_open(devname);
9518 if (!serial_hds[i]) {
9519 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9520 devname);
9521 exit(1);
9523 if (strstart(devname, "vc", 0))
9524 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9528 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9529 const char *devname = parallel_devices[i];
9530 if (devname[0] != '\0' && strcmp(devname, "none")) {
9531 parallel_hds[i] = qemu_chr_open(devname);
9532 if (!parallel_hds[i]) {
9533 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9534 devname);
9535 exit(1);
9537 if (strstart(devname, "vc", 0))
9538 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9542 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9543 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9545 /* init USB devices */
9546 if (usb_enabled) {
9547 for(i = 0; i < usb_devices_index; i++) {
9548 if (usb_device_add(usb_devices[i]) < 0) {
9549 fprintf(stderr, "Warning: could not add USB device %s\n",
9550 usb_devices[i]);
9555 if (display_state.dpy_refresh) {
9556 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9557 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9560 if (kvm_enabled())
9561 kvm_init_ap();
9563 #ifdef CONFIG_GDBSTUB
9564 if (use_gdbstub) {
9565 /* XXX: use standard host:port notation and modify options
9566 accordingly. */
9567 if (gdbserver_start(gdbstub_port) < 0) {
9568 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9569 gdbstub_port);
9570 exit(1);
9573 #endif
9574 if (loadvm)
9575 do_loadvm(loadvm);
9577 if (incoming) {
9578 int rc;
9580 rc = migrate_incoming(incoming);
9581 if (rc != 0) {
9582 fprintf(stderr, "Migration failed rc=%d\n", rc);
9583 exit(rc);
9588 /* XXX: simplify init */
9589 read_passwords();
9590 if (autostart) {
9591 vm_start();
9595 if (daemonize) {
9596 uint8_t status = 0;
9597 ssize_t len;
9598 int fd;
9600 again1:
9601 len = write(fds[1], &status, 1);
9602 if (len == -1 && (errno == EINTR))
9603 goto again1;
9605 if (len != 1)
9606 exit(1);
9608 chdir("/");
9609 TFR(fd = open("/dev/null", O_RDWR));
9610 if (fd == -1)
9611 exit(1);
9613 dup2(fd, 0);
9614 dup2(fd, 1);
9615 dup2(fd, 2);
9617 close(fd);
9620 main_loop();
9621 quit_timers();
9623 #if !defined(_WIN32)
9624 /* close network clients */
9625 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9626 VLANClientState *vc;
9628 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9629 if (vc->fd_read == tap_receive) {
9630 char ifname[64];
9631 TAPState *s = vc->opaque;
9633 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9634 s->down_script[0])
9635 launch_script(s->down_script, ifname, s->fd);
9639 #endif
9640 return 0;