kvm: bios: notify _EJ0 through _SEJ OperationRegion
[qemu-kvm/fedora.git] / vl.c
blob74183627f658230e537f0acc0d144b45e0a3de51
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 int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 int64_t ram_size;
188 int pit_min_timer_count = 0;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int cirrus_vga_enabled = 1;
195 int vmsvga_enabled = 0;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 int full_screen = 0;
206 int no_frame = 0;
207 int no_quit = 0;
208 int balloon_used = 0;
209 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 static VLANState *first_vlan;
217 int smp_cpus = 1;
218 const char *vnc_display;
219 #if defined(TARGET_SPARC)
220 #define MAX_CPUS 16
221 #elif defined(TARGET_I386)
222 #define MAX_CPUS 255
223 #elif defined(TARGET_IA64)
224 #define MAX_CPUS 4
225 #else
226 #define MAX_CPUS 1
227 #endif
228 int acpi_enabled = 1;
229 int fd_bootchk = 1;
230 int no_reboot = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 int daemonize = 0;
234 const char *incoming;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 int autostart = 1;
239 int time_drift_fix = 0;
240 unsigned int kvm_shadow_memory = 0;
241 const char *mem_path = NULL;
242 int hpagesize = 0;
243 const char *cpu_vendor_string;
244 #ifdef TARGET_ARM
245 int old_param = 0;
246 #endif
247 const char *qemu_name;
248 int alt_grab = 0;
249 #ifdef TARGET_SPARC
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int nb_drives_opt;
254 struct drive_opt drives_opt[MAX_DRIVES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int event_pending = 1;
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 void decorate_application_name(char *appname, int max_len)
264 if (kvm_enabled())
266 int remain = max_len - strlen(appname) - 1;
268 if (remain > 0)
269 strncat(appname, "/KVM", remain);
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
277 PicState2 *isa_pic;
279 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
281 #ifdef DEBUG_UNUSED_IOPORT
282 fprintf(stderr, "unused inb: port=0x%04x\n", address);
283 #endif
284 return 0xff;
287 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
289 #ifdef DEBUG_UNUSED_IOPORT
290 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
291 #endif
294 /* default is to make two byte accesses */
295 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
297 uint32_t data;
298 data = ioport_read_table[0][address](ioport_opaque[address], address);
299 address = (address + 1) & (MAX_IOPORTS - 1);
300 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
301 return data;
304 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
306 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
307 address = (address + 1) & (MAX_IOPORTS - 1);
308 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
311 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
313 #ifdef DEBUG_UNUSED_IOPORT
314 fprintf(stderr, "unused inl: port=0x%04x\n", address);
315 #endif
316 return 0xffffffff;
319 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
323 #endif
326 static void init_ioports(void)
328 int i;
330 for(i = 0; i < MAX_IOPORTS; i++) {
331 ioport_read_table[0][i] = default_ioport_readb;
332 ioport_write_table[0][i] = default_ioport_writeb;
333 ioport_read_table[1][i] = default_ioport_readw;
334 ioport_write_table[1][i] = default_ioport_writew;
335 ioport_read_table[2][i] = default_ioport_readl;
336 ioport_write_table[2][i] = default_ioport_writel;
340 /* size is the word size in byte */
341 int register_ioport_read(int start, int length, int size,
342 IOPortReadFunc *func, void *opaque)
344 int i, bsize;
346 if (size == 1) {
347 bsize = 0;
348 } else if (size == 2) {
349 bsize = 1;
350 } else if (size == 4) {
351 bsize = 2;
352 } else {
353 hw_error("register_ioport_read: invalid size");
354 return -1;
356 for(i = start; i < start + length; i += size) {
357 ioport_read_table[bsize][i] = func;
358 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
359 hw_error("register_ioport_read: invalid opaque");
360 ioport_opaque[i] = opaque;
362 return 0;
365 /* size is the word size in byte */
366 int register_ioport_write(int start, int length, int size,
367 IOPortWriteFunc *func, void *opaque)
369 int i, bsize;
371 if (size == 1) {
372 bsize = 0;
373 } else if (size == 2) {
374 bsize = 1;
375 } else if (size == 4) {
376 bsize = 2;
377 } else {
378 hw_error("register_ioport_write: invalid size");
379 return -1;
381 for(i = start; i < start + length; i += size) {
382 ioport_write_table[bsize][i] = func;
383 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
384 hw_error("register_ioport_write: invalid opaque");
385 ioport_opaque[i] = opaque;
387 return 0;
390 void isa_unassign_ioport(int start, int length)
392 int i;
394 for(i = start; i < start + length; i++) {
395 ioport_read_table[0][i] = default_ioport_readb;
396 ioport_read_table[1][i] = default_ioport_readw;
397 ioport_read_table[2][i] = default_ioport_readl;
399 ioport_write_table[0][i] = default_ioport_writeb;
400 ioport_write_table[1][i] = default_ioport_writew;
401 ioport_write_table[2][i] = default_ioport_writel;
405 /***********************************************************/
407 void cpu_outb(CPUState *env, int addr, int val)
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "outb: %04x %02x\n", addr, val);
412 #endif
413 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
420 void cpu_outw(CPUState *env, int addr, int val)
422 #ifdef DEBUG_IOPORT
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "outw: %04x %04x\n", addr, val);
425 #endif
426 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
433 void cpu_outl(CPUState *env, int addr, int val)
435 #ifdef DEBUG_IOPORT
436 if (loglevel & CPU_LOG_IOPORT)
437 fprintf(logfile, "outl: %04x %08x\n", addr, val);
438 #endif
439 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
440 #ifdef USE_KQEMU
441 if (env)
442 env->last_io_time = cpu_get_time_fast();
443 #endif
446 int cpu_inb(CPUState *env, int addr)
448 int val;
449 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
450 #ifdef DEBUG_IOPORT
451 if (loglevel & CPU_LOG_IOPORT)
452 fprintf(logfile, "inb : %04x %02x\n", addr, val);
453 #endif
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
458 return val;
461 int cpu_inw(CPUState *env, int addr)
463 int val;
464 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
465 #ifdef DEBUG_IOPORT
466 if (loglevel & CPU_LOG_IOPORT)
467 fprintf(logfile, "inw : %04x %04x\n", addr, val);
468 #endif
469 #ifdef USE_KQEMU
470 if (env)
471 env->last_io_time = cpu_get_time_fast();
472 #endif
473 return val;
476 int cpu_inl(CPUState *env, int addr)
478 int val;
479 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
480 #ifdef DEBUG_IOPORT
481 if (loglevel & CPU_LOG_IOPORT)
482 fprintf(logfile, "inl : %04x %08x\n", addr, val);
483 #endif
484 #ifdef USE_KQEMU
485 if (env)
486 env->last_io_time = cpu_get_time_fast();
487 #endif
488 return val;
491 /***********************************************************/
492 void hw_error(const char *fmt, ...)
494 va_list ap;
495 CPUState *env;
497 va_start(ap, fmt);
498 fprintf(stderr, "qemu: hardware error: ");
499 vfprintf(stderr, fmt, ap);
500 fprintf(stderr, "\n");
501 for(env = first_cpu; env != NULL; env = env->next_cpu) {
502 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
503 #ifdef TARGET_I386
504 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
505 #else
506 cpu_dump_state(env, stderr, fprintf, 0);
507 #endif
509 va_end(ap);
510 abort();
513 /***********************************************************/
514 /* keyboard/mouse */
516 static QEMUPutKBDEvent *qemu_put_kbd_event;
517 static void *qemu_put_kbd_event_opaque;
518 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
519 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
521 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
523 qemu_put_kbd_event_opaque = opaque;
524 qemu_put_kbd_event = func;
527 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
528 void *opaque, int absolute,
529 const char *name)
531 QEMUPutMouseEntry *s, *cursor;
533 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
534 if (!s)
535 return NULL;
537 s->qemu_put_mouse_event = func;
538 s->qemu_put_mouse_event_opaque = opaque;
539 s->qemu_put_mouse_event_absolute = absolute;
540 s->qemu_put_mouse_event_name = qemu_strdup(name);
541 s->next = NULL;
543 if (!qemu_put_mouse_event_head) {
544 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
545 return s;
548 cursor = qemu_put_mouse_event_head;
549 while (cursor->next != NULL)
550 cursor = cursor->next;
552 cursor->next = s;
553 qemu_put_mouse_event_current = s;
555 return s;
558 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
560 QEMUPutMouseEntry *prev = NULL, *cursor;
562 if (!qemu_put_mouse_event_head || entry == NULL)
563 return;
565 cursor = qemu_put_mouse_event_head;
566 while (cursor != NULL && cursor != entry) {
567 prev = cursor;
568 cursor = cursor->next;
571 if (cursor == NULL) // does not exist or list empty
572 return;
573 else if (prev == NULL) { // entry is head
574 qemu_put_mouse_event_head = cursor->next;
575 if (qemu_put_mouse_event_current == entry)
576 qemu_put_mouse_event_current = cursor->next;
577 qemu_free(entry->qemu_put_mouse_event_name);
578 qemu_free(entry);
579 return;
582 prev->next = entry->next;
584 if (qemu_put_mouse_event_current == entry)
585 qemu_put_mouse_event_current = prev;
587 qemu_free(entry->qemu_put_mouse_event_name);
588 qemu_free(entry);
591 void kbd_put_keycode(int keycode)
593 if (qemu_put_kbd_event) {
594 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
598 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
600 QEMUPutMouseEvent *mouse_event;
601 void *mouse_event_opaque;
602 int width;
604 if (!qemu_put_mouse_event_current) {
605 return;
608 mouse_event =
609 qemu_put_mouse_event_current->qemu_put_mouse_event;
610 mouse_event_opaque =
611 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
613 if (mouse_event) {
614 if (graphic_rotate) {
615 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
616 width = 0x7fff;
617 else
618 width = graphic_width;
619 mouse_event(mouse_event_opaque,
620 width - dy, dx, dz, buttons_state);
621 } else
622 mouse_event(mouse_event_opaque,
623 dx, dy, dz, buttons_state);
627 int kbd_mouse_is_absolute(void)
629 if (!qemu_put_mouse_event_current)
630 return 0;
632 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
635 void do_info_mice(void)
637 QEMUPutMouseEntry *cursor;
638 int index = 0;
640 if (!qemu_put_mouse_event_head) {
641 term_printf("No mouse devices connected\n");
642 return;
645 term_printf("Mouse devices available:\n");
646 cursor = qemu_put_mouse_event_head;
647 while (cursor != NULL) {
648 term_printf("%c Mouse #%d: %s\n",
649 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
650 index, cursor->qemu_put_mouse_event_name);
651 index++;
652 cursor = cursor->next;
656 void do_mouse_set(int index)
658 QEMUPutMouseEntry *cursor;
659 int i = 0;
661 if (!qemu_put_mouse_event_head) {
662 term_printf("No mouse devices connected\n");
663 return;
666 cursor = qemu_put_mouse_event_head;
667 while (cursor != NULL && index != i) {
668 i++;
669 cursor = cursor->next;
672 if (cursor != NULL)
673 qemu_put_mouse_event_current = cursor;
674 else
675 term_printf("Mouse at given index not found\n");
678 /* compute with 96 bit intermediate result: (a*b)/c */
679 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
681 union {
682 uint64_t ll;
683 struct {
684 #ifdef WORDS_BIGENDIAN
685 uint32_t high, low;
686 #else
687 uint32_t low, high;
688 #endif
689 } l;
690 } u, res;
691 uint64_t rl, rh;
693 u.ll = a;
694 rl = (uint64_t)u.l.low * (uint64_t)b;
695 rh = (uint64_t)u.l.high * (uint64_t)b;
696 rh += (rl >> 32);
697 res.l.high = rh / c;
698 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
699 return res.ll;
702 /***********************************************************/
703 /* real time host monotonic timer */
705 #define QEMU_TIMER_BASE 1000000000LL
707 #ifdef WIN32
709 static int64_t clock_freq;
711 static void init_get_clock(void)
713 LARGE_INTEGER freq;
714 int ret;
715 ret = QueryPerformanceFrequency(&freq);
716 if (ret == 0) {
717 fprintf(stderr, "Could not calibrate ticks\n");
718 exit(1);
720 clock_freq = freq.QuadPart;
723 static int64_t get_clock(void)
725 LARGE_INTEGER ti;
726 QueryPerformanceCounter(&ti);
727 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
730 #else
732 static int use_rt_clock;
734 static void init_get_clock(void)
736 use_rt_clock = 0;
737 #if defined(__linux__)
739 struct timespec ts;
740 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
741 use_rt_clock = 1;
744 #endif
747 static int64_t get_clock(void)
749 #if defined(__linux__)
750 if (use_rt_clock) {
751 struct timespec ts;
752 clock_gettime(CLOCK_MONOTONIC, &ts);
753 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
754 } else
755 #endif
757 /* XXX: using gettimeofday leads to problems if the date
758 changes, so it should be avoided. */
759 struct timeval tv;
760 gettimeofday(&tv, NULL);
761 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
765 #endif
767 /***********************************************************/
768 /* guest cycle counter */
770 static int64_t cpu_ticks_prev;
771 static int64_t cpu_ticks_offset;
772 static int64_t cpu_clock_offset;
773 static int cpu_ticks_enabled;
775 /* return the host CPU cycle counter and handle stop/restart */
776 int64_t cpu_get_ticks(void)
778 if (!cpu_ticks_enabled) {
779 return cpu_ticks_offset;
780 } else {
781 int64_t ticks;
782 ticks = cpu_get_real_ticks();
783 if (cpu_ticks_prev > ticks) {
784 /* Note: non increasing ticks may happen if the host uses
785 software suspend */
786 cpu_ticks_offset += cpu_ticks_prev - ticks;
788 cpu_ticks_prev = ticks;
789 return ticks + cpu_ticks_offset;
793 /* return the host CPU monotonic timer and handle stop/restart */
794 static int64_t cpu_get_clock(void)
796 int64_t ti;
797 if (!cpu_ticks_enabled) {
798 return cpu_clock_offset;
799 } else {
800 ti = get_clock();
801 return ti + cpu_clock_offset;
805 /* enable cpu_get_ticks() */
806 void cpu_enable_ticks(void)
808 if (!cpu_ticks_enabled) {
809 cpu_ticks_offset -= cpu_get_real_ticks();
810 cpu_clock_offset -= get_clock();
811 cpu_ticks_enabled = 1;
815 /* disable cpu_get_ticks() : the clock is stopped. You must not call
816 cpu_get_ticks() after that. */
817 void cpu_disable_ticks(void)
819 if (cpu_ticks_enabled) {
820 cpu_ticks_offset = cpu_get_ticks();
821 cpu_clock_offset = cpu_get_clock();
822 cpu_ticks_enabled = 0;
826 /***********************************************************/
827 /* timers */
829 #define QEMU_TIMER_REALTIME 0
830 #define QEMU_TIMER_VIRTUAL 1
832 struct QEMUClock {
833 int type;
834 /* XXX: add frequency */
837 struct QEMUTimer {
838 QEMUClock *clock;
839 int64_t expire_time;
840 QEMUTimerCB *cb;
841 void *opaque;
842 struct QEMUTimer *next;
845 struct qemu_alarm_timer {
846 char const *name;
847 unsigned int flags;
849 int (*start)(struct qemu_alarm_timer *t);
850 void (*stop)(struct qemu_alarm_timer *t);
851 void (*rearm)(struct qemu_alarm_timer *t);
852 void *priv;
855 #define ALARM_FLAG_DYNTICKS 0x1
856 #define ALARM_FLAG_EXPIRED 0x2
858 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
860 return t->flags & ALARM_FLAG_DYNTICKS;
863 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
865 if (!alarm_has_dynticks(t))
866 return;
868 t->rearm(t);
871 /* TODO: MIN_TIMER_REARM_US should be optimized */
872 #define MIN_TIMER_REARM_US 250
874 static struct qemu_alarm_timer *alarm_timer;
876 #ifdef _WIN32
878 struct qemu_alarm_win32 {
879 MMRESULT timerId;
880 HANDLE host_alarm;
881 unsigned int period;
882 } alarm_win32_data = {0, NULL, -1};
884 static int win32_start_timer(struct qemu_alarm_timer *t);
885 static void win32_stop_timer(struct qemu_alarm_timer *t);
886 static void win32_rearm_timer(struct qemu_alarm_timer *t);
888 #else
890 static int unix_start_timer(struct qemu_alarm_timer *t);
891 static void unix_stop_timer(struct qemu_alarm_timer *t);
893 #ifdef __linux__
895 static int dynticks_start_timer(struct qemu_alarm_timer *t);
896 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
897 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
899 static int hpet_start_timer(struct qemu_alarm_timer *t);
900 static void hpet_stop_timer(struct qemu_alarm_timer *t);
902 static int rtc_start_timer(struct qemu_alarm_timer *t);
903 static void rtc_stop_timer(struct qemu_alarm_timer *t);
905 #endif /* __linux__ */
907 #endif /* _WIN32 */
909 static struct qemu_alarm_timer alarm_timers[] = {
910 #ifndef _WIN32
911 #ifdef __linux__
912 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
913 dynticks_stop_timer, dynticks_rearm_timer, NULL},
914 /* HPET - if available - is preferred */
915 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
916 /* ...otherwise try RTC */
917 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
918 #endif
919 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
920 #else
921 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
922 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
923 {"win32", 0, win32_start_timer,
924 win32_stop_timer, NULL, &alarm_win32_data},
925 #endif
926 {NULL, }
929 static void show_available_alarms()
931 int i;
933 printf("Available alarm timers, in order of precedence:\n");
934 for (i = 0; alarm_timers[i].name; i++)
935 printf("%s\n", alarm_timers[i].name);
938 static void configure_alarms(char const *opt)
940 int i;
941 int cur = 0;
942 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
943 char *arg;
944 char *name;
946 if (!strcmp(opt, "help")) {
947 show_available_alarms();
948 exit(0);
951 arg = strdup(opt);
953 /* Reorder the array */
954 name = strtok(arg, ",");
955 while (name) {
956 struct qemu_alarm_timer tmp;
958 for (i = 0; i < count && alarm_timers[i].name; i++) {
959 if (!strcmp(alarm_timers[i].name, name))
960 break;
963 if (i == count) {
964 fprintf(stderr, "Unknown clock %s\n", name);
965 goto next;
968 if (i < cur)
969 /* Ignore */
970 goto next;
972 /* Swap */
973 tmp = alarm_timers[i];
974 alarm_timers[i] = alarm_timers[cur];
975 alarm_timers[cur] = tmp;
977 cur++;
978 next:
979 name = strtok(NULL, ",");
982 free(arg);
984 if (cur) {
985 /* Disable remaining timers */
986 for (i = cur; i < count; i++)
987 alarm_timers[i].name = NULL;
990 /* debug */
991 show_available_alarms();
994 QEMUClock *rt_clock;
995 QEMUClock *vm_clock;
997 static QEMUTimer *active_timers[2];
999 static QEMUClock *qemu_new_clock(int type)
1001 QEMUClock *clock;
1002 clock = qemu_mallocz(sizeof(QEMUClock));
1003 if (!clock)
1004 return NULL;
1005 clock->type = type;
1006 return clock;
1009 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1011 QEMUTimer *ts;
1013 ts = qemu_mallocz(sizeof(QEMUTimer));
1014 ts->clock = clock;
1015 ts->cb = cb;
1016 ts->opaque = opaque;
1017 return ts;
1020 void qemu_free_timer(QEMUTimer *ts)
1022 qemu_free(ts);
1025 /* stop a timer, but do not dealloc it */
1026 void qemu_del_timer(QEMUTimer *ts)
1028 QEMUTimer **pt, *t;
1030 /* NOTE: this code must be signal safe because
1031 qemu_timer_expired() can be called from a signal. */
1032 pt = &active_timers[ts->clock->type];
1033 for(;;) {
1034 t = *pt;
1035 if (!t)
1036 break;
1037 if (t == ts) {
1038 *pt = t->next;
1039 break;
1041 pt = &t->next;
1045 /* modify the current timer so that it will be fired when current_time
1046 >= expire_time. The corresponding callback will be called. */
1047 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1049 QEMUTimer **pt, *t;
1051 qemu_del_timer(ts);
1053 /* add the timer in the sorted list */
1054 /* NOTE: this code must be signal safe because
1055 qemu_timer_expired() can be called from a signal. */
1056 pt = &active_timers[ts->clock->type];
1057 for(;;) {
1058 t = *pt;
1059 if (!t)
1060 break;
1061 if (t->expire_time > expire_time)
1062 break;
1063 pt = &t->next;
1065 ts->expire_time = expire_time;
1066 ts->next = *pt;
1067 *pt = ts;
1069 /* Rearm if necessary */
1070 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1071 pt == &active_timers[ts->clock->type])
1072 qemu_rearm_alarm_timer(alarm_timer);
1075 int qemu_timer_pending(QEMUTimer *ts)
1077 QEMUTimer *t;
1078 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1079 if (t == ts)
1080 return 1;
1082 return 0;
1085 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1087 if (!timer_head)
1088 return 0;
1089 return (timer_head->expire_time <= current_time);
1092 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1094 QEMUTimer *ts;
1096 for(;;) {
1097 ts = *ptimer_head;
1098 if (!ts || ts->expire_time > current_time)
1099 break;
1100 /* remove timer from the list before calling the callback */
1101 *ptimer_head = ts->next;
1102 ts->next = NULL;
1104 /* run the callback (the timer list can be modified) */
1105 ts->cb(ts->opaque);
1109 int64_t qemu_get_clock(QEMUClock *clock)
1111 switch(clock->type) {
1112 case QEMU_TIMER_REALTIME:
1113 return get_clock() / 1000000;
1114 default:
1115 case QEMU_TIMER_VIRTUAL:
1116 return cpu_get_clock();
1120 static void init_timers(void)
1122 init_get_clock();
1123 ticks_per_sec = QEMU_TIMER_BASE;
1124 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1125 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1128 /* save a timer */
1129 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1131 uint64_t expire_time;
1133 if (qemu_timer_pending(ts)) {
1134 expire_time = ts->expire_time;
1135 } else {
1136 expire_time = -1;
1138 qemu_put_be64(f, expire_time);
1141 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1143 uint64_t expire_time;
1145 expire_time = qemu_get_be64(f);
1146 if (expire_time != -1) {
1147 qemu_mod_timer(ts, expire_time);
1148 } else {
1149 qemu_del_timer(ts);
1153 static void timer_save(QEMUFile *f, void *opaque)
1155 if (cpu_ticks_enabled) {
1156 hw_error("cannot save state if virtual timers are running");
1158 qemu_put_be64(f, cpu_ticks_offset);
1159 qemu_put_be64(f, ticks_per_sec);
1160 qemu_put_be64(f, cpu_clock_offset);
1163 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1165 if (version_id != 1 && version_id != 2)
1166 return -EINVAL;
1167 if (cpu_ticks_enabled) {
1168 return -EINVAL;
1170 cpu_ticks_offset=qemu_get_be64(f);
1171 ticks_per_sec=qemu_get_be64(f);
1172 if (version_id == 2) {
1173 cpu_clock_offset=qemu_get_be64(f);
1175 return 0;
1178 #ifdef _WIN32
1179 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1180 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1181 #else
1182 static void host_alarm_handler(int host_signum)
1183 #endif
1185 #if 0
1186 #define DISP_FREQ 1000
1188 static int64_t delta_min = INT64_MAX;
1189 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1190 static int count;
1191 ti = qemu_get_clock(vm_clock);
1192 if (last_clock != 0) {
1193 delta = ti - last_clock;
1194 if (delta < delta_min)
1195 delta_min = delta;
1196 if (delta > delta_max)
1197 delta_max = delta;
1198 delta_cum += delta;
1199 if (++count == DISP_FREQ) {
1200 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1201 muldiv64(delta_min, 1000000, ticks_per_sec),
1202 muldiv64(delta_max, 1000000, ticks_per_sec),
1203 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1204 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1205 count = 0;
1206 delta_min = INT64_MAX;
1207 delta_max = 0;
1208 delta_cum = 0;
1211 last_clock = ti;
1213 #endif
1214 if (1 ||
1215 alarm_has_dynticks(alarm_timer) ||
1216 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1217 qemu_get_clock(vm_clock)) ||
1218 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1219 qemu_get_clock(rt_clock))) {
1220 #ifdef _WIN32
1221 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1222 SetEvent(data->host_alarm);
1223 #endif
1224 CPUState *env = next_cpu;
1226 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1228 if (env) {
1229 /* stop the currently executing cpu because a timer occured */
1230 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1231 #ifdef USE_KQEMU
1232 if (env->kqemu_enabled) {
1233 kqemu_cpu_interrupt(env);
1235 #endif
1237 event_pending = 1;
1241 static uint64_t qemu_next_deadline(void)
1243 int64_t nearest_delta_us = INT64_MAX;
1244 int64_t vmdelta_us;
1246 if (active_timers[QEMU_TIMER_REALTIME])
1247 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1248 qemu_get_clock(rt_clock))*1000;
1250 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1251 /* round up */
1252 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1253 qemu_get_clock(vm_clock)+999)/1000;
1254 if (vmdelta_us < nearest_delta_us)
1255 nearest_delta_us = vmdelta_us;
1258 /* Avoid arming the timer to negative, zero, or too low values */
1259 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1260 nearest_delta_us = MIN_TIMER_REARM_US;
1262 return nearest_delta_us;
1265 #ifndef _WIN32
1267 #if defined(__linux__)
1269 #define RTC_FREQ 1024
1271 static void enable_sigio_timer(int fd)
1273 struct sigaction act;
1275 /* timer signal */
1276 sigfillset(&act.sa_mask);
1277 act.sa_flags = 0;
1278 act.sa_handler = host_alarm_handler;
1280 sigaction(SIGIO, &act, NULL);
1281 fcntl(fd, F_SETFL, O_ASYNC);
1282 fcntl(fd, F_SETOWN, getpid());
1285 static int hpet_start_timer(struct qemu_alarm_timer *t)
1287 struct hpet_info info;
1288 int r, fd;
1290 fd = open("/dev/hpet", O_RDONLY);
1291 if (fd < 0)
1292 return -1;
1294 /* Set frequency */
1295 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1296 if (r < 0) {
1297 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1298 "error, but for better emulation accuracy type:\n"
1299 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1300 goto fail;
1303 /* Check capabilities */
1304 r = ioctl(fd, HPET_INFO, &info);
1305 if (r < 0)
1306 goto fail;
1308 /* Enable periodic mode */
1309 r = ioctl(fd, HPET_EPI, 0);
1310 if (info.hi_flags && (r < 0))
1311 goto fail;
1313 /* Enable interrupt */
1314 r = ioctl(fd, HPET_IE_ON, 0);
1315 if (r < 0)
1316 goto fail;
1318 enable_sigio_timer(fd);
1319 t->priv = (void *)(long)fd;
1321 return 0;
1322 fail:
1323 close(fd);
1324 return -1;
1327 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1329 int fd = (long)t->priv;
1331 close(fd);
1334 static int rtc_start_timer(struct qemu_alarm_timer *t)
1336 int rtc_fd;
1337 unsigned long current_rtc_freq = 0;
1339 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1340 if (rtc_fd < 0)
1341 return -1;
1342 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1343 if (current_rtc_freq != RTC_FREQ &&
1344 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1345 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1346 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1347 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1348 goto fail;
1350 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1351 fail:
1352 close(rtc_fd);
1353 return -1;
1356 enable_sigio_timer(rtc_fd);
1358 t->priv = (void *)(long)rtc_fd;
1360 return 0;
1363 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1365 int rtc_fd = (long)t->priv;
1367 close(rtc_fd);
1370 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1372 struct sigevent ev;
1373 timer_t host_timer;
1374 struct sigaction act;
1376 sigfillset(&act.sa_mask);
1377 act.sa_flags = 0;
1378 act.sa_handler = host_alarm_handler;
1380 sigaction(SIGALRM, &act, NULL);
1382 ev.sigev_value.sival_int = 0;
1383 ev.sigev_notify = SIGEV_SIGNAL;
1384 ev.sigev_signo = SIGALRM;
1386 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1387 perror("timer_create");
1389 /* disable dynticks */
1390 fprintf(stderr, "Dynamic Ticks disabled\n");
1392 return -1;
1395 t->priv = (void *)host_timer;
1397 return 0;
1400 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1402 timer_t host_timer = (timer_t)t->priv;
1404 timer_delete(host_timer);
1407 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1409 timer_t host_timer = (timer_t)t->priv;
1410 struct itimerspec timeout;
1411 int64_t nearest_delta_us = INT64_MAX;
1412 int64_t current_us;
1414 if (!active_timers[QEMU_TIMER_REALTIME] &&
1415 !active_timers[QEMU_TIMER_VIRTUAL])
1416 return;
1418 nearest_delta_us = qemu_next_deadline();
1420 /* check whether a timer is already running */
1421 if (timer_gettime(host_timer, &timeout)) {
1422 perror("gettime");
1423 fprintf(stderr, "Internal timer error: aborting\n");
1424 exit(1);
1426 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1427 if (current_us && current_us <= nearest_delta_us)
1428 return;
1430 timeout.it_interval.tv_sec = 0;
1431 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1432 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1433 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1434 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1435 perror("settime");
1436 fprintf(stderr, "Internal timer error: aborting\n");
1437 exit(1);
1441 #endif /* defined(__linux__) */
1443 static int unix_start_timer(struct qemu_alarm_timer *t)
1445 struct sigaction act;
1446 struct itimerval itv;
1447 int err;
1449 /* timer signal */
1450 sigfillset(&act.sa_mask);
1451 act.sa_flags = 0;
1452 act.sa_handler = host_alarm_handler;
1454 sigaction(SIGALRM, &act, NULL);
1456 itv.it_interval.tv_sec = 0;
1457 /* for i386 kernel 2.6 to get 1 ms */
1458 itv.it_interval.tv_usec = 999;
1459 itv.it_value.tv_sec = 0;
1460 itv.it_value.tv_usec = 10 * 1000;
1462 err = setitimer(ITIMER_REAL, &itv, NULL);
1463 if (err)
1464 return -1;
1466 return 0;
1469 static void unix_stop_timer(struct qemu_alarm_timer *t)
1471 struct itimerval itv;
1473 memset(&itv, 0, sizeof(itv));
1474 setitimer(ITIMER_REAL, &itv, NULL);
1477 #endif /* !defined(_WIN32) */
1479 #ifdef _WIN32
1481 static int win32_start_timer(struct qemu_alarm_timer *t)
1483 TIMECAPS tc;
1484 struct qemu_alarm_win32 *data = t->priv;
1485 UINT flags;
1487 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1488 if (!data->host_alarm) {
1489 perror("Failed CreateEvent");
1490 return -1;
1493 memset(&tc, 0, sizeof(tc));
1494 timeGetDevCaps(&tc, sizeof(tc));
1496 if (data->period < tc.wPeriodMin)
1497 data->period = tc.wPeriodMin;
1499 timeBeginPeriod(data->period);
1501 flags = TIME_CALLBACK_FUNCTION;
1502 if (alarm_has_dynticks(t))
1503 flags |= TIME_ONESHOT;
1504 else
1505 flags |= TIME_PERIODIC;
1507 data->timerId = timeSetEvent(1, // interval (ms)
1508 data->period, // resolution
1509 host_alarm_handler, // function
1510 (DWORD)t, // parameter
1511 flags);
1513 if (!data->timerId) {
1514 perror("Failed to initialize win32 alarm timer");
1516 timeEndPeriod(data->period);
1517 CloseHandle(data->host_alarm);
1518 return -1;
1521 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1523 return 0;
1526 static void win32_stop_timer(struct qemu_alarm_timer *t)
1528 struct qemu_alarm_win32 *data = t->priv;
1530 timeKillEvent(data->timerId);
1531 timeEndPeriod(data->period);
1533 CloseHandle(data->host_alarm);
1536 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1538 struct qemu_alarm_win32 *data = t->priv;
1539 uint64_t nearest_delta_us;
1541 if (!active_timers[QEMU_TIMER_REALTIME] &&
1542 !active_timers[QEMU_TIMER_VIRTUAL])
1543 return;
1545 nearest_delta_us = qemu_next_deadline();
1546 nearest_delta_us /= 1000;
1548 timeKillEvent(data->timerId);
1550 data->timerId = timeSetEvent(1,
1551 data->period,
1552 host_alarm_handler,
1553 (DWORD)t,
1554 TIME_ONESHOT | TIME_PERIODIC);
1556 if (!data->timerId) {
1557 perror("Failed to re-arm win32 alarm timer");
1559 timeEndPeriod(data->period);
1560 CloseHandle(data->host_alarm);
1561 exit(1);
1565 #endif /* _WIN32 */
1567 static void init_timer_alarm(void)
1569 struct qemu_alarm_timer *t;
1570 int i, err = -1;
1572 for (i = 0; alarm_timers[i].name; i++) {
1573 t = &alarm_timers[i];
1575 err = t->start(t);
1576 if (!err)
1577 break;
1580 if (err) {
1581 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1582 fprintf(stderr, "Terminating\n");
1583 exit(1);
1586 alarm_timer = t;
1589 static void quit_timers(void)
1591 alarm_timer->stop(alarm_timer);
1592 alarm_timer = NULL;
1595 /***********************************************************/
1596 /* host time/date access */
1597 void qemu_get_timedate(struct tm *tm, int offset)
1599 time_t ti;
1600 struct tm *ret;
1602 time(&ti);
1603 ti += offset;
1604 if (rtc_date_offset == -1) {
1605 if (rtc_utc)
1606 ret = gmtime(&ti);
1607 else
1608 ret = localtime(&ti);
1609 } else {
1610 ti -= rtc_date_offset;
1611 ret = gmtime(&ti);
1614 memcpy(tm, ret, sizeof(struct tm));
1617 int qemu_timedate_diff(struct tm *tm)
1619 time_t seconds;
1621 if (rtc_date_offset == -1)
1622 if (rtc_utc)
1623 seconds = mktimegm(tm);
1624 else
1625 seconds = mktime(tm);
1626 else
1627 seconds = mktimegm(tm) + rtc_date_offset;
1629 return seconds - time(NULL);
1632 /***********************************************************/
1633 /* character device */
1635 static void qemu_chr_event(CharDriverState *s, int event)
1637 if (!s->chr_event)
1638 return;
1639 s->chr_event(s->handler_opaque, event);
1642 static void qemu_chr_reset_bh(void *opaque)
1644 CharDriverState *s = opaque;
1645 qemu_chr_event(s, CHR_EVENT_RESET);
1646 qemu_bh_delete(s->bh);
1647 s->bh = NULL;
1650 void qemu_chr_reset(CharDriverState *s)
1652 if (s->bh == NULL) {
1653 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1654 qemu_bh_schedule(s->bh);
1658 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1660 return s->chr_write(s, buf, len);
1663 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1665 if (!s->chr_ioctl)
1666 return -ENOTSUP;
1667 return s->chr_ioctl(s, cmd, arg);
1670 int qemu_chr_can_read(CharDriverState *s)
1672 if (!s->chr_can_read)
1673 return 0;
1674 return s->chr_can_read(s->handler_opaque);
1677 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1679 s->chr_read(s->handler_opaque, buf, len);
1682 void qemu_chr_accept_input(CharDriverState *s)
1684 if (s->chr_accept_input)
1685 s->chr_accept_input(s);
1688 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1690 char buf[4096];
1691 va_list ap;
1692 va_start(ap, fmt);
1693 vsnprintf(buf, sizeof(buf), fmt, ap);
1694 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1695 va_end(ap);
1698 void qemu_chr_send_event(CharDriverState *s, int event)
1700 if (s->chr_send_event)
1701 s->chr_send_event(s, event);
1704 void qemu_chr_add_handlers(CharDriverState *s,
1705 IOCanRWHandler *fd_can_read,
1706 IOReadHandler *fd_read,
1707 IOEventHandler *fd_event,
1708 void *opaque)
1710 s->chr_can_read = fd_can_read;
1711 s->chr_read = fd_read;
1712 s->chr_event = fd_event;
1713 s->handler_opaque = opaque;
1714 if (s->chr_update_read_handler)
1715 s->chr_update_read_handler(s);
1718 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1720 return len;
1723 static CharDriverState *qemu_chr_open_null(void)
1725 CharDriverState *chr;
1727 chr = qemu_mallocz(sizeof(CharDriverState));
1728 if (!chr)
1729 return NULL;
1730 chr->chr_write = null_chr_write;
1731 return chr;
1734 /* MUX driver for serial I/O splitting */
1735 static int term_timestamps;
1736 static int64_t term_timestamps_start;
1737 #define MAX_MUX 4
1738 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1739 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1740 typedef struct {
1741 IOCanRWHandler *chr_can_read[MAX_MUX];
1742 IOReadHandler *chr_read[MAX_MUX];
1743 IOEventHandler *chr_event[MAX_MUX];
1744 void *ext_opaque[MAX_MUX];
1745 CharDriverState *drv;
1746 unsigned char buffer[MUX_BUFFER_SIZE];
1747 int prod;
1748 int cons;
1749 int mux_cnt;
1750 int term_got_escape;
1751 int max_size;
1752 } MuxDriver;
1755 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1757 MuxDriver *d = chr->opaque;
1758 int ret;
1759 if (!term_timestamps) {
1760 ret = d->drv->chr_write(d->drv, buf, len);
1761 } else {
1762 int i;
1764 ret = 0;
1765 for(i = 0; i < len; i++) {
1766 ret += d->drv->chr_write(d->drv, buf+i, 1);
1767 if (buf[i] == '\n') {
1768 char buf1[64];
1769 int64_t ti;
1770 int secs;
1772 ti = get_clock();
1773 if (term_timestamps_start == -1)
1774 term_timestamps_start = ti;
1775 ti -= term_timestamps_start;
1776 secs = ti / 1000000000;
1777 snprintf(buf1, sizeof(buf1),
1778 "[%02d:%02d:%02d.%03d] ",
1779 secs / 3600,
1780 (secs / 60) % 60,
1781 secs % 60,
1782 (int)((ti / 1000000) % 1000));
1783 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1787 return ret;
1790 static char *mux_help[] = {
1791 "% h print this help\n\r",
1792 "% x exit emulator\n\r",
1793 "% s save disk data back to file (if -snapshot)\n\r",
1794 "% t toggle console timestamps\n\r"
1795 "% b send break (magic sysrq)\n\r",
1796 "% c switch between console and monitor\n\r",
1797 "% % sends %\n\r",
1798 NULL
1801 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1802 static void mux_print_help(CharDriverState *chr)
1804 int i, j;
1805 char ebuf[15] = "Escape-Char";
1806 char cbuf[50] = "\n\r";
1808 if (term_escape_char > 0 && term_escape_char < 26) {
1809 sprintf(cbuf,"\n\r");
1810 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1811 } else {
1812 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1813 term_escape_char);
1815 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1816 for (i = 0; mux_help[i] != NULL; i++) {
1817 for (j=0; mux_help[i][j] != '\0'; j++) {
1818 if (mux_help[i][j] == '%')
1819 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1820 else
1821 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1826 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1828 if (d->term_got_escape) {
1829 d->term_got_escape = 0;
1830 if (ch == term_escape_char)
1831 goto send_char;
1832 switch(ch) {
1833 case '?':
1834 case 'h':
1835 mux_print_help(chr);
1836 break;
1837 case 'x':
1839 char *term = "QEMU: Terminated\n\r";
1840 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1841 exit(0);
1842 break;
1844 case 's':
1846 int i;
1847 for (i = 0; i < nb_drives; i++) {
1848 bdrv_commit(drives_table[i].bdrv);
1851 break;
1852 case 'b':
1853 qemu_chr_event(chr, CHR_EVENT_BREAK);
1854 break;
1855 case 'c':
1856 /* Switch to the next registered device */
1857 chr->focus++;
1858 if (chr->focus >= d->mux_cnt)
1859 chr->focus = 0;
1860 break;
1861 case 't':
1862 term_timestamps = !term_timestamps;
1863 term_timestamps_start = -1;
1864 break;
1866 } else if (ch == term_escape_char) {
1867 d->term_got_escape = 1;
1868 } else {
1869 send_char:
1870 return 1;
1872 return 0;
1875 static void mux_chr_accept_input(CharDriverState *chr)
1877 int m = chr->focus;
1878 MuxDriver *d = chr->opaque;
1880 while (d->prod != d->cons &&
1881 d->chr_can_read[m] &&
1882 d->chr_can_read[m](d->ext_opaque[m])) {
1883 d->chr_read[m](d->ext_opaque[m],
1884 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1888 static int mux_chr_can_read(void *opaque)
1890 CharDriverState *chr = opaque;
1891 MuxDriver *d = chr->opaque;
1893 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1894 return 1;
1895 if (d->chr_can_read[chr->focus])
1896 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1897 return 0;
1900 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1902 CharDriverState *chr = opaque;
1903 MuxDriver *d = chr->opaque;
1904 int m = chr->focus;
1905 int i;
1907 mux_chr_accept_input (opaque);
1909 for(i = 0; i < size; i++)
1910 if (mux_proc_byte(chr, d, buf[i])) {
1911 if (d->prod == d->cons &&
1912 d->chr_can_read[m] &&
1913 d->chr_can_read[m](d->ext_opaque[m]))
1914 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1915 else
1916 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1920 static void mux_chr_event(void *opaque, int event)
1922 CharDriverState *chr = opaque;
1923 MuxDriver *d = chr->opaque;
1924 int i;
1926 /* Send the event to all registered listeners */
1927 for (i = 0; i < d->mux_cnt; i++)
1928 if (d->chr_event[i])
1929 d->chr_event[i](d->ext_opaque[i], event);
1932 static void mux_chr_update_read_handler(CharDriverState *chr)
1934 MuxDriver *d = chr->opaque;
1936 if (d->mux_cnt >= MAX_MUX) {
1937 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1938 return;
1940 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1941 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1942 d->chr_read[d->mux_cnt] = chr->chr_read;
1943 d->chr_event[d->mux_cnt] = chr->chr_event;
1944 /* Fix up the real driver with mux routines */
1945 if (d->mux_cnt == 0) {
1946 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1947 mux_chr_event, chr);
1949 chr->focus = d->mux_cnt;
1950 d->mux_cnt++;
1953 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1955 CharDriverState *chr;
1956 MuxDriver *d;
1958 chr = qemu_mallocz(sizeof(CharDriverState));
1959 if (!chr)
1960 return NULL;
1961 d = qemu_mallocz(sizeof(MuxDriver));
1962 if (!d) {
1963 free(chr);
1964 return NULL;
1967 chr->opaque = d;
1968 d->drv = drv;
1969 chr->focus = -1;
1970 chr->chr_write = mux_chr_write;
1971 chr->chr_update_read_handler = mux_chr_update_read_handler;
1972 chr->chr_accept_input = mux_chr_accept_input;
1973 return chr;
1977 #ifdef _WIN32
1979 static void socket_cleanup(void)
1981 WSACleanup();
1984 static int socket_init(void)
1986 WSADATA Data;
1987 int ret, err;
1989 ret = WSAStartup(MAKEWORD(2,2), &Data);
1990 if (ret != 0) {
1991 err = WSAGetLastError();
1992 fprintf(stderr, "WSAStartup: %d\n", err);
1993 return -1;
1995 atexit(socket_cleanup);
1996 return 0;
1999 static int send_all(int fd, const uint8_t *buf, int len1)
2001 int ret, len;
2003 len = len1;
2004 while (len > 0) {
2005 ret = send(fd, buf, len, 0);
2006 if (ret < 0) {
2007 int errno;
2008 errno = WSAGetLastError();
2009 if (errno != WSAEWOULDBLOCK) {
2010 return -1;
2012 } else if (ret == 0) {
2013 break;
2014 } else {
2015 buf += ret;
2016 len -= ret;
2019 return len1 - len;
2022 void socket_set_nonblock(int fd)
2024 unsigned long opt = 1;
2025 ioctlsocket(fd, FIONBIO, &opt);
2028 #else
2030 static int unix_write(int fd, const uint8_t *buf, int len1)
2032 int ret, len;
2034 len = len1;
2035 while (len > 0) {
2036 ret = write(fd, buf, len);
2037 if (ret < 0) {
2038 if (errno != EINTR && errno != EAGAIN)
2039 return -1;
2040 } else if (ret == 0) {
2041 break;
2042 } else {
2043 buf += ret;
2044 len -= ret;
2047 return len1 - len;
2050 static inline int send_all(int fd, const uint8_t *buf, int len1)
2052 return unix_write(fd, buf, len1);
2055 void socket_set_nonblock(int fd)
2057 fcntl(fd, F_SETFL, O_NONBLOCK);
2059 #endif /* !_WIN32 */
2061 #ifndef _WIN32
2063 typedef struct {
2064 int fd_in, fd_out;
2065 int max_size;
2066 } FDCharDriver;
2068 #define STDIO_MAX_CLIENTS 1
2069 static int stdio_nb_clients = 0;
2071 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2073 FDCharDriver *s = chr->opaque;
2074 return unix_write(s->fd_out, buf, len);
2077 static int fd_chr_read_poll(void *opaque)
2079 CharDriverState *chr = opaque;
2080 FDCharDriver *s = chr->opaque;
2082 s->max_size = qemu_chr_can_read(chr);
2083 return s->max_size;
2086 static void fd_chr_read(void *opaque)
2088 CharDriverState *chr = opaque;
2089 FDCharDriver *s = chr->opaque;
2090 int size, len;
2091 uint8_t buf[1024];
2093 len = sizeof(buf);
2094 if (len > s->max_size)
2095 len = s->max_size;
2096 if (len == 0)
2097 return;
2098 size = read(s->fd_in, buf, len);
2099 if (size == 0) {
2100 /* FD has been closed. Remove it from the active list. */
2101 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2102 return;
2104 if (size > 0) {
2105 qemu_chr_read(chr, buf, size);
2109 static void fd_chr_update_read_handler(CharDriverState *chr)
2111 FDCharDriver *s = chr->opaque;
2113 if (s->fd_in >= 0) {
2114 if (nographic && s->fd_in == 0) {
2115 } else {
2116 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2117 fd_chr_read, NULL, chr);
2122 static void fd_chr_close(struct CharDriverState *chr)
2124 FDCharDriver *s = chr->opaque;
2126 if (s->fd_in >= 0) {
2127 if (nographic && s->fd_in == 0) {
2128 } else {
2129 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2133 qemu_free(s);
2136 /* open a character device to a unix fd */
2137 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2139 CharDriverState *chr;
2140 FDCharDriver *s;
2142 chr = qemu_mallocz(sizeof(CharDriverState));
2143 if (!chr)
2144 return NULL;
2145 s = qemu_mallocz(sizeof(FDCharDriver));
2146 if (!s) {
2147 free(chr);
2148 return NULL;
2150 s->fd_in = fd_in;
2151 s->fd_out = fd_out;
2152 chr->opaque = s;
2153 chr->chr_write = fd_chr_write;
2154 chr->chr_update_read_handler = fd_chr_update_read_handler;
2155 chr->chr_close = fd_chr_close;
2157 qemu_chr_reset(chr);
2159 return chr;
2162 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2164 int fd_out;
2166 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2167 if (fd_out < 0)
2168 return NULL;
2169 return qemu_chr_open_fd(-1, fd_out);
2172 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2174 int fd_in, fd_out;
2175 char filename_in[256], filename_out[256];
2177 snprintf(filename_in, 256, "%s.in", filename);
2178 snprintf(filename_out, 256, "%s.out", filename);
2179 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2180 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2181 if (fd_in < 0 || fd_out < 0) {
2182 if (fd_in >= 0)
2183 close(fd_in);
2184 if (fd_out >= 0)
2185 close(fd_out);
2186 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2187 if (fd_in < 0)
2188 return NULL;
2190 return qemu_chr_open_fd(fd_in, fd_out);
2194 /* for STDIO, we handle the case where several clients use it
2195 (nographic mode) */
2197 #define TERM_FIFO_MAX_SIZE 1
2199 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2200 static int term_fifo_size;
2202 static int stdio_read_poll(void *opaque)
2204 CharDriverState *chr = opaque;
2206 /* try to flush the queue if needed */
2207 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2208 qemu_chr_read(chr, term_fifo, 1);
2209 term_fifo_size = 0;
2211 /* see if we can absorb more chars */
2212 if (term_fifo_size == 0)
2213 return 1;
2214 else
2215 return 0;
2218 static void stdio_read(void *opaque)
2220 int size;
2221 uint8_t buf[1];
2222 CharDriverState *chr = opaque;
2224 size = read(0, buf, 1);
2225 if (size == 0) {
2226 /* stdin has been closed. Remove it from the active list. */
2227 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2228 return;
2230 if (size > 0) {
2231 if (qemu_chr_can_read(chr) > 0) {
2232 qemu_chr_read(chr, buf, 1);
2233 } else if (term_fifo_size == 0) {
2234 term_fifo[term_fifo_size++] = buf[0];
2239 /* init terminal so that we can grab keys */
2240 static struct termios oldtty;
2241 static int old_fd0_flags;
2242 static int term_atexit_done;
2244 static void term_exit(void)
2246 tcsetattr (0, TCSANOW, &oldtty);
2247 fcntl(0, F_SETFL, old_fd0_flags);
2250 static void term_init(void)
2252 struct termios tty;
2254 tcgetattr (0, &tty);
2255 oldtty = tty;
2256 old_fd0_flags = fcntl(0, F_GETFL);
2258 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2259 |INLCR|IGNCR|ICRNL|IXON);
2260 tty.c_oflag |= OPOST;
2261 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2262 /* if graphical mode, we allow Ctrl-C handling */
2263 if (nographic)
2264 tty.c_lflag &= ~ISIG;
2265 tty.c_cflag &= ~(CSIZE|PARENB);
2266 tty.c_cflag |= CS8;
2267 tty.c_cc[VMIN] = 1;
2268 tty.c_cc[VTIME] = 0;
2270 tcsetattr (0, TCSANOW, &tty);
2272 if (!term_atexit_done++)
2273 atexit(term_exit);
2275 fcntl(0, F_SETFL, O_NONBLOCK);
2278 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2280 term_exit();
2281 stdio_nb_clients--;
2282 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2283 fd_chr_close(chr);
2286 static CharDriverState *qemu_chr_open_stdio(void)
2288 CharDriverState *chr;
2290 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2291 return NULL;
2292 chr = qemu_chr_open_fd(0, 1);
2293 chr->chr_close = qemu_chr_close_stdio;
2294 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2295 stdio_nb_clients++;
2296 term_init();
2298 return chr;
2301 #if defined(__linux__) || defined(__sun__)
2302 static CharDriverState *qemu_chr_open_pty(void)
2304 struct termios tty;
2305 char slave_name[1024];
2306 int master_fd, slave_fd;
2308 #if defined(__linux__)
2309 /* Not satisfying */
2310 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2311 return NULL;
2313 #endif
2315 /* Disabling local echo and line-buffered output */
2316 tcgetattr (master_fd, &tty);
2317 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2318 tty.c_cc[VMIN] = 1;
2319 tty.c_cc[VTIME] = 0;
2320 tcsetattr (master_fd, TCSAFLUSH, &tty);
2322 fprintf(stderr, "char device redirected to %s\n", slave_name);
2323 return qemu_chr_open_fd(master_fd, master_fd);
2326 static void tty_serial_init(int fd, int speed,
2327 int parity, int data_bits, int stop_bits)
2329 struct termios tty;
2330 speed_t spd;
2332 #if 0
2333 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2334 speed, parity, data_bits, stop_bits);
2335 #endif
2336 tcgetattr (fd, &tty);
2338 #define MARGIN 1.1
2339 if (speed <= 50 * MARGIN)
2340 spd = B50;
2341 else if (speed <= 75 * MARGIN)
2342 spd = B75;
2343 else if (speed <= 300 * MARGIN)
2344 spd = B300;
2345 else if (speed <= 600 * MARGIN)
2346 spd = B600;
2347 else if (speed <= 1200 * MARGIN)
2348 spd = B1200;
2349 else if (speed <= 2400 * MARGIN)
2350 spd = B2400;
2351 else if (speed <= 4800 * MARGIN)
2352 spd = B4800;
2353 else if (speed <= 9600 * MARGIN)
2354 spd = B9600;
2355 else if (speed <= 19200 * MARGIN)
2356 spd = B19200;
2357 else if (speed <= 38400 * MARGIN)
2358 spd = B38400;
2359 else if (speed <= 57600 * MARGIN)
2360 spd = B57600;
2361 else if (speed <= 115200 * MARGIN)
2362 spd = B115200;
2363 else
2364 spd = B115200;
2366 cfsetispeed(&tty, spd);
2367 cfsetospeed(&tty, spd);
2369 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2370 |INLCR|IGNCR|ICRNL|IXON);
2371 tty.c_oflag |= OPOST;
2372 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2373 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2374 switch(data_bits) {
2375 default:
2376 case 8:
2377 tty.c_cflag |= CS8;
2378 break;
2379 case 7:
2380 tty.c_cflag |= CS7;
2381 break;
2382 case 6:
2383 tty.c_cflag |= CS6;
2384 break;
2385 case 5:
2386 tty.c_cflag |= CS5;
2387 break;
2389 switch(parity) {
2390 default:
2391 case 'N':
2392 break;
2393 case 'E':
2394 tty.c_cflag |= PARENB;
2395 break;
2396 case 'O':
2397 tty.c_cflag |= PARENB | PARODD;
2398 break;
2400 if (stop_bits == 2)
2401 tty.c_cflag |= CSTOPB;
2403 tcsetattr (fd, TCSANOW, &tty);
2406 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2408 FDCharDriver *s = chr->opaque;
2410 switch(cmd) {
2411 case CHR_IOCTL_SERIAL_SET_PARAMS:
2413 QEMUSerialSetParams *ssp = arg;
2414 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2415 ssp->data_bits, ssp->stop_bits);
2417 break;
2418 case CHR_IOCTL_SERIAL_SET_BREAK:
2420 int enable = *(int *)arg;
2421 if (enable)
2422 tcsendbreak(s->fd_in, 1);
2424 break;
2425 default:
2426 return -ENOTSUP;
2428 return 0;
2431 static CharDriverState *qemu_chr_open_tty(const char *filename)
2433 CharDriverState *chr;
2434 int fd;
2436 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2437 fcntl(fd, F_SETFL, O_NONBLOCK);
2438 tty_serial_init(fd, 115200, 'N', 8, 1);
2439 chr = qemu_chr_open_fd(fd, fd);
2440 if (!chr) {
2441 close(fd);
2442 return NULL;
2444 chr->chr_ioctl = tty_serial_ioctl;
2445 qemu_chr_reset(chr);
2446 return chr;
2448 #else /* ! __linux__ && ! __sun__ */
2449 static CharDriverState *qemu_chr_open_pty(void)
2451 return NULL;
2453 #endif /* __linux__ || __sun__ */
2455 #if defined(__linux__)
2456 typedef struct {
2457 int fd;
2458 int mode;
2459 } ParallelCharDriver;
2461 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2463 if (s->mode != mode) {
2464 int m = mode;
2465 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2466 return 0;
2467 s->mode = mode;
2469 return 1;
2472 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2474 ParallelCharDriver *drv = chr->opaque;
2475 int fd = drv->fd;
2476 uint8_t b;
2478 switch(cmd) {
2479 case CHR_IOCTL_PP_READ_DATA:
2480 if (ioctl(fd, PPRDATA, &b) < 0)
2481 return -ENOTSUP;
2482 *(uint8_t *)arg = b;
2483 break;
2484 case CHR_IOCTL_PP_WRITE_DATA:
2485 b = *(uint8_t *)arg;
2486 if (ioctl(fd, PPWDATA, &b) < 0)
2487 return -ENOTSUP;
2488 break;
2489 case CHR_IOCTL_PP_READ_CONTROL:
2490 if (ioctl(fd, PPRCONTROL, &b) < 0)
2491 return -ENOTSUP;
2492 /* Linux gives only the lowest bits, and no way to know data
2493 direction! For better compatibility set the fixed upper
2494 bits. */
2495 *(uint8_t *)arg = b | 0xc0;
2496 break;
2497 case CHR_IOCTL_PP_WRITE_CONTROL:
2498 b = *(uint8_t *)arg;
2499 if (ioctl(fd, PPWCONTROL, &b) < 0)
2500 return -ENOTSUP;
2501 break;
2502 case CHR_IOCTL_PP_READ_STATUS:
2503 if (ioctl(fd, PPRSTATUS, &b) < 0)
2504 return -ENOTSUP;
2505 *(uint8_t *)arg = b;
2506 break;
2507 case CHR_IOCTL_PP_EPP_READ_ADDR:
2508 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2509 struct ParallelIOArg *parg = arg;
2510 int n = read(fd, parg->buffer, parg->count);
2511 if (n != parg->count) {
2512 return -EIO;
2515 break;
2516 case CHR_IOCTL_PP_EPP_READ:
2517 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2518 struct ParallelIOArg *parg = arg;
2519 int n = read(fd, parg->buffer, parg->count);
2520 if (n != parg->count) {
2521 return -EIO;
2524 break;
2525 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2526 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2527 struct ParallelIOArg *parg = arg;
2528 int n = write(fd, parg->buffer, parg->count);
2529 if (n != parg->count) {
2530 return -EIO;
2533 break;
2534 case CHR_IOCTL_PP_EPP_WRITE:
2535 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2536 struct ParallelIOArg *parg = arg;
2537 int n = write(fd, parg->buffer, parg->count);
2538 if (n != parg->count) {
2539 return -EIO;
2542 break;
2543 default:
2544 return -ENOTSUP;
2546 return 0;
2549 static void pp_close(CharDriverState *chr)
2551 ParallelCharDriver *drv = chr->opaque;
2552 int fd = drv->fd;
2554 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2555 ioctl(fd, PPRELEASE);
2556 close(fd);
2557 qemu_free(drv);
2560 static CharDriverState *qemu_chr_open_pp(const char *filename)
2562 CharDriverState *chr;
2563 ParallelCharDriver *drv;
2564 int fd;
2566 TFR(fd = open(filename, O_RDWR));
2567 if (fd < 0)
2568 return NULL;
2570 if (ioctl(fd, PPCLAIM) < 0) {
2571 close(fd);
2572 return NULL;
2575 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2576 if (!drv) {
2577 close(fd);
2578 return NULL;
2580 drv->fd = fd;
2581 drv->mode = IEEE1284_MODE_COMPAT;
2583 chr = qemu_mallocz(sizeof(CharDriverState));
2584 if (!chr) {
2585 qemu_free(drv);
2586 close(fd);
2587 return NULL;
2589 chr->chr_write = null_chr_write;
2590 chr->chr_ioctl = pp_ioctl;
2591 chr->chr_close = pp_close;
2592 chr->opaque = drv;
2594 qemu_chr_reset(chr);
2596 return chr;
2598 #endif /* __linux__ */
2600 #else /* _WIN32 */
2602 typedef struct {
2603 int max_size;
2604 HANDLE hcom, hrecv, hsend;
2605 OVERLAPPED orecv, osend;
2606 BOOL fpipe;
2607 DWORD len;
2608 } WinCharState;
2610 #define NSENDBUF 2048
2611 #define NRECVBUF 2048
2612 #define MAXCONNECT 1
2613 #define NTIMEOUT 5000
2615 static int win_chr_poll(void *opaque);
2616 static int win_chr_pipe_poll(void *opaque);
2618 static void win_chr_close(CharDriverState *chr)
2620 WinCharState *s = chr->opaque;
2622 if (s->hsend) {
2623 CloseHandle(s->hsend);
2624 s->hsend = NULL;
2626 if (s->hrecv) {
2627 CloseHandle(s->hrecv);
2628 s->hrecv = NULL;
2630 if (s->hcom) {
2631 CloseHandle(s->hcom);
2632 s->hcom = NULL;
2634 if (s->fpipe)
2635 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2636 else
2637 qemu_del_polling_cb(win_chr_poll, chr);
2640 static int win_chr_init(CharDriverState *chr, const char *filename)
2642 WinCharState *s = chr->opaque;
2643 COMMCONFIG comcfg;
2644 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2645 COMSTAT comstat;
2646 DWORD size;
2647 DWORD err;
2649 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2650 if (!s->hsend) {
2651 fprintf(stderr, "Failed CreateEvent\n");
2652 goto fail;
2654 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2655 if (!s->hrecv) {
2656 fprintf(stderr, "Failed CreateEvent\n");
2657 goto fail;
2660 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2661 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2662 if (s->hcom == INVALID_HANDLE_VALUE) {
2663 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2664 s->hcom = NULL;
2665 goto fail;
2668 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2669 fprintf(stderr, "Failed SetupComm\n");
2670 goto fail;
2673 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2674 size = sizeof(COMMCONFIG);
2675 GetDefaultCommConfig(filename, &comcfg, &size);
2676 comcfg.dcb.DCBlength = sizeof(DCB);
2677 CommConfigDialog(filename, NULL, &comcfg);
2679 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2680 fprintf(stderr, "Failed SetCommState\n");
2681 goto fail;
2684 if (!SetCommMask(s->hcom, EV_ERR)) {
2685 fprintf(stderr, "Failed SetCommMask\n");
2686 goto fail;
2689 cto.ReadIntervalTimeout = MAXDWORD;
2690 if (!SetCommTimeouts(s->hcom, &cto)) {
2691 fprintf(stderr, "Failed SetCommTimeouts\n");
2692 goto fail;
2695 if (!ClearCommError(s->hcom, &err, &comstat)) {
2696 fprintf(stderr, "Failed ClearCommError\n");
2697 goto fail;
2699 qemu_add_polling_cb(win_chr_poll, chr);
2700 return 0;
2702 fail:
2703 win_chr_close(chr);
2704 return -1;
2707 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2709 WinCharState *s = chr->opaque;
2710 DWORD len, ret, size, err;
2712 len = len1;
2713 ZeroMemory(&s->osend, sizeof(s->osend));
2714 s->osend.hEvent = s->hsend;
2715 while (len > 0) {
2716 if (s->hsend)
2717 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2718 else
2719 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2720 if (!ret) {
2721 err = GetLastError();
2722 if (err == ERROR_IO_PENDING) {
2723 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2724 if (ret) {
2725 buf += size;
2726 len -= size;
2727 } else {
2728 break;
2730 } else {
2731 break;
2733 } else {
2734 buf += size;
2735 len -= size;
2738 return len1 - len;
2741 static int win_chr_read_poll(CharDriverState *chr)
2743 WinCharState *s = chr->opaque;
2745 s->max_size = qemu_chr_can_read(chr);
2746 return s->max_size;
2749 static void win_chr_readfile(CharDriverState *chr)
2751 WinCharState *s = chr->opaque;
2752 int ret, err;
2753 uint8_t buf[1024];
2754 DWORD size;
2756 ZeroMemory(&s->orecv, sizeof(s->orecv));
2757 s->orecv.hEvent = s->hrecv;
2758 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2759 if (!ret) {
2760 err = GetLastError();
2761 if (err == ERROR_IO_PENDING) {
2762 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2766 if (size > 0) {
2767 qemu_chr_read(chr, buf, size);
2771 static void win_chr_read(CharDriverState *chr)
2773 WinCharState *s = chr->opaque;
2775 if (s->len > s->max_size)
2776 s->len = s->max_size;
2777 if (s->len == 0)
2778 return;
2780 win_chr_readfile(chr);
2783 static int win_chr_poll(void *opaque)
2785 CharDriverState *chr = opaque;
2786 WinCharState *s = chr->opaque;
2787 COMSTAT status;
2788 DWORD comerr;
2790 ClearCommError(s->hcom, &comerr, &status);
2791 if (status.cbInQue > 0) {
2792 s->len = status.cbInQue;
2793 win_chr_read_poll(chr);
2794 win_chr_read(chr);
2795 return 1;
2797 return 0;
2800 static CharDriverState *qemu_chr_open_win(const char *filename)
2802 CharDriverState *chr;
2803 WinCharState *s;
2805 chr = qemu_mallocz(sizeof(CharDriverState));
2806 if (!chr)
2807 return NULL;
2808 s = qemu_mallocz(sizeof(WinCharState));
2809 if (!s) {
2810 free(chr);
2811 return NULL;
2813 chr->opaque = s;
2814 chr->chr_write = win_chr_write;
2815 chr->chr_close = win_chr_close;
2817 if (win_chr_init(chr, filename) < 0) {
2818 free(s);
2819 free(chr);
2820 return NULL;
2822 qemu_chr_reset(chr);
2823 return chr;
2826 static int win_chr_pipe_poll(void *opaque)
2828 CharDriverState *chr = opaque;
2829 WinCharState *s = chr->opaque;
2830 DWORD size;
2832 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2833 if (size > 0) {
2834 s->len = size;
2835 win_chr_read_poll(chr);
2836 win_chr_read(chr);
2837 return 1;
2839 return 0;
2842 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2844 WinCharState *s = chr->opaque;
2845 OVERLAPPED ov;
2846 int ret;
2847 DWORD size;
2848 char openname[256];
2850 s->fpipe = TRUE;
2852 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2853 if (!s->hsend) {
2854 fprintf(stderr, "Failed CreateEvent\n");
2855 goto fail;
2857 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2858 if (!s->hrecv) {
2859 fprintf(stderr, "Failed CreateEvent\n");
2860 goto fail;
2863 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2864 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2865 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2866 PIPE_WAIT,
2867 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2868 if (s->hcom == INVALID_HANDLE_VALUE) {
2869 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2870 s->hcom = NULL;
2871 goto fail;
2874 ZeroMemory(&ov, sizeof(ov));
2875 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2876 ret = ConnectNamedPipe(s->hcom, &ov);
2877 if (ret) {
2878 fprintf(stderr, "Failed ConnectNamedPipe\n");
2879 goto fail;
2882 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2883 if (!ret) {
2884 fprintf(stderr, "Failed GetOverlappedResult\n");
2885 if (ov.hEvent) {
2886 CloseHandle(ov.hEvent);
2887 ov.hEvent = NULL;
2889 goto fail;
2892 if (ov.hEvent) {
2893 CloseHandle(ov.hEvent);
2894 ov.hEvent = NULL;
2896 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2897 return 0;
2899 fail:
2900 win_chr_close(chr);
2901 return -1;
2905 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2907 CharDriverState *chr;
2908 WinCharState *s;
2910 chr = qemu_mallocz(sizeof(CharDriverState));
2911 if (!chr)
2912 return NULL;
2913 s = qemu_mallocz(sizeof(WinCharState));
2914 if (!s) {
2915 free(chr);
2916 return NULL;
2918 chr->opaque = s;
2919 chr->chr_write = win_chr_write;
2920 chr->chr_close = win_chr_close;
2922 if (win_chr_pipe_init(chr, filename) < 0) {
2923 free(s);
2924 free(chr);
2925 return NULL;
2927 qemu_chr_reset(chr);
2928 return chr;
2931 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2933 CharDriverState *chr;
2934 WinCharState *s;
2936 chr = qemu_mallocz(sizeof(CharDriverState));
2937 if (!chr)
2938 return NULL;
2939 s = qemu_mallocz(sizeof(WinCharState));
2940 if (!s) {
2941 free(chr);
2942 return NULL;
2944 s->hcom = fd_out;
2945 chr->opaque = s;
2946 chr->chr_write = win_chr_write;
2947 qemu_chr_reset(chr);
2948 return chr;
2951 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2953 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2956 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2958 HANDLE fd_out;
2960 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2961 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2962 if (fd_out == INVALID_HANDLE_VALUE)
2963 return NULL;
2965 return qemu_chr_open_win_file(fd_out);
2967 #endif /* !_WIN32 */
2969 /***********************************************************/
2970 /* UDP Net console */
2972 typedef struct {
2973 int fd;
2974 struct sockaddr_in daddr;
2975 uint8_t buf[1024];
2976 int bufcnt;
2977 int bufptr;
2978 int max_size;
2979 } NetCharDriver;
2981 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2983 NetCharDriver *s = chr->opaque;
2985 return sendto(s->fd, buf, len, 0,
2986 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2989 static int udp_chr_read_poll(void *opaque)
2991 CharDriverState *chr = opaque;
2992 NetCharDriver *s = chr->opaque;
2994 s->max_size = qemu_chr_can_read(chr);
2996 /* If there were any stray characters in the queue process them
2997 * first
2999 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3000 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3001 s->bufptr++;
3002 s->max_size = qemu_chr_can_read(chr);
3004 return s->max_size;
3007 static void udp_chr_read(void *opaque)
3009 CharDriverState *chr = opaque;
3010 NetCharDriver *s = chr->opaque;
3012 if (s->max_size == 0)
3013 return;
3014 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3015 s->bufptr = s->bufcnt;
3016 if (s->bufcnt <= 0)
3017 return;
3019 s->bufptr = 0;
3020 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3021 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3022 s->bufptr++;
3023 s->max_size = qemu_chr_can_read(chr);
3027 static void udp_chr_update_read_handler(CharDriverState *chr)
3029 NetCharDriver *s = chr->opaque;
3031 if (s->fd >= 0) {
3032 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3033 udp_chr_read, NULL, chr);
3037 #ifndef _WIN32
3038 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3039 #endif
3040 int parse_host_src_port(struct sockaddr_in *haddr,
3041 struct sockaddr_in *saddr,
3042 const char *str);
3044 static CharDriverState *qemu_chr_open_udp(const char *def)
3046 CharDriverState *chr = NULL;
3047 NetCharDriver *s = NULL;
3048 int fd = -1;
3049 struct sockaddr_in saddr;
3051 chr = qemu_mallocz(sizeof(CharDriverState));
3052 if (!chr)
3053 goto return_err;
3054 s = qemu_mallocz(sizeof(NetCharDriver));
3055 if (!s)
3056 goto return_err;
3058 fd = socket(PF_INET, SOCK_DGRAM, 0);
3059 if (fd < 0) {
3060 perror("socket(PF_INET, SOCK_DGRAM)");
3061 goto return_err;
3064 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3065 printf("Could not parse: %s\n", def);
3066 goto return_err;
3069 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3071 perror("bind");
3072 goto return_err;
3075 s->fd = fd;
3076 s->bufcnt = 0;
3077 s->bufptr = 0;
3078 chr->opaque = s;
3079 chr->chr_write = udp_chr_write;
3080 chr->chr_update_read_handler = udp_chr_update_read_handler;
3081 return chr;
3083 return_err:
3084 if (chr)
3085 free(chr);
3086 if (s)
3087 free(s);
3088 if (fd >= 0)
3089 closesocket(fd);
3090 return NULL;
3093 /***********************************************************/
3094 /* TCP Net console */
3096 typedef struct {
3097 int fd, listen_fd;
3098 int connected;
3099 int max_size;
3100 int do_telnetopt;
3101 int do_nodelay;
3102 int is_unix;
3103 } TCPCharDriver;
3105 static void tcp_chr_accept(void *opaque);
3107 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3109 TCPCharDriver *s = chr->opaque;
3110 if (s->connected) {
3111 return send_all(s->fd, buf, len);
3112 } else {
3113 /* XXX: indicate an error ? */
3114 return len;
3118 static int tcp_chr_read_poll(void *opaque)
3120 CharDriverState *chr = opaque;
3121 TCPCharDriver *s = chr->opaque;
3122 if (!s->connected)
3123 return 0;
3124 s->max_size = qemu_chr_can_read(chr);
3125 return s->max_size;
3128 #define IAC 255
3129 #define IAC_BREAK 243
3130 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3131 TCPCharDriver *s,
3132 uint8_t *buf, int *size)
3134 /* Handle any telnet client's basic IAC options to satisfy char by
3135 * char mode with no echo. All IAC options will be removed from
3136 * the buf and the do_telnetopt variable will be used to track the
3137 * state of the width of the IAC information.
3139 * IAC commands come in sets of 3 bytes with the exception of the
3140 * "IAC BREAK" command and the double IAC.
3143 int i;
3144 int j = 0;
3146 for (i = 0; i < *size; i++) {
3147 if (s->do_telnetopt > 1) {
3148 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3149 /* Double IAC means send an IAC */
3150 if (j != i)
3151 buf[j] = buf[i];
3152 j++;
3153 s->do_telnetopt = 1;
3154 } else {
3155 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3156 /* Handle IAC break commands by sending a serial break */
3157 qemu_chr_event(chr, CHR_EVENT_BREAK);
3158 s->do_telnetopt++;
3160 s->do_telnetopt++;
3162 if (s->do_telnetopt >= 4) {
3163 s->do_telnetopt = 1;
3165 } else {
3166 if ((unsigned char)buf[i] == IAC) {
3167 s->do_telnetopt = 2;
3168 } else {
3169 if (j != i)
3170 buf[j] = buf[i];
3171 j++;
3175 *size = j;
3178 static void tcp_chr_read(void *opaque)
3180 CharDriverState *chr = opaque;
3181 TCPCharDriver *s = chr->opaque;
3182 uint8_t buf[1024];
3183 int len, size;
3185 if (!s->connected || s->max_size <= 0)
3186 return;
3187 len = sizeof(buf);
3188 if (len > s->max_size)
3189 len = s->max_size;
3190 size = recv(s->fd, buf, len, 0);
3191 if (size == 0) {
3192 /* connection closed */
3193 s->connected = 0;
3194 if (s->listen_fd >= 0) {
3195 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3197 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3198 closesocket(s->fd);
3199 s->fd = -1;
3200 } else if (size > 0) {
3201 if (s->do_telnetopt)
3202 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3203 if (size > 0)
3204 qemu_chr_read(chr, buf, size);
3208 static void tcp_chr_connect(void *opaque)
3210 CharDriverState *chr = opaque;
3211 TCPCharDriver *s = chr->opaque;
3213 s->connected = 1;
3214 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3215 tcp_chr_read, NULL, chr);
3216 qemu_chr_reset(chr);
3219 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3220 static void tcp_chr_telnet_init(int fd)
3222 char buf[3];
3223 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3224 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3225 send(fd, (char *)buf, 3, 0);
3226 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3227 send(fd, (char *)buf, 3, 0);
3228 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3229 send(fd, (char *)buf, 3, 0);
3230 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3231 send(fd, (char *)buf, 3, 0);
3234 static void socket_set_nodelay(int fd)
3236 int val = 1;
3237 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3240 static void tcp_chr_accept(void *opaque)
3242 CharDriverState *chr = opaque;
3243 TCPCharDriver *s = chr->opaque;
3244 struct sockaddr_in saddr;
3245 #ifndef _WIN32
3246 struct sockaddr_un uaddr;
3247 #endif
3248 struct sockaddr *addr;
3249 socklen_t len;
3250 int fd;
3252 for(;;) {
3253 #ifndef _WIN32
3254 if (s->is_unix) {
3255 len = sizeof(uaddr);
3256 addr = (struct sockaddr *)&uaddr;
3257 } else
3258 #endif
3260 len = sizeof(saddr);
3261 addr = (struct sockaddr *)&saddr;
3263 fd = accept(s->listen_fd, addr, &len);
3264 if (fd < 0 && errno != EINTR) {
3265 return;
3266 } else if (fd >= 0) {
3267 if (s->do_telnetopt)
3268 tcp_chr_telnet_init(fd);
3269 break;
3272 socket_set_nonblock(fd);
3273 if (s->do_nodelay)
3274 socket_set_nodelay(fd);
3275 s->fd = fd;
3276 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3277 tcp_chr_connect(chr);
3280 static void tcp_chr_close(CharDriverState *chr)
3282 TCPCharDriver *s = chr->opaque;
3283 if (s->fd >= 0)
3284 closesocket(s->fd);
3285 if (s->listen_fd >= 0)
3286 closesocket(s->listen_fd);
3287 qemu_free(s);
3290 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3291 int is_telnet,
3292 int is_unix)
3294 CharDriverState *chr = NULL;
3295 TCPCharDriver *s = NULL;
3296 int fd = -1, ret, err, val;
3297 int is_listen = 0;
3298 int is_waitconnect = 1;
3299 int do_nodelay = 0;
3300 const char *ptr;
3301 struct sockaddr_in saddr;
3302 #ifndef _WIN32
3303 struct sockaddr_un uaddr;
3304 #endif
3305 struct sockaddr *addr;
3306 socklen_t addrlen;
3308 #ifndef _WIN32
3309 if (is_unix) {
3310 addr = (struct sockaddr *)&uaddr;
3311 addrlen = sizeof(uaddr);
3312 if (parse_unix_path(&uaddr, host_str) < 0)
3313 goto fail;
3314 } else
3315 #endif
3317 addr = (struct sockaddr *)&saddr;
3318 addrlen = sizeof(saddr);
3319 if (parse_host_port(&saddr, host_str) < 0)
3320 goto fail;
3323 ptr = host_str;
3324 while((ptr = strchr(ptr,','))) {
3325 ptr++;
3326 if (!strncmp(ptr,"server",6)) {
3327 is_listen = 1;
3328 } else if (!strncmp(ptr,"nowait",6)) {
3329 is_waitconnect = 0;
3330 } else if (!strncmp(ptr,"nodelay",6)) {
3331 do_nodelay = 1;
3332 } else {
3333 printf("Unknown option: %s\n", ptr);
3334 goto fail;
3337 if (!is_listen)
3338 is_waitconnect = 0;
3340 chr = qemu_mallocz(sizeof(CharDriverState));
3341 if (!chr)
3342 goto fail;
3343 s = qemu_mallocz(sizeof(TCPCharDriver));
3344 if (!s)
3345 goto fail;
3347 #ifndef _WIN32
3348 if (is_unix)
3349 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3350 else
3351 #endif
3352 fd = socket(PF_INET, SOCK_STREAM, 0);
3354 if (fd < 0)
3355 goto fail;
3357 if (!is_waitconnect)
3358 socket_set_nonblock(fd);
3360 s->connected = 0;
3361 s->fd = -1;
3362 s->listen_fd = -1;
3363 s->is_unix = is_unix;
3364 s->do_nodelay = do_nodelay && !is_unix;
3366 chr->opaque = s;
3367 chr->chr_write = tcp_chr_write;
3368 chr->chr_close = tcp_chr_close;
3370 if (is_listen) {
3371 /* allow fast reuse */
3372 #ifndef _WIN32
3373 if (is_unix) {
3374 char path[109];
3375 strncpy(path, uaddr.sun_path, 108);
3376 path[108] = 0;
3377 unlink(path);
3378 } else
3379 #endif
3381 val = 1;
3382 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3385 ret = bind(fd, addr, addrlen);
3386 if (ret < 0)
3387 goto fail;
3389 ret = listen(fd, 0);
3390 if (ret < 0)
3391 goto fail;
3393 s->listen_fd = fd;
3394 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3395 if (is_telnet)
3396 s->do_telnetopt = 1;
3397 } else {
3398 for(;;) {
3399 ret = connect(fd, addr, addrlen);
3400 if (ret < 0) {
3401 err = socket_error();
3402 if (err == EINTR || err == EWOULDBLOCK) {
3403 } else if (err == EINPROGRESS) {
3404 break;
3405 #ifdef _WIN32
3406 } else if (err == WSAEALREADY) {
3407 break;
3408 #endif
3409 } else {
3410 goto fail;
3412 } else {
3413 s->connected = 1;
3414 break;
3417 s->fd = fd;
3418 socket_set_nodelay(fd);
3419 if (s->connected)
3420 tcp_chr_connect(chr);
3421 else
3422 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3425 if (is_listen && is_waitconnect) {
3426 printf("QEMU waiting for connection on: %s\n", host_str);
3427 tcp_chr_accept(chr);
3428 socket_set_nonblock(s->listen_fd);
3431 return chr;
3432 fail:
3433 if (fd >= 0)
3434 closesocket(fd);
3435 qemu_free(s);
3436 qemu_free(chr);
3437 return NULL;
3440 CharDriverState *qemu_chr_open(const char *filename)
3442 const char *p;
3444 if (!strcmp(filename, "vc")) {
3445 return text_console_init(&display_state, 0);
3446 } else if (strstart(filename, "vc:", &p)) {
3447 return text_console_init(&display_state, p);
3448 } else if (!strcmp(filename, "null")) {
3449 return qemu_chr_open_null();
3450 } else
3451 if (strstart(filename, "tcp:", &p)) {
3452 return qemu_chr_open_tcp(p, 0, 0);
3453 } else
3454 if (strstart(filename, "telnet:", &p)) {
3455 return qemu_chr_open_tcp(p, 1, 0);
3456 } else
3457 if (strstart(filename, "udp:", &p)) {
3458 return qemu_chr_open_udp(p);
3459 } else
3460 if (strstart(filename, "mon:", &p)) {
3461 CharDriverState *drv = qemu_chr_open(p);
3462 if (drv) {
3463 drv = qemu_chr_open_mux(drv);
3464 monitor_init(drv, !nographic);
3465 return drv;
3467 printf("Unable to open driver: %s\n", p);
3468 return 0;
3469 } else
3470 #ifndef _WIN32
3471 if (strstart(filename, "unix:", &p)) {
3472 return qemu_chr_open_tcp(p, 0, 1);
3473 } else if (strstart(filename, "file:", &p)) {
3474 return qemu_chr_open_file_out(p);
3475 } else if (strstart(filename, "pipe:", &p)) {
3476 return qemu_chr_open_pipe(p);
3477 } else if (!strcmp(filename, "pty")) {
3478 return qemu_chr_open_pty();
3479 } else if (!strcmp(filename, "stdio")) {
3480 return qemu_chr_open_stdio();
3481 } else
3482 #if defined(__linux__)
3483 if (strstart(filename, "/dev/parport", NULL)) {
3484 return qemu_chr_open_pp(filename);
3485 } else
3486 #endif
3487 #if defined(__linux__) || defined(__sun__)
3488 if (strstart(filename, "/dev/", NULL)) {
3489 return qemu_chr_open_tty(filename);
3490 } else
3491 #endif
3492 #else /* !_WIN32 */
3493 if (strstart(filename, "COM", NULL)) {
3494 return qemu_chr_open_win(filename);
3495 } else
3496 if (strstart(filename, "pipe:", &p)) {
3497 return qemu_chr_open_win_pipe(p);
3498 } else
3499 if (strstart(filename, "con:", NULL)) {
3500 return qemu_chr_open_win_con(filename);
3501 } else
3502 if (strstart(filename, "file:", &p)) {
3503 return qemu_chr_open_win_file_out(p);
3505 #endif
3507 return NULL;
3511 void qemu_chr_close(CharDriverState *chr)
3513 if (chr->chr_close)
3514 chr->chr_close(chr);
3515 qemu_free(chr);
3518 /***********************************************************/
3519 /* network device redirectors */
3521 __attribute__ (( unused ))
3522 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3524 int len, i, j, c;
3526 for(i=0;i<size;i+=16) {
3527 len = size - i;
3528 if (len > 16)
3529 len = 16;
3530 fprintf(f, "%08x ", i);
3531 for(j=0;j<16;j++) {
3532 if (j < len)
3533 fprintf(f, " %02x", buf[i+j]);
3534 else
3535 fprintf(f, " ");
3537 fprintf(f, " ");
3538 for(j=0;j<len;j++) {
3539 c = buf[i+j];
3540 if (c < ' ' || c > '~')
3541 c = '.';
3542 fprintf(f, "%c", c);
3544 fprintf(f, "\n");
3548 static int parse_macaddr(uint8_t *macaddr, const char *p)
3550 int i;
3551 char *last_char;
3552 long int offset;
3554 errno = 0;
3555 offset = strtol(p, &last_char, 0);
3556 if (0 == errno && '\0' == *last_char &&
3557 offset >= 0 && offset <= 0xFFFFFF) {
3558 macaddr[3] = (offset & 0xFF0000) >> 16;
3559 macaddr[4] = (offset & 0xFF00) >> 8;
3560 macaddr[5] = offset & 0xFF;
3561 return 0;
3562 } else {
3563 for(i = 0; i < 6; i++) {
3564 macaddr[i] = strtol(p, (char **)&p, 16);
3565 if (i == 5) {
3566 if (*p != '\0')
3567 return -1;
3568 } else {
3569 if (*p != ':' && *p != '-')
3570 return -1;
3571 p++;
3574 return 0;
3577 return -1;
3580 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3582 const char *p, *p1;
3583 int len;
3584 p = *pp;
3585 p1 = strchr(p, sep);
3586 if (!p1)
3587 return -1;
3588 len = p1 - p;
3589 p1++;
3590 if (buf_size > 0) {
3591 if (len > buf_size - 1)
3592 len = buf_size - 1;
3593 memcpy(buf, p, len);
3594 buf[len] = '\0';
3596 *pp = p1;
3597 return 0;
3600 int parse_host_src_port(struct sockaddr_in *haddr,
3601 struct sockaddr_in *saddr,
3602 const char *input_str)
3604 char *str = strdup(input_str);
3605 char *host_str = str;
3606 char *src_str;
3607 char *ptr;
3610 * Chop off any extra arguments at the end of the string which
3611 * would start with a comma, then fill in the src port information
3612 * if it was provided else use the "any address" and "any port".
3614 if ((ptr = strchr(str,',')))
3615 *ptr = '\0';
3617 if ((src_str = strchr(input_str,'@'))) {
3618 *src_str = '\0';
3619 src_str++;
3622 if (parse_host_port(haddr, host_str) < 0)
3623 goto fail;
3625 if (!src_str || *src_str == '\0')
3626 src_str = ":0";
3628 if (parse_host_port(saddr, src_str) < 0)
3629 goto fail;
3631 free(str);
3632 return(0);
3634 fail:
3635 free(str);
3636 return -1;
3639 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3641 char buf[512];
3642 struct hostent *he;
3643 const char *p, *r;
3644 int port;
3646 p = str;
3647 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3648 return -1;
3649 saddr->sin_family = AF_INET;
3650 if (buf[0] == '\0') {
3651 saddr->sin_addr.s_addr = 0;
3652 } else {
3653 if (isdigit(buf[0])) {
3654 if (!inet_aton(buf, &saddr->sin_addr))
3655 return -1;
3656 } else {
3657 if ((he = gethostbyname(buf)) == NULL)
3658 return - 1;
3659 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3662 port = strtol(p, (char **)&r, 0);
3663 if (r == p)
3664 return -1;
3665 saddr->sin_port = htons(port);
3666 return 0;
3669 #ifndef _WIN32
3670 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3672 const char *p;
3673 int len;
3675 len = MIN(108, strlen(str));
3676 p = strchr(str, ',');
3677 if (p)
3678 len = MIN(len, p - str);
3680 memset(uaddr, 0, sizeof(*uaddr));
3682 uaddr->sun_family = AF_UNIX;
3683 memcpy(uaddr->sun_path, str, len);
3685 return 0;
3687 #endif
3689 /* find or alloc a new VLAN */
3690 VLANState *qemu_find_vlan(int id)
3692 VLANState **pvlan, *vlan;
3693 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3694 if (vlan->id == id)
3695 return vlan;
3697 vlan = qemu_mallocz(sizeof(VLANState));
3698 if (!vlan)
3699 return NULL;
3700 vlan->id = id;
3701 vlan->next = NULL;
3702 pvlan = &first_vlan;
3703 while (*pvlan != NULL)
3704 pvlan = &(*pvlan)->next;
3705 *pvlan = vlan;
3706 return vlan;
3709 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3710 IOReadHandler *fd_read,
3711 IOCanRWHandler *fd_can_read,
3712 void *opaque)
3714 VLANClientState *vc, **pvc;
3715 vc = qemu_mallocz(sizeof(VLANClientState));
3716 if (!vc)
3717 return NULL;
3718 vc->fd_read = fd_read;
3719 vc->fd_can_read = fd_can_read;
3720 vc->opaque = opaque;
3721 vc->vlan = vlan;
3723 vc->next = NULL;
3724 pvc = &vlan->first_client;
3725 while (*pvc != NULL)
3726 pvc = &(*pvc)->next;
3727 *pvc = vc;
3728 return vc;
3731 int qemu_can_send_packet(VLANClientState *vc1)
3733 VLANState *vlan = vc1->vlan;
3734 VLANClientState *vc;
3736 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3737 if (vc != vc1) {
3738 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3739 return 1;
3742 return 0;
3745 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3747 VLANState *vlan = vc1->vlan;
3748 VLANClientState *vc;
3750 #if 0
3751 printf("vlan %d send:\n", vlan->id);
3752 hex_dump(stdout, buf, size);
3753 #endif
3754 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3755 if (vc != vc1) {
3756 vc->fd_read(vc->opaque, buf, size);
3761 #if defined(CONFIG_SLIRP)
3763 /* slirp network adapter */
3765 static int slirp_inited;
3766 static VLANClientState *slirp_vc;
3768 int slirp_can_output(void)
3770 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3773 void slirp_output(const uint8_t *pkt, int pkt_len)
3775 #if 0
3776 printf("slirp output:\n");
3777 hex_dump(stdout, pkt, pkt_len);
3778 #endif
3779 if (!slirp_vc)
3780 return;
3781 qemu_send_packet(slirp_vc, pkt, pkt_len);
3784 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3786 #if 0
3787 printf("slirp input:\n");
3788 hex_dump(stdout, buf, size);
3789 #endif
3790 slirp_input(buf, size);
3793 static int net_slirp_init(VLANState *vlan)
3795 if (!slirp_inited) {
3796 slirp_inited = 1;
3797 slirp_init();
3799 slirp_vc = qemu_new_vlan_client(vlan,
3800 slirp_receive, NULL, NULL);
3801 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3802 return 0;
3805 static void net_slirp_redir(const char *redir_str)
3807 int is_udp;
3808 char buf[256], *r;
3809 const char *p;
3810 struct in_addr guest_addr;
3811 int host_port, guest_port;
3813 if (!slirp_inited) {
3814 slirp_inited = 1;
3815 slirp_init();
3818 p = redir_str;
3819 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3820 goto fail;
3821 if (!strcmp(buf, "tcp")) {
3822 is_udp = 0;
3823 } else if (!strcmp(buf, "udp")) {
3824 is_udp = 1;
3825 } else {
3826 goto fail;
3829 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3830 goto fail;
3831 host_port = strtol(buf, &r, 0);
3832 if (r == buf)
3833 goto fail;
3835 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3836 goto fail;
3837 if (buf[0] == '\0') {
3838 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3840 if (!inet_aton(buf, &guest_addr))
3841 goto fail;
3843 guest_port = strtol(p, &r, 0);
3844 if (r == p)
3845 goto fail;
3847 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3848 fprintf(stderr, "qemu: could not set up redirection\n");
3849 exit(1);
3851 return;
3852 fail:
3853 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3854 exit(1);
3857 #ifndef _WIN32
3859 char smb_dir[1024];
3861 static void erase_dir(char *dir_name)
3863 DIR *d;
3864 struct dirent *de;
3865 char filename[1024];
3867 /* erase all the files in the directory */
3868 if ((d = opendir(dir_name)) != 0) {
3869 for(;;) {
3870 de = readdir(d);
3871 if (!de)
3872 break;
3873 if (strcmp(de->d_name, ".") != 0 &&
3874 strcmp(de->d_name, "..") != 0) {
3875 snprintf(filename, sizeof(filename), "%s/%s",
3876 smb_dir, de->d_name);
3877 if (unlink(filename) != 0) /* is it a directory? */
3878 erase_dir(filename);
3881 closedir(d);
3882 rmdir(dir_name);
3886 /* automatic user mode samba server configuration */
3887 static void smb_exit(void)
3889 erase_dir(smb_dir);
3892 /* automatic user mode samba server configuration */
3893 static void net_slirp_smb(const char *exported_dir)
3895 char smb_conf[1024];
3896 char smb_cmdline[1024];
3897 FILE *f;
3899 if (!slirp_inited) {
3900 slirp_inited = 1;
3901 slirp_init();
3904 /* XXX: better tmp dir construction */
3905 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3906 if (mkdir(smb_dir, 0700) < 0) {
3907 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3908 exit(1);
3910 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3912 f = fopen(smb_conf, "w");
3913 if (!f) {
3914 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3915 exit(1);
3917 fprintf(f,
3918 "[global]\n"
3919 "private dir=%s\n"
3920 "smb ports=0\n"
3921 "socket address=127.0.0.1\n"
3922 "pid directory=%s\n"
3923 "lock directory=%s\n"
3924 "log file=%s/log.smbd\n"
3925 "smb passwd file=%s/smbpasswd\n"
3926 "security = share\n"
3927 "[qemu]\n"
3928 "path=%s\n"
3929 "read only=no\n"
3930 "guest ok=yes\n",
3931 smb_dir,
3932 smb_dir,
3933 smb_dir,
3934 smb_dir,
3935 smb_dir,
3936 exported_dir
3938 fclose(f);
3939 atexit(smb_exit);
3941 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3942 SMBD_COMMAND, smb_conf);
3944 slirp_add_exec(0, smb_cmdline, 4, 139);
3947 #endif /* !defined(_WIN32) */
3948 void do_info_slirp(void)
3950 slirp_stats();
3953 #endif /* CONFIG_SLIRP */
3955 #if !defined(_WIN32)
3957 typedef struct TAPState {
3958 VLANClientState *vc;
3959 int fd;
3960 char down_script[1024];
3961 int no_poll;
3962 } TAPState;
3964 static int tap_read_poll(void *opaque)
3966 TAPState *s = opaque;
3967 return (!s->no_poll);
3970 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3972 TAPState *s = opaque;
3973 int ret;
3974 for(;;) {
3975 ret = write(s->fd, buf, size);
3976 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3977 } else {
3978 break;
3983 static void tap_send(void *opaque)
3985 TAPState *s = opaque;
3986 uint8_t buf[4096];
3987 int size;
3989 #ifdef __sun__
3990 struct strbuf sbuf;
3991 int f = 0;
3992 sbuf.maxlen = sizeof(buf);
3993 sbuf.buf = buf;
3994 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3995 #else
3996 size = read(s->fd, buf, sizeof(buf));
3997 #endif
3998 if (size > 0) {
3999 qemu_send_packet(s->vc, buf, size);
4003 int hack_around_tap(void *opaque)
4005 VLANClientState *vc = opaque;
4006 TAPState *ts = vc->opaque;
4008 if (vc->fd_read != tap_receive)
4009 return -1;
4011 if (ts) {
4012 ts->no_poll = 1;
4013 return ts->fd;
4016 return -1;
4019 /* fd support */
4021 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4023 TAPState *s;
4025 s = qemu_mallocz(sizeof(TAPState));
4026 if (!s)
4027 return NULL;
4028 s->fd = fd;
4029 s->no_poll = 0;
4030 enable_sigio_timer(fd);
4031 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4032 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4033 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4034 return s;
4037 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4038 static int tap_open(char *ifname, int ifname_size)
4040 int fd;
4041 char *dev;
4042 struct stat s;
4044 TFR(fd = open("/dev/tap", O_RDWR));
4045 if (fd < 0) {
4046 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4047 return -1;
4050 fstat(fd, &s);
4051 dev = devname(s.st_rdev, S_IFCHR);
4052 pstrcpy(ifname, ifname_size, dev);
4054 fcntl(fd, F_SETFL, O_NONBLOCK);
4055 return fd;
4057 #elif defined(__sun__)
4058 #define TUNNEWPPA (('T'<<16) | 0x0001)
4060 * Allocate TAP device, returns opened fd.
4061 * Stores dev name in the first arg(must be large enough).
4063 int tap_alloc(char *dev)
4065 int tap_fd, if_fd, ppa = -1;
4066 static int ip_fd = 0;
4067 char *ptr;
4069 static int arp_fd = 0;
4070 int ip_muxid, arp_muxid;
4071 struct strioctl strioc_if, strioc_ppa;
4072 int link_type = I_PLINK;;
4073 struct lifreq ifr;
4074 char actual_name[32] = "";
4076 memset(&ifr, 0x0, sizeof(ifr));
4078 if( *dev ){
4079 ptr = dev;
4080 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4081 ppa = atoi(ptr);
4084 /* Check if IP device was opened */
4085 if( ip_fd )
4086 close(ip_fd);
4088 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4089 if (ip_fd < 0) {
4090 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4091 return -1;
4094 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4095 if (tap_fd < 0) {
4096 syslog(LOG_ERR, "Can't open /dev/tap");
4097 return -1;
4100 /* Assign a new PPA and get its unit number. */
4101 strioc_ppa.ic_cmd = TUNNEWPPA;
4102 strioc_ppa.ic_timout = 0;
4103 strioc_ppa.ic_len = sizeof(ppa);
4104 strioc_ppa.ic_dp = (char *)&ppa;
4105 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4106 syslog (LOG_ERR, "Can't assign new interface");
4108 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4109 if (if_fd < 0) {
4110 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4111 return -1;
4113 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4114 syslog(LOG_ERR, "Can't push IP module");
4115 return -1;
4118 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4119 syslog(LOG_ERR, "Can't get flags\n");
4121 snprintf (actual_name, 32, "tap%d", ppa);
4122 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4124 ifr.lifr_ppa = ppa;
4125 /* Assign ppa according to the unit number returned by tun device */
4127 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4128 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4129 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4130 syslog (LOG_ERR, "Can't get flags\n");
4131 /* Push arp module to if_fd */
4132 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4133 syslog (LOG_ERR, "Can't push ARP module (2)");
4135 /* Push arp module to ip_fd */
4136 if (ioctl (ip_fd, I_POP, NULL) < 0)
4137 syslog (LOG_ERR, "I_POP failed\n");
4138 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4139 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4140 /* Open arp_fd */
4141 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4142 if (arp_fd < 0)
4143 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4145 /* Set ifname to arp */
4146 strioc_if.ic_cmd = SIOCSLIFNAME;
4147 strioc_if.ic_timout = 0;
4148 strioc_if.ic_len = sizeof(ifr);
4149 strioc_if.ic_dp = (char *)&ifr;
4150 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4151 syslog (LOG_ERR, "Can't set ifname to arp\n");
4154 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4155 syslog(LOG_ERR, "Can't link TAP device to IP");
4156 return -1;
4159 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4160 syslog (LOG_ERR, "Can't link TAP device to ARP");
4162 close (if_fd);
4164 memset(&ifr, 0x0, sizeof(ifr));
4165 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4166 ifr.lifr_ip_muxid = ip_muxid;
4167 ifr.lifr_arp_muxid = arp_muxid;
4169 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4171 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4172 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4173 syslog (LOG_ERR, "Can't set multiplexor id");
4176 sprintf(dev, "tap%d", ppa);
4177 return tap_fd;
4180 static int tap_open(char *ifname, int ifname_size)
4182 char dev[10]="";
4183 int fd;
4184 if( (fd = tap_alloc(dev)) < 0 ){
4185 fprintf(stderr, "Cannot allocate TAP device\n");
4186 return -1;
4188 pstrcpy(ifname, ifname_size, dev);
4189 fcntl(fd, F_SETFL, O_NONBLOCK);
4190 return fd;
4192 #else
4193 static int tap_open(char *ifname, int ifname_size)
4195 struct ifreq ifr;
4196 int fd, ret;
4198 TFR(fd = open("/dev/net/tun", O_RDWR));
4199 if (fd < 0) {
4200 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4201 return -1;
4203 memset(&ifr, 0, sizeof(ifr));
4204 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4205 if (ifname[0] != '\0')
4206 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4207 else
4208 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4209 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4210 if (ret != 0) {
4211 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4212 close(fd);
4213 return -1;
4215 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4216 fcntl(fd, F_SETFL, O_NONBLOCK);
4217 return fd;
4219 #endif
4221 static int launch_script(const char *setup_script, const char *ifname, int fd)
4223 int pid, status;
4224 char *args[3];
4225 char **parg;
4227 /* try to launch network script */
4228 pid = fork();
4229 if (pid >= 0) {
4230 if (pid == 0) {
4231 int open_max = sysconf (_SC_OPEN_MAX), i;
4232 for (i = 0; i < open_max; i++)
4233 if (i != STDIN_FILENO &&
4234 i != STDOUT_FILENO &&
4235 i != STDERR_FILENO &&
4236 i != fd)
4237 close(i);
4239 parg = args;
4240 *parg++ = (char *)setup_script;
4241 *parg++ = (char *)ifname;
4242 *parg++ = NULL;
4243 execv(setup_script, args);
4244 _exit(1);
4246 while (waitpid(pid, &status, 0) != pid);
4247 if (!WIFEXITED(status) ||
4248 WEXITSTATUS(status) != 0) {
4249 fprintf(stderr, "%s: could not launch network script\n",
4250 setup_script);
4251 return -1;
4254 return 0;
4257 static int net_tap_init(VLANState *vlan, const char *ifname1,
4258 const char *setup_script, const char *down_script)
4260 TAPState *s;
4261 int fd;
4262 char ifname[128];
4264 if (ifname1 != NULL)
4265 pstrcpy(ifname, sizeof(ifname), ifname1);
4266 else
4267 ifname[0] = '\0';
4268 TFR(fd = tap_open(ifname, sizeof(ifname)));
4269 if (fd < 0)
4270 return -1;
4272 if (!setup_script || !strcmp(setup_script, "no"))
4273 setup_script = "";
4274 if (setup_script[0] != '\0') {
4275 if (launch_script(setup_script, ifname, fd))
4276 return -1;
4278 s = net_tap_fd_init(vlan, fd);
4279 if (!s)
4280 return -1;
4281 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4282 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4283 if (down_script && strcmp(down_script, "no"))
4284 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4285 return 0;
4288 #endif /* !_WIN32 */
4290 /* network connection */
4291 typedef struct NetSocketState {
4292 VLANClientState *vc;
4293 int fd;
4294 int state; /* 0 = getting length, 1 = getting data */
4295 int index;
4296 int packet_len;
4297 uint8_t buf[4096];
4298 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4299 } NetSocketState;
4301 typedef struct NetSocketListenState {
4302 VLANState *vlan;
4303 int fd;
4304 } NetSocketListenState;
4306 /* XXX: we consider we can send the whole packet without blocking */
4307 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4309 NetSocketState *s = opaque;
4310 uint32_t len;
4311 len = htonl(size);
4313 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4314 send_all(s->fd, buf, size);
4317 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4319 NetSocketState *s = opaque;
4320 sendto(s->fd, buf, size, 0,
4321 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4324 static void net_socket_send(void *opaque)
4326 NetSocketState *s = opaque;
4327 int l, size, err;
4328 uint8_t buf1[4096];
4329 const uint8_t *buf;
4331 size = recv(s->fd, buf1, sizeof(buf1), 0);
4332 if (size < 0) {
4333 err = socket_error();
4334 if (err != EWOULDBLOCK)
4335 goto eoc;
4336 } else if (size == 0) {
4337 /* end of connection */
4338 eoc:
4339 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4340 closesocket(s->fd);
4341 return;
4343 buf = buf1;
4344 while (size > 0) {
4345 /* reassemble a packet from the network */
4346 switch(s->state) {
4347 case 0:
4348 l = 4 - s->index;
4349 if (l > size)
4350 l = size;
4351 memcpy(s->buf + s->index, buf, l);
4352 buf += l;
4353 size -= l;
4354 s->index += l;
4355 if (s->index == 4) {
4356 /* got length */
4357 s->packet_len = ntohl(*(uint32_t *)s->buf);
4358 s->index = 0;
4359 s->state = 1;
4361 break;
4362 case 1:
4363 l = s->packet_len - s->index;
4364 if (l > size)
4365 l = size;
4366 memcpy(s->buf + s->index, buf, l);
4367 s->index += l;
4368 buf += l;
4369 size -= l;
4370 if (s->index >= s->packet_len) {
4371 qemu_send_packet(s->vc, s->buf, s->packet_len);
4372 s->index = 0;
4373 s->state = 0;
4375 break;
4380 static void net_socket_send_dgram(void *opaque)
4382 NetSocketState *s = opaque;
4383 int size;
4385 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4386 if (size < 0)
4387 return;
4388 if (size == 0) {
4389 /* end of connection */
4390 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4391 return;
4393 qemu_send_packet(s->vc, s->buf, size);
4396 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4398 struct ip_mreq imr;
4399 int fd;
4400 int val, ret;
4401 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4402 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4403 inet_ntoa(mcastaddr->sin_addr),
4404 (int)ntohl(mcastaddr->sin_addr.s_addr));
4405 return -1;
4408 fd = socket(PF_INET, SOCK_DGRAM, 0);
4409 if (fd < 0) {
4410 perror("socket(PF_INET, SOCK_DGRAM)");
4411 return -1;
4414 val = 1;
4415 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4416 (const char *)&val, sizeof(val));
4417 if (ret < 0) {
4418 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4419 goto fail;
4422 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4423 if (ret < 0) {
4424 perror("bind");
4425 goto fail;
4428 /* Add host to multicast group */
4429 imr.imr_multiaddr = mcastaddr->sin_addr;
4430 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4432 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4433 (const char *)&imr, sizeof(struct ip_mreq));
4434 if (ret < 0) {
4435 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4436 goto fail;
4439 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4440 val = 1;
4441 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4442 (const char *)&val, sizeof(val));
4443 if (ret < 0) {
4444 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4445 goto fail;
4448 socket_set_nonblock(fd);
4449 return fd;
4450 fail:
4451 if (fd >= 0)
4452 closesocket(fd);
4453 return -1;
4456 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4457 int is_connected)
4459 struct sockaddr_in saddr;
4460 int newfd;
4461 socklen_t saddr_len;
4462 NetSocketState *s;
4464 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4465 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4466 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4469 if (is_connected) {
4470 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4471 /* must be bound */
4472 if (saddr.sin_addr.s_addr==0) {
4473 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4474 fd);
4475 return NULL;
4477 /* clone dgram socket */
4478 newfd = net_socket_mcast_create(&saddr);
4479 if (newfd < 0) {
4480 /* error already reported by net_socket_mcast_create() */
4481 close(fd);
4482 return NULL;
4484 /* clone newfd to fd, close newfd */
4485 dup2(newfd, fd);
4486 close(newfd);
4488 } else {
4489 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4490 fd, strerror(errno));
4491 return NULL;
4495 s = qemu_mallocz(sizeof(NetSocketState));
4496 if (!s)
4497 return NULL;
4498 s->fd = fd;
4500 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4501 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4503 /* mcast: save bound address as dst */
4504 if (is_connected) s->dgram_dst=saddr;
4506 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4507 "socket: fd=%d (%s mcast=%s:%d)",
4508 fd, is_connected? "cloned" : "",
4509 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4510 return s;
4513 static void net_socket_connect(void *opaque)
4515 NetSocketState *s = opaque;
4516 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4519 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4520 int is_connected)
4522 NetSocketState *s;
4523 s = qemu_mallocz(sizeof(NetSocketState));
4524 if (!s)
4525 return NULL;
4526 s->fd = fd;
4527 s->vc = qemu_new_vlan_client(vlan,
4528 net_socket_receive, NULL, s);
4529 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4530 "socket: fd=%d", fd);
4531 if (is_connected) {
4532 net_socket_connect(s);
4533 } else {
4534 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4536 return s;
4539 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4540 int is_connected)
4542 int so_type=-1, optlen=sizeof(so_type);
4544 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4545 (socklen_t *)&optlen)< 0) {
4546 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4547 return NULL;
4549 switch(so_type) {
4550 case SOCK_DGRAM:
4551 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4552 case SOCK_STREAM:
4553 return net_socket_fd_init_stream(vlan, fd, is_connected);
4554 default:
4555 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4556 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4557 return net_socket_fd_init_stream(vlan, fd, is_connected);
4559 return NULL;
4562 static void net_socket_accept(void *opaque)
4564 NetSocketListenState *s = opaque;
4565 NetSocketState *s1;
4566 struct sockaddr_in saddr;
4567 socklen_t len;
4568 int fd;
4570 for(;;) {
4571 len = sizeof(saddr);
4572 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4573 if (fd < 0 && errno != EINTR) {
4574 return;
4575 } else if (fd >= 0) {
4576 break;
4579 s1 = net_socket_fd_init(s->vlan, fd, 1);
4580 if (!s1) {
4581 closesocket(fd);
4582 } else {
4583 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4584 "socket: connection from %s:%d",
4585 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4589 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4591 NetSocketListenState *s;
4592 int fd, val, ret;
4593 struct sockaddr_in saddr;
4595 if (parse_host_port(&saddr, host_str) < 0)
4596 return -1;
4598 s = qemu_mallocz(sizeof(NetSocketListenState));
4599 if (!s)
4600 return -1;
4602 fd = socket(PF_INET, SOCK_STREAM, 0);
4603 if (fd < 0) {
4604 perror("socket");
4605 return -1;
4607 socket_set_nonblock(fd);
4609 /* allow fast reuse */
4610 val = 1;
4611 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4613 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4614 if (ret < 0) {
4615 perror("bind");
4616 return -1;
4618 ret = listen(fd, 0);
4619 if (ret < 0) {
4620 perror("listen");
4621 return -1;
4623 s->vlan = vlan;
4624 s->fd = fd;
4625 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4626 return 0;
4629 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4631 NetSocketState *s;
4632 int fd, connected, ret, err;
4633 struct sockaddr_in saddr;
4635 if (parse_host_port(&saddr, host_str) < 0)
4636 return -1;
4638 fd = socket(PF_INET, SOCK_STREAM, 0);
4639 if (fd < 0) {
4640 perror("socket");
4641 return -1;
4643 socket_set_nonblock(fd);
4645 connected = 0;
4646 for(;;) {
4647 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4648 if (ret < 0) {
4649 err = socket_error();
4650 if (err == EINTR || err == EWOULDBLOCK) {
4651 } else if (err == EINPROGRESS) {
4652 break;
4653 #ifdef _WIN32
4654 } else if (err == WSAEALREADY) {
4655 break;
4656 #endif
4657 } else {
4658 perror("connect");
4659 closesocket(fd);
4660 return -1;
4662 } else {
4663 connected = 1;
4664 break;
4667 s = net_socket_fd_init(vlan, fd, connected);
4668 if (!s)
4669 return -1;
4670 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4671 "socket: connect to %s:%d",
4672 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4673 return 0;
4676 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4678 NetSocketState *s;
4679 int fd;
4680 struct sockaddr_in saddr;
4682 if (parse_host_port(&saddr, host_str) < 0)
4683 return -1;
4686 fd = net_socket_mcast_create(&saddr);
4687 if (fd < 0)
4688 return -1;
4690 s = net_socket_fd_init(vlan, fd, 0);
4691 if (!s)
4692 return -1;
4694 s->dgram_dst = saddr;
4696 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4697 "socket: mcast=%s:%d",
4698 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4699 return 0;
4703 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4705 char *q;
4707 q = buf;
4708 while (*p != '\0' && *p != '=') {
4709 if (q && (q - buf) < buf_size - 1)
4710 *q++ = *p;
4711 p++;
4713 if (q)
4714 *q = '\0';
4716 return p;
4719 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4721 char *q;
4723 q = buf;
4724 while (*p != '\0') {
4725 if (*p == ',') {
4726 if (*(p + 1) != ',')
4727 break;
4728 p++;
4730 if (q && (q - buf) < buf_size - 1)
4731 *q++ = *p;
4732 p++;
4734 if (q)
4735 *q = '\0';
4737 return p;
4740 int get_param_value(char *buf, int buf_size,
4741 const char *tag, const char *str)
4743 const char *p;
4744 char option[128];
4746 p = str;
4747 for(;;) {
4748 p = get_opt_name(option, sizeof(option), p);
4749 if (*p != '=')
4750 break;
4751 p++;
4752 if (!strcmp(tag, option)) {
4753 (void)get_opt_value(buf, buf_size, p);
4754 return strlen(buf);
4755 } else {
4756 p = get_opt_value(NULL, 0, p);
4758 if (*p != ',')
4759 break;
4760 p++;
4762 return 0;
4765 int check_params(char *buf, int buf_size,
4766 char **params, const char *str)
4768 const char *p;
4769 int i;
4771 p = str;
4772 for(;;) {
4773 p = get_opt_name(buf, buf_size, p);
4774 if (*p != '=')
4775 return -1;
4776 p++;
4777 for(i = 0; params[i] != NULL; i++)
4778 if (!strcmp(params[i], buf))
4779 break;
4780 if (params[i] == NULL)
4781 return -1;
4782 p = get_opt_value(NULL, 0, p);
4783 if (*p != ',')
4784 break;
4785 p++;
4787 return 0;
4790 static int nic_get_free_idx(void)
4792 int index;
4794 for (index = 0; index < MAX_NICS; index++)
4795 if (!nd_table[index].used)
4796 return index;
4797 return -1;
4800 int net_client_init(const char *str)
4802 const char *p;
4803 char *q;
4804 char device[64];
4805 char buf[1024];
4806 int vlan_id, ret;
4807 VLANState *vlan;
4809 p = str;
4810 q = device;
4811 while (*p != '\0' && *p != ',') {
4812 if ((q - device) < sizeof(device) - 1)
4813 *q++ = *p;
4814 p++;
4816 *q = '\0';
4817 if (*p == ',')
4818 p++;
4819 vlan_id = 0;
4820 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4821 vlan_id = strtol(buf, NULL, 0);
4823 vlan = qemu_find_vlan(vlan_id);
4824 if (!vlan) {
4825 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4826 return -1;
4828 if (!strcmp(device, "nic")) {
4829 NICInfo *nd;
4830 uint8_t *macaddr;
4831 int idx = nic_get_free_idx();
4833 if (idx == -1 || nb_nics >= MAX_NICS) {
4834 fprintf(stderr, "Too Many NICs\n");
4835 return -1;
4837 nd = &nd_table[idx];
4838 macaddr = nd->macaddr;
4839 macaddr[0] = 0x52;
4840 macaddr[1] = 0x54;
4841 macaddr[2] = 0x00;
4842 macaddr[3] = 0x12;
4843 macaddr[4] = 0x34;
4844 macaddr[5] = 0x56 + idx;
4846 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4847 if (parse_macaddr(macaddr, buf) < 0) {
4848 fprintf(stderr, "invalid syntax for ethernet address\n");
4849 return -1;
4852 if (get_param_value(buf, sizeof(buf), "model", p)) {
4853 nd->model = strdup(buf);
4855 nd->vlan = vlan;
4856 nd->used = 1;
4857 nb_nics++;
4858 vlan->nb_guest_devs++;
4859 ret = idx;
4860 } else
4861 if (!strcmp(device, "none")) {
4862 /* does nothing. It is needed to signal that no network cards
4863 are wanted */
4864 ret = 0;
4865 } else
4866 #ifdef CONFIG_SLIRP
4867 if (!strcmp(device, "user")) {
4868 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4869 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4871 vlan->nb_host_devs++;
4872 ret = net_slirp_init(vlan);
4873 } else
4874 #endif
4875 #ifdef _WIN32
4876 if (!strcmp(device, "tap")) {
4877 char ifname[64];
4878 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4879 fprintf(stderr, "tap: no interface name\n");
4880 return -1;
4882 vlan->nb_host_devs++;
4883 ret = tap_win32_init(vlan, ifname);
4884 } else
4885 #else
4886 if (!strcmp(device, "tap")) {
4887 char ifname[64];
4888 char setup_script[1024], down_script[1024];
4889 int fd;
4890 vlan->nb_host_devs++;
4891 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4892 fd = strtol(buf, NULL, 0);
4893 ret = -1;
4894 if (net_tap_fd_init(vlan, fd))
4895 ret = 0;
4896 } else {
4897 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4898 ifname[0] = '\0';
4900 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4901 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4903 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4904 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4906 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4908 } else
4909 #endif
4910 if (!strcmp(device, "socket")) {
4911 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4912 int fd;
4913 fd = strtol(buf, NULL, 0);
4914 ret = -1;
4915 if (net_socket_fd_init(vlan, fd, 1))
4916 ret = 0;
4917 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4918 ret = net_socket_listen_init(vlan, buf);
4919 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4920 ret = net_socket_connect_init(vlan, buf);
4921 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4922 ret = net_socket_mcast_init(vlan, buf);
4923 } else {
4924 fprintf(stderr, "Unknown socket options: %s\n", p);
4925 return -1;
4927 vlan->nb_host_devs++;
4928 } else
4930 fprintf(stderr, "Unknown network device: %s\n", device);
4931 return -1;
4933 if (ret < 0) {
4934 fprintf(stderr, "Could not initialize device '%s'\n", device);
4937 return ret;
4940 void net_client_uninit(NICInfo *nd)
4942 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
4943 nb_nics--;
4944 nd->used = 0;
4945 free(nd->model);
4948 void do_info_network(void)
4950 VLANState *vlan;
4951 VLANClientState *vc;
4953 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4954 term_printf("VLAN %d devices:\n", vlan->id);
4955 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4956 term_printf(" %s\n", vc->info_str);
4960 #define HD_ALIAS "index=%d,media=disk"
4961 #ifdef TARGET_PPC
4962 #define CDROM_ALIAS "index=1,media=cdrom"
4963 #else
4964 #define CDROM_ALIAS "index=2,media=cdrom"
4965 #endif
4966 #define FD_ALIAS "index=%d,if=floppy"
4967 #define PFLASH_ALIAS "if=pflash"
4968 #define MTD_ALIAS "if=mtd"
4969 #define SD_ALIAS "index=0,if=sd"
4971 static int drive_opt_get_free_idx(void)
4973 int index;
4975 for (index = 0; index < MAX_DRIVES; index++)
4976 if (!drives_opt[index].used) {
4977 drives_opt[index].used = 1;
4978 return index;
4981 return -1;
4984 static int drive_get_free_idx(void)
4986 int index;
4988 for (index = 0; index < MAX_DRIVES; index++)
4989 if (!drives_table[index].used) {
4990 drives_table[index].used = 1;
4991 return index;
4994 return -1;
4997 int drive_add(const char *file, const char *fmt, ...)
4999 va_list ap;
5000 int index = drive_opt_get_free_idx();
5002 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5003 fprintf(stderr, "qemu: too many drives\n");
5004 return -1;
5007 drives_opt[index].file = file;
5008 va_start(ap, fmt);
5009 vsnprintf(drives_opt[index].opt,
5010 sizeof(drives_opt[0].opt), fmt, ap);
5011 va_end(ap);
5013 nb_drives_opt++;
5014 return index;
5017 void drive_remove(int index)
5019 drives_opt[index].used = 0;
5020 nb_drives_opt--;
5023 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5025 int index;
5027 /* seek interface, bus and unit */
5029 for (index = 0; index < MAX_DRIVES; index++)
5030 if (drives_table[index].type == type &&
5031 drives_table[index].bus == bus &&
5032 drives_table[index].unit == unit &&
5033 drives_table[index].used)
5034 return index;
5036 return -1;
5039 int drive_get_max_bus(BlockInterfaceType type)
5041 int max_bus;
5042 int index;
5044 max_bus = -1;
5045 for (index = 0; index < nb_drives; index++) {
5046 if(drives_table[index].type == type &&
5047 drives_table[index].bus > max_bus)
5048 max_bus = drives_table[index].bus;
5050 return max_bus;
5053 void drive_uninit(BlockDriverState *bdrv)
5055 int i;
5057 for (i = 0; i < MAX_DRIVES; i++)
5058 if (drives_table[i].bdrv == bdrv) {
5059 drives_table[i].bdrv = NULL;
5060 drives_table[i].used = 0;
5061 drive_remove(drives_table[i].drive_opt_idx);
5062 nb_drives--;
5063 break;
5067 int drive_init(struct drive_opt *arg, int snapshot,
5068 void *opaque)
5070 QEMUMachine *machine = opaque;
5071 char buf[128];
5072 char file[1024];
5073 char devname[128];
5074 const char *mediastr = "";
5075 BlockInterfaceType type;
5076 enum { MEDIA_DISK, MEDIA_CDROM } media;
5077 int bus_id, unit_id;
5078 int cyls, heads, secs, translation;
5079 BlockDriverState *bdrv;
5080 int max_devs;
5081 int index;
5082 int cache;
5083 int bdrv_flags;
5084 int drives_table_idx;
5085 char *str = arg->opt;
5086 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5087 "secs", "trans", "media", "snapshot", "file",
5088 "cache", "boot", NULL };
5090 if (check_params(buf, sizeof(buf), params, str) < 0) {
5091 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5092 buf, str);
5093 return -1;
5096 file[0] = 0;
5097 cyls = heads = secs = 0;
5098 bus_id = 0;
5099 unit_id = -1;
5100 translation = BIOS_ATA_TRANSLATION_AUTO;
5101 index = -1;
5102 cache = 1;
5104 if (!strcmp(machine->name, "realview") ||
5105 !strcmp(machine->name, "SS-5") ||
5106 !strcmp(machine->name, "SS-10") ||
5107 !strcmp(machine->name, "SS-600MP") ||
5108 !strcmp(machine->name, "versatilepb") ||
5109 !strcmp(machine->name, "versatileab")) {
5110 type = IF_SCSI;
5111 max_devs = MAX_SCSI_DEVS;
5112 strcpy(devname, "scsi");
5113 } else {
5114 type = IF_IDE;
5115 max_devs = MAX_IDE_DEVS;
5116 strcpy(devname, "ide");
5118 media = MEDIA_DISK;
5120 /* extract parameters */
5122 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5123 bus_id = strtol(buf, NULL, 0);
5124 if (bus_id < 0) {
5125 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5126 return -1;
5130 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5131 unit_id = strtol(buf, NULL, 0);
5132 if (unit_id < 0) {
5133 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5134 return -1;
5138 if (get_param_value(buf, sizeof(buf), "if", str)) {
5139 strncpy(devname, buf, sizeof(devname));
5140 if (!strcmp(buf, "ide")) {
5141 type = IF_IDE;
5142 max_devs = MAX_IDE_DEVS;
5143 } else if (!strcmp(buf, "scsi")) {
5144 type = IF_SCSI;
5145 max_devs = MAX_SCSI_DEVS;
5146 } else if (!strcmp(buf, "floppy")) {
5147 type = IF_FLOPPY;
5148 max_devs = 0;
5149 } else if (!strcmp(buf, "pflash")) {
5150 type = IF_PFLASH;
5151 max_devs = 0;
5152 } else if (!strcmp(buf, "mtd")) {
5153 type = IF_MTD;
5154 max_devs = 0;
5155 } else if (!strcmp(buf, "sd")) {
5156 type = IF_SD;
5157 max_devs = 0;
5158 } else if (!strcmp(buf, "virtio")) {
5159 type = IF_VIRTIO;
5160 max_devs = 0;
5161 } else {
5162 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5163 return -1;
5167 if (get_param_value(buf, sizeof(buf), "index", str)) {
5168 index = strtol(buf, NULL, 0);
5169 if (index < 0) {
5170 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5171 return -1;
5175 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5176 cyls = strtol(buf, NULL, 0);
5179 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5180 heads = strtol(buf, NULL, 0);
5183 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5184 secs = strtol(buf, NULL, 0);
5187 if (cyls || heads || secs) {
5188 if (cyls < 1 || cyls > 16383) {
5189 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5190 return -1;
5192 if (heads < 1 || heads > 16) {
5193 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5194 return -1;
5196 if (secs < 1 || secs > 63) {
5197 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5198 return -1;
5202 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5203 if (!cyls) {
5204 fprintf(stderr,
5205 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5206 str);
5207 return -1;
5209 if (!strcmp(buf, "none"))
5210 translation = BIOS_ATA_TRANSLATION_NONE;
5211 else if (!strcmp(buf, "lba"))
5212 translation = BIOS_ATA_TRANSLATION_LBA;
5213 else if (!strcmp(buf, "auto"))
5214 translation = BIOS_ATA_TRANSLATION_AUTO;
5215 else {
5216 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5217 return -1;
5221 if (get_param_value(buf, sizeof(buf), "media", str)) {
5222 if (!strcmp(buf, "disk")) {
5223 media = MEDIA_DISK;
5224 } else if (!strcmp(buf, "cdrom")) {
5225 if (cyls || secs || heads) {
5226 fprintf(stderr,
5227 "qemu: '%s' invalid physical CHS format\n", str);
5228 return -1;
5230 media = MEDIA_CDROM;
5231 } else {
5232 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5233 return -1;
5237 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5238 if (!strcmp(buf, "on"))
5239 snapshot = 1;
5240 else if (!strcmp(buf, "off"))
5241 snapshot = 0;
5242 else {
5243 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5244 return -1;
5248 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5249 if (!strcmp(buf, "off"))
5250 cache = 0;
5251 else if (!strcmp(buf, "on"))
5252 cache = 1;
5253 else {
5254 fprintf(stderr, "qemu: invalid cache option\n");
5255 return -1;
5259 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5260 if (!strcmp(buf, "on")) {
5261 if (extboot_drive != -1) {
5262 fprintf(stderr, "qemu: two bootable drives specified\n");
5263 return -1;
5265 extboot_drive = nb_drives;
5266 } else if (strcmp(buf, "off")) {
5267 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5268 return -1;
5272 if (arg->file == NULL)
5273 get_param_value(file, sizeof(file), "file", str);
5274 else
5275 pstrcpy(file, sizeof(file), arg->file);
5277 /* compute bus and unit according index */
5279 if (index != -1) {
5280 if (bus_id != 0 || unit_id != -1) {
5281 fprintf(stderr,
5282 "qemu: '%s' index cannot be used with bus and unit\n", str);
5283 return -1;
5285 if (max_devs == 0)
5287 unit_id = index;
5288 bus_id = 0;
5289 } else {
5290 unit_id = index % max_devs;
5291 bus_id = index / max_devs;
5295 /* if user doesn't specify a unit_id,
5296 * try to find the first free
5299 if (unit_id == -1) {
5300 unit_id = 0;
5301 while (drive_get_index(type, bus_id, unit_id) != -1) {
5302 unit_id++;
5303 if (max_devs && unit_id >= max_devs) {
5304 unit_id -= max_devs;
5305 bus_id++;
5310 /* check unit id */
5312 if (max_devs && unit_id >= max_devs) {
5313 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5314 str, unit_id, max_devs - 1);
5315 return -1;
5319 * ignore multiple definitions
5322 if (drive_get_index(type, bus_id, unit_id) != -1)
5323 return -2;
5325 /* init */
5327 if (type == IF_IDE || type == IF_SCSI)
5328 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5329 if (max_devs)
5330 snprintf(buf, sizeof(buf), "%s%i%s%i",
5331 devname, bus_id, mediastr, unit_id);
5332 else
5333 snprintf(buf, sizeof(buf), "%s%s%i",
5334 devname, mediastr, unit_id);
5335 bdrv = bdrv_new(buf);
5336 drives_table_idx = drive_get_free_idx();
5337 drives_table[drives_table_idx].bdrv = bdrv;
5338 drives_table[drives_table_idx].type = type;
5339 drives_table[drives_table_idx].bus = bus_id;
5340 drives_table[drives_table_idx].unit = unit_id;
5341 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
5342 nb_drives++;
5344 switch(type) {
5345 case IF_IDE:
5346 case IF_SCSI:
5347 switch(media) {
5348 case MEDIA_DISK:
5349 if (cyls != 0) {
5350 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5351 bdrv_set_translation_hint(bdrv, translation);
5353 break;
5354 case MEDIA_CDROM:
5355 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5356 break;
5358 break;
5359 case IF_SD:
5360 /* FIXME: This isn't really a floppy, but it's a reasonable
5361 approximation. */
5362 case IF_FLOPPY:
5363 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5364 break;
5365 case IF_PFLASH:
5366 case IF_MTD:
5367 case IF_VIRTIO:
5368 break;
5370 if (!file[0])
5371 return -2;
5372 bdrv_flags = 0;
5373 if (snapshot)
5374 bdrv_flags |= BDRV_O_SNAPSHOT;
5375 if (!cache)
5376 bdrv_flags |= BDRV_O_DIRECT;
5377 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5378 fprintf(stderr, "qemu: could not open disk image %s\n",
5379 file);
5380 return -1;
5382 return drives_table_idx;
5385 /***********************************************************/
5386 /* USB devices */
5388 static USBPort *used_usb_ports;
5389 static USBPort *free_usb_ports;
5391 /* ??? Maybe change this to register a hub to keep track of the topology. */
5392 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5393 usb_attachfn attach)
5395 port->opaque = opaque;
5396 port->index = index;
5397 port->attach = attach;
5398 port->next = free_usb_ports;
5399 free_usb_ports = port;
5402 static int usb_device_add(const char *devname)
5404 const char *p;
5405 USBDevice *dev;
5406 USBPort *port;
5408 if (!free_usb_ports)
5409 return -1;
5411 if (strstart(devname, "host:", &p)) {
5412 dev = usb_host_device_open(p);
5413 } else if (!strcmp(devname, "mouse")) {
5414 dev = usb_mouse_init();
5415 } else if (!strcmp(devname, "tablet")) {
5416 dev = usb_tablet_init();
5417 } else if (!strcmp(devname, "keyboard")) {
5418 dev = usb_keyboard_init();
5419 } else if (strstart(devname, "disk:", &p)) {
5420 dev = usb_msd_init(p);
5421 } else if (!strcmp(devname, "wacom-tablet")) {
5422 dev = usb_wacom_init();
5423 } else if (strstart(devname, "serial:", &p)) {
5424 dev = usb_serial_init(p);
5425 } else {
5426 return -1;
5428 if (!dev)
5429 return -1;
5431 /* Find a USB port to add the device to. */
5432 port = free_usb_ports;
5433 if (!port->next) {
5434 USBDevice *hub;
5436 /* Create a new hub and chain it on. */
5437 free_usb_ports = NULL;
5438 port->next = used_usb_ports;
5439 used_usb_ports = port;
5441 hub = usb_hub_init(VM_USB_HUB_SIZE);
5442 usb_attach(port, hub);
5443 port = free_usb_ports;
5446 free_usb_ports = port->next;
5447 port->next = used_usb_ports;
5448 used_usb_ports = port;
5449 usb_attach(port, dev);
5450 return 0;
5453 static int usb_device_del(const char *devname)
5455 USBPort *port;
5456 USBPort **lastp;
5457 USBDevice *dev;
5458 int bus_num, addr;
5459 const char *p;
5461 if (!used_usb_ports)
5462 return -1;
5464 p = strchr(devname, '.');
5465 if (!p)
5466 return -1;
5467 bus_num = strtoul(devname, NULL, 0);
5468 addr = strtoul(p + 1, NULL, 0);
5469 if (bus_num != 0)
5470 return -1;
5472 lastp = &used_usb_ports;
5473 port = used_usb_ports;
5474 while (port && port->dev->addr != addr) {
5475 lastp = &port->next;
5476 port = port->next;
5479 if (!port)
5480 return -1;
5482 dev = port->dev;
5483 *lastp = port->next;
5484 usb_attach(port, NULL);
5485 dev->handle_destroy(dev);
5486 port->next = free_usb_ports;
5487 free_usb_ports = port;
5488 return 0;
5491 void do_usb_add(const char *devname)
5493 int ret;
5494 ret = usb_device_add(devname);
5495 if (ret < 0)
5496 term_printf("Could not add USB device '%s'\n", devname);
5499 void do_usb_del(const char *devname)
5501 int ret;
5502 ret = usb_device_del(devname);
5503 if (ret < 0)
5504 term_printf("Could not remove USB device '%s'\n", devname);
5507 void usb_info(void)
5509 USBDevice *dev;
5510 USBPort *port;
5511 const char *speed_str;
5513 if (!usb_enabled) {
5514 term_printf("USB support not enabled\n");
5515 return;
5518 for (port = used_usb_ports; port; port = port->next) {
5519 dev = port->dev;
5520 if (!dev)
5521 continue;
5522 switch(dev->speed) {
5523 case USB_SPEED_LOW:
5524 speed_str = "1.5";
5525 break;
5526 case USB_SPEED_FULL:
5527 speed_str = "12";
5528 break;
5529 case USB_SPEED_HIGH:
5530 speed_str = "480";
5531 break;
5532 default:
5533 speed_str = "?";
5534 break;
5536 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5537 0, dev->addr, speed_str, dev->devname);
5541 /***********************************************************/
5542 /* PCMCIA/Cardbus */
5544 static struct pcmcia_socket_entry_s {
5545 struct pcmcia_socket_s *socket;
5546 struct pcmcia_socket_entry_s *next;
5547 } *pcmcia_sockets = 0;
5549 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5551 struct pcmcia_socket_entry_s *entry;
5553 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5554 entry->socket = socket;
5555 entry->next = pcmcia_sockets;
5556 pcmcia_sockets = entry;
5559 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5561 struct pcmcia_socket_entry_s *entry, **ptr;
5563 ptr = &pcmcia_sockets;
5564 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5565 if (entry->socket == socket) {
5566 *ptr = entry->next;
5567 qemu_free(entry);
5571 void pcmcia_info(void)
5573 struct pcmcia_socket_entry_s *iter;
5574 if (!pcmcia_sockets)
5575 term_printf("No PCMCIA sockets\n");
5577 for (iter = pcmcia_sockets; iter; iter = iter->next)
5578 term_printf("%s: %s\n", iter->socket->slot_string,
5579 iter->socket->attached ? iter->socket->card_string :
5580 "Empty");
5583 /***********************************************************/
5584 /* dumb display */
5586 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5590 static void dumb_resize(DisplayState *ds, int w, int h)
5594 static void dumb_refresh(DisplayState *ds)
5596 #if defined(CONFIG_SDL)
5597 vga_hw_update();
5598 #endif
5601 static void dumb_display_init(DisplayState *ds)
5603 ds->data = NULL;
5604 ds->linesize = 0;
5605 ds->depth = 0;
5606 ds->dpy_update = dumb_update;
5607 ds->dpy_resize = dumb_resize;
5608 ds->dpy_refresh = dumb_refresh;
5611 /***********************************************************/
5612 /* I/O handling */
5614 #define MAX_IO_HANDLERS 64
5616 typedef struct IOHandlerRecord {
5617 int fd;
5618 IOCanRWHandler *fd_read_poll;
5619 IOHandler *fd_read;
5620 IOHandler *fd_write;
5621 int deleted;
5622 void *opaque;
5623 /* temporary data */
5624 struct pollfd *ufd;
5625 struct IOHandlerRecord *next;
5626 } IOHandlerRecord;
5628 static IOHandlerRecord *first_io_handler;
5630 /* XXX: fd_read_poll should be suppressed, but an API change is
5631 necessary in the character devices to suppress fd_can_read(). */
5632 int qemu_set_fd_handler2(int fd,
5633 IOCanRWHandler *fd_read_poll,
5634 IOHandler *fd_read,
5635 IOHandler *fd_write,
5636 void *opaque)
5638 IOHandlerRecord **pioh, *ioh;
5640 if (!fd_read && !fd_write) {
5641 pioh = &first_io_handler;
5642 for(;;) {
5643 ioh = *pioh;
5644 if (ioh == NULL)
5645 break;
5646 if (ioh->fd == fd) {
5647 ioh->deleted = 1;
5648 break;
5650 pioh = &ioh->next;
5652 } else {
5653 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5654 if (ioh->fd == fd)
5655 goto found;
5657 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5658 if (!ioh)
5659 return -1;
5660 ioh->next = first_io_handler;
5661 first_io_handler = ioh;
5662 found:
5663 ioh->fd = fd;
5664 ioh->fd_read_poll = fd_read_poll;
5665 ioh->fd_read = fd_read;
5666 ioh->fd_write = fd_write;
5667 ioh->opaque = opaque;
5668 ioh->deleted = 0;
5670 return 0;
5673 int qemu_set_fd_handler(int fd,
5674 IOHandler *fd_read,
5675 IOHandler *fd_write,
5676 void *opaque)
5678 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5681 /***********************************************************/
5682 /* Polling handling */
5684 typedef struct PollingEntry {
5685 PollingFunc *func;
5686 void *opaque;
5687 struct PollingEntry *next;
5688 } PollingEntry;
5690 static PollingEntry *first_polling_entry;
5692 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5694 PollingEntry **ppe, *pe;
5695 pe = qemu_mallocz(sizeof(PollingEntry));
5696 if (!pe)
5697 return -1;
5698 pe->func = func;
5699 pe->opaque = opaque;
5700 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5701 *ppe = pe;
5702 return 0;
5705 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5707 PollingEntry **ppe, *pe;
5708 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5709 pe = *ppe;
5710 if (pe->func == func && pe->opaque == opaque) {
5711 *ppe = pe->next;
5712 qemu_free(pe);
5713 break;
5718 #ifdef _WIN32
5719 /***********************************************************/
5720 /* Wait objects support */
5721 typedef struct WaitObjects {
5722 int num;
5723 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5724 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5725 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5726 } WaitObjects;
5728 static WaitObjects wait_objects = {0};
5730 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5732 WaitObjects *w = &wait_objects;
5734 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5735 return -1;
5736 w->events[w->num] = handle;
5737 w->func[w->num] = func;
5738 w->opaque[w->num] = opaque;
5739 w->num++;
5740 return 0;
5743 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5745 int i, found;
5746 WaitObjects *w = &wait_objects;
5748 found = 0;
5749 for (i = 0; i < w->num; i++) {
5750 if (w->events[i] == handle)
5751 found = 1;
5752 if (found) {
5753 w->events[i] = w->events[i + 1];
5754 w->func[i] = w->func[i + 1];
5755 w->opaque[i] = w->opaque[i + 1];
5758 if (found)
5759 w->num--;
5761 #endif
5763 #define SELF_ANNOUNCE_ROUNDS 5
5764 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5765 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5766 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5768 static int announce_self_create(uint8_t *buf,
5769 uint8_t *mac_addr)
5771 uint32_t magic = EXPERIMENTAL_MAGIC;
5772 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5774 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5776 memset(buf, 0xff, 6); /* h_dst */
5777 memcpy(buf + 6, mac_addr, 6); /* h_src */
5778 memcpy(buf + 12, &proto, 2); /* h_proto */
5779 memcpy(buf + 14, &magic, 4); /* magic */
5781 return 18; /* len */
5784 static void qemu_announce_self(void)
5786 int i, j, len;
5787 VLANState *vlan;
5788 VLANClientState *vc;
5789 uint8_t buf[256];
5791 for (i = 0; i < nb_nics; i++) {
5792 len = announce_self_create(buf, nd_table[i].macaddr);
5793 vlan = nd_table[i].vlan;
5794 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5795 if (vc->fd_read == tap_receive) /* send only if tap */
5796 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5797 vc->fd_read(vc->opaque, buf, len);
5802 /***********************************************************/
5803 /* savevm/loadvm support */
5805 #define IO_BUF_SIZE 32768
5807 struct QEMUFile {
5808 QEMUFilePutBufferFunc *put_buffer;
5809 QEMUFileGetBufferFunc *get_buffer;
5810 QEMUFileCloseFunc *close;
5811 void *opaque;
5813 int64_t buf_offset; /* start of buffer when writing, end of buffer
5814 when reading */
5815 int buf_index;
5816 int buf_size; /* 0 when writing */
5817 uint8_t buf[IO_BUF_SIZE];
5820 typedef struct QEMUFileFD
5822 int fd;
5823 } QEMUFileFD;
5825 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5827 QEMUFileFD *s = opaque;
5828 int offset = 0;
5829 ssize_t len;
5831 again:
5832 len = read(s->fd, buf + offset, size - offset);
5833 if (len == -1) {
5834 if (errno == EINTR || errno == EAGAIN)
5835 goto again;
5838 return len;
5841 QEMUFile *qemu_fopen_fd(int fd)
5843 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5844 s->fd = fd;
5845 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5848 typedef struct QEMUFileUnix
5850 FILE *outfile;
5851 } QEMUFileUnix;
5853 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5855 QEMUFileUnix *s = opaque;
5856 fseek(s->outfile, pos, SEEK_SET);
5857 fwrite(buf, 1, size, s->outfile);
5860 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5862 QEMUFileUnix *s = opaque;
5863 fseek(s->outfile, pos, SEEK_SET);
5864 return fread(buf, 1, size, s->outfile);
5867 static void file_close(void *opaque)
5869 QEMUFileUnix *s = opaque;
5870 fclose(s->outfile);
5871 qemu_free(s);
5874 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5876 QEMUFileUnix *s;
5878 s = qemu_mallocz(sizeof(QEMUFileUnix));
5879 if (!s)
5880 return NULL;
5882 s->outfile = fopen(filename, mode);
5883 if (!s->outfile)
5884 goto fail;
5886 if (!strcmp(mode, "wb"))
5887 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5888 else if (!strcmp(mode, "rb"))
5889 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5891 fail:
5892 if (s->outfile)
5893 fclose(s->outfile);
5894 qemu_free(s);
5895 return NULL;
5898 typedef struct QEMUFileBdrv
5900 BlockDriverState *bs;
5901 int64_t base_offset;
5902 } QEMUFileBdrv;
5904 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5906 QEMUFileBdrv *s = opaque;
5907 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5910 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5912 QEMUFileBdrv *s = opaque;
5913 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5916 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5918 QEMUFileBdrv *s;
5920 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5921 if (!s)
5922 return NULL;
5924 s->bs = bs;
5925 s->base_offset = offset;
5927 if (is_writable)
5928 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5930 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5933 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5934 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5936 QEMUFile *f;
5938 f = qemu_mallocz(sizeof(QEMUFile));
5939 if (!f)
5940 return NULL;
5942 f->opaque = opaque;
5943 f->put_buffer = put_buffer;
5944 f->get_buffer = get_buffer;
5945 f->close = close;
5947 return f;
5950 void qemu_fflush(QEMUFile *f)
5952 if (!f->put_buffer)
5953 return;
5955 if (f->buf_index > 0) {
5956 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5957 f->buf_offset += f->buf_index;
5958 f->buf_index = 0;
5962 static void qemu_fill_buffer(QEMUFile *f)
5964 int len;
5966 if (!f->get_buffer)
5967 return;
5969 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5970 if (len < 0)
5971 len = 0;
5973 f->buf_index = 0;
5974 f->buf_size = len;
5975 f->buf_offset += len;
5978 void qemu_fclose(QEMUFile *f)
5980 qemu_fflush(f);
5981 if (f->close)
5982 f->close(f->opaque);
5983 qemu_free(f);
5986 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5988 int l;
5989 while (size > 0) {
5990 l = IO_BUF_SIZE - f->buf_index;
5991 if (l > size)
5992 l = size;
5993 memcpy(f->buf + f->buf_index, buf, l);
5994 f->buf_index += l;
5995 buf += l;
5996 size -= l;
5997 if (f->buf_index >= IO_BUF_SIZE)
5998 qemu_fflush(f);
6002 void qemu_put_byte(QEMUFile *f, int v)
6004 f->buf[f->buf_index++] = v;
6005 if (f->buf_index >= IO_BUF_SIZE)
6006 qemu_fflush(f);
6009 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6011 int size, l;
6013 size = size1;
6014 while (size > 0) {
6015 l = f->buf_size - f->buf_index;
6016 if (l == 0) {
6017 qemu_fill_buffer(f);
6018 l = f->buf_size - f->buf_index;
6019 if (l == 0)
6020 break;
6022 if (l > size)
6023 l = size;
6024 memcpy(buf, f->buf + f->buf_index, l);
6025 f->buf_index += l;
6026 buf += l;
6027 size -= l;
6029 return size1 - size;
6032 int qemu_get_byte(QEMUFile *f)
6034 if (f->buf_index >= f->buf_size) {
6035 qemu_fill_buffer(f);
6036 if (f->buf_index >= f->buf_size)
6037 return 0;
6039 return f->buf[f->buf_index++];
6042 int64_t qemu_ftell(QEMUFile *f)
6044 return f->buf_offset - f->buf_size + f->buf_index;
6047 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6049 if (whence == SEEK_SET) {
6050 /* nothing to do */
6051 } else if (whence == SEEK_CUR) {
6052 pos += qemu_ftell(f);
6053 } else {
6054 /* SEEK_END not supported */
6055 return -1;
6057 if (f->put_buffer) {
6058 qemu_fflush(f);
6059 f->buf_offset = pos;
6060 } else {
6061 f->buf_offset = pos;
6062 f->buf_index = 0;
6063 f->buf_size = 0;
6065 return pos;
6068 void qemu_put_be16(QEMUFile *f, unsigned int v)
6070 qemu_put_byte(f, v >> 8);
6071 qemu_put_byte(f, v);
6074 void qemu_put_be32(QEMUFile *f, unsigned int v)
6076 qemu_put_byte(f, v >> 24);
6077 qemu_put_byte(f, v >> 16);
6078 qemu_put_byte(f, v >> 8);
6079 qemu_put_byte(f, v);
6082 void qemu_put_be64(QEMUFile *f, uint64_t v)
6084 qemu_put_be32(f, v >> 32);
6085 qemu_put_be32(f, v);
6088 unsigned int qemu_get_be16(QEMUFile *f)
6090 unsigned int v;
6091 v = qemu_get_byte(f) << 8;
6092 v |= qemu_get_byte(f);
6093 return v;
6096 unsigned int qemu_get_be32(QEMUFile *f)
6098 unsigned int v;
6099 v = qemu_get_byte(f) << 24;
6100 v |= qemu_get_byte(f) << 16;
6101 v |= qemu_get_byte(f) << 8;
6102 v |= qemu_get_byte(f);
6103 return v;
6106 uint64_t qemu_get_be64(QEMUFile *f)
6108 uint64_t v;
6109 v = (uint64_t)qemu_get_be32(f) << 32;
6110 v |= qemu_get_be32(f);
6111 return v;
6114 typedef struct SaveStateEntry {
6115 char idstr[256];
6116 int instance_id;
6117 int version_id;
6118 SaveStateHandler *save_state;
6119 LoadStateHandler *load_state;
6120 void *opaque;
6121 struct SaveStateEntry *next;
6122 } SaveStateEntry;
6124 static SaveStateEntry *first_se;
6126 int register_savevm(const char *idstr,
6127 int instance_id,
6128 int version_id,
6129 SaveStateHandler *save_state,
6130 LoadStateHandler *load_state,
6131 void *opaque)
6133 SaveStateEntry *se, **pse;
6135 se = qemu_malloc(sizeof(SaveStateEntry));
6136 if (!se)
6137 return -1;
6138 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6139 se->instance_id = instance_id;
6140 se->version_id = version_id;
6141 se->save_state = save_state;
6142 se->load_state = load_state;
6143 se->opaque = opaque;
6144 se->next = NULL;
6146 /* add at the end of list */
6147 pse = &first_se;
6148 while (*pse != NULL)
6149 pse = &(*pse)->next;
6150 *pse = se;
6151 return 0;
6154 #define QEMU_VM_FILE_MAGIC 0x5145564d
6155 #define QEMU_VM_FILE_VERSION 0x00000002
6157 static int qemu_savevm_state(QEMUFile *f)
6159 SaveStateEntry *se;
6160 int len, ret;
6161 int64_t cur_pos, len_pos, total_len_pos;
6163 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6164 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6165 total_len_pos = qemu_ftell(f);
6166 qemu_put_be64(f, 0); /* total size */
6168 for(se = first_se; se != NULL; se = se->next) {
6169 /* ID string */
6170 len = strlen(se->idstr);
6171 qemu_put_byte(f, len);
6172 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6174 qemu_put_be32(f, se->instance_id);
6175 qemu_put_be32(f, se->version_id);
6177 /* record size: filled later */
6178 len_pos = qemu_ftell(f);
6179 qemu_put_be32(f, 0);
6180 se->save_state(f, se->opaque);
6182 /* fill record size */
6183 cur_pos = qemu_ftell(f);
6184 len = cur_pos - len_pos - 4;
6185 qemu_fseek(f, len_pos, SEEK_SET);
6186 qemu_put_be32(f, len);
6187 qemu_fseek(f, cur_pos, SEEK_SET);
6189 cur_pos = qemu_ftell(f);
6190 qemu_fseek(f, total_len_pos, SEEK_SET);
6191 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6192 qemu_fseek(f, cur_pos, SEEK_SET);
6194 ret = 0;
6195 return ret;
6198 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6200 SaveStateEntry *se;
6202 for(se = first_se; se != NULL; se = se->next) {
6203 if (!strcmp(se->idstr, idstr) &&
6204 instance_id == se->instance_id)
6205 return se;
6207 return NULL;
6210 static int qemu_loadvm_state(QEMUFile *f)
6212 SaveStateEntry *se;
6213 int len, ret, instance_id, record_len, version_id;
6214 int64_t total_len, end_pos, cur_pos;
6215 unsigned int v;
6216 char idstr[256];
6218 v = qemu_get_be32(f);
6219 if (v != QEMU_VM_FILE_MAGIC)
6220 goto fail;
6221 v = qemu_get_be32(f);
6222 if (v != QEMU_VM_FILE_VERSION) {
6223 fail:
6224 ret = -1;
6225 goto the_end;
6227 total_len = qemu_get_be64(f);
6228 end_pos = total_len + qemu_ftell(f);
6229 for(;;) {
6230 if (qemu_ftell(f) >= end_pos)
6231 break;
6232 len = qemu_get_byte(f);
6233 qemu_get_buffer(f, (uint8_t *)idstr, len);
6234 idstr[len] = '\0';
6235 instance_id = qemu_get_be32(f);
6236 version_id = qemu_get_be32(f);
6237 record_len = qemu_get_be32(f);
6238 #if 0
6239 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6240 idstr, instance_id, version_id, record_len);
6241 #endif
6242 cur_pos = qemu_ftell(f);
6243 se = find_se(idstr, instance_id);
6244 if (!se) {
6245 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6246 instance_id, idstr);
6247 } else {
6248 ret = se->load_state(f, se->opaque, version_id);
6249 if (ret < 0) {
6250 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6251 instance_id, idstr);
6252 goto the_end;
6255 /* always seek to exact end of record */
6256 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6258 ret = 0;
6259 the_end:
6260 return ret;
6263 int qemu_live_savevm_state(QEMUFile *f)
6265 SaveStateEntry *se;
6266 int len, ret;
6268 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6269 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6271 for(se = first_se; se != NULL; se = se->next) {
6272 len = strlen(se->idstr);
6274 qemu_put_byte(f, len);
6275 qemu_put_buffer(f, se->idstr, len);
6276 qemu_put_be32(f, se->instance_id);
6277 qemu_put_be32(f, se->version_id);
6279 se->save_state(f, se->opaque);
6282 qemu_put_byte(f, 0);
6284 ret = 0;
6285 return ret;
6288 int qemu_live_loadvm_state(QEMUFile *f)
6290 SaveStateEntry *se;
6291 int len, ret, instance_id, version_id;
6292 unsigned int v;
6293 char idstr[256];
6295 v = qemu_get_be32(f);
6296 if (v != QEMU_VM_FILE_MAGIC)
6297 goto fail;
6298 v = qemu_get_be32(f);
6299 if (v != QEMU_VM_FILE_VERSION) {
6300 fail:
6301 ret = -1;
6302 goto the_end;
6305 for(;;) {
6306 len = qemu_get_byte(f);
6307 if (len == 0)
6308 break;
6309 qemu_get_buffer(f, idstr, len);
6310 idstr[len] = '\0';
6311 instance_id = qemu_get_be32(f);
6312 version_id = qemu_get_be32(f);
6313 se = find_se(idstr, instance_id);
6314 if (!se) {
6315 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6316 instance_id, idstr);
6317 } else {
6318 if (version_id > se->version_id) { /* src version > dst version */
6319 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6320 idstr, version_id, se->version_id);
6321 ret = -1;
6322 goto the_end;
6324 ret = se->load_state(f, se->opaque, version_id);
6325 if (ret < 0) {
6326 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6327 instance_id, idstr);
6328 goto the_end;
6332 ret = 0;
6334 qemu_announce_self();
6336 the_end:
6337 return ret;
6340 /* device can contain snapshots */
6341 static int bdrv_can_snapshot(BlockDriverState *bs)
6343 return (bs &&
6344 !bdrv_is_removable(bs) &&
6345 !bdrv_is_read_only(bs));
6348 /* device must be snapshots in order to have a reliable snapshot */
6349 static int bdrv_has_snapshot(BlockDriverState *bs)
6351 return (bs &&
6352 !bdrv_is_removable(bs) &&
6353 !bdrv_is_read_only(bs));
6356 static BlockDriverState *get_bs_snapshots(void)
6358 BlockDriverState *bs;
6359 int i;
6361 if (bs_snapshots)
6362 return bs_snapshots;
6363 for(i = 0; i <= nb_drives; i++) {
6364 bs = drives_table[i].bdrv;
6365 if (bdrv_can_snapshot(bs))
6366 goto ok;
6368 return NULL;
6370 bs_snapshots = bs;
6371 return bs;
6374 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6375 const char *name)
6377 QEMUSnapshotInfo *sn_tab, *sn;
6378 int nb_sns, i, ret;
6380 ret = -ENOENT;
6381 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6382 if (nb_sns < 0)
6383 return ret;
6384 for(i = 0; i < nb_sns; i++) {
6385 sn = &sn_tab[i];
6386 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6387 *sn_info = *sn;
6388 ret = 0;
6389 break;
6392 qemu_free(sn_tab);
6393 return ret;
6396 void do_savevm(const char *name)
6398 BlockDriverState *bs, *bs1;
6399 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6400 int must_delete, ret, i;
6401 BlockDriverInfo bdi1, *bdi = &bdi1;
6402 QEMUFile *f;
6403 int saved_vm_running;
6404 #ifdef _WIN32
6405 struct _timeb tb;
6406 #else
6407 struct timeval tv;
6408 #endif
6410 bs = get_bs_snapshots();
6411 if (!bs) {
6412 term_printf("No block device can accept snapshots\n");
6413 return;
6416 /* ??? Should this occur after vm_stop? */
6417 qemu_aio_flush();
6419 saved_vm_running = vm_running;
6420 vm_stop(0);
6422 must_delete = 0;
6423 if (name) {
6424 ret = bdrv_snapshot_find(bs, old_sn, name);
6425 if (ret >= 0) {
6426 must_delete = 1;
6429 memset(sn, 0, sizeof(*sn));
6430 if (must_delete) {
6431 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6432 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6433 } else {
6434 if (name)
6435 pstrcpy(sn->name, sizeof(sn->name), name);
6438 /* fill auxiliary fields */
6439 #ifdef _WIN32
6440 _ftime(&tb);
6441 sn->date_sec = tb.time;
6442 sn->date_nsec = tb.millitm * 1000000;
6443 #else
6444 gettimeofday(&tv, NULL);
6445 sn->date_sec = tv.tv_sec;
6446 sn->date_nsec = tv.tv_usec * 1000;
6447 #endif
6448 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6450 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6451 term_printf("Device %s does not support VM state snapshots\n",
6452 bdrv_get_device_name(bs));
6453 goto the_end;
6456 /* save the VM state */
6457 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6458 if (!f) {
6459 term_printf("Could not open VM state file\n");
6460 goto the_end;
6462 ret = qemu_savevm_state(f);
6463 sn->vm_state_size = qemu_ftell(f);
6464 qemu_fclose(f);
6465 if (ret < 0) {
6466 term_printf("Error %d while writing VM\n", ret);
6467 goto the_end;
6470 /* create the snapshots */
6472 for(i = 0; i < nb_drives; i++) {
6473 bs1 = drives_table[i].bdrv;
6474 if (bdrv_has_snapshot(bs1)) {
6475 if (must_delete) {
6476 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6477 if (ret < 0) {
6478 term_printf("Error while deleting snapshot on '%s'\n",
6479 bdrv_get_device_name(bs1));
6482 ret = bdrv_snapshot_create(bs1, sn);
6483 if (ret < 0) {
6484 term_printf("Error while creating snapshot on '%s'\n",
6485 bdrv_get_device_name(bs1));
6490 the_end:
6491 if (saved_vm_running)
6492 vm_start();
6495 void do_loadvm(const char *name)
6497 BlockDriverState *bs, *bs1;
6498 BlockDriverInfo bdi1, *bdi = &bdi1;
6499 QEMUFile *f;
6500 int i, ret;
6501 int saved_vm_running;
6503 bs = get_bs_snapshots();
6504 if (!bs) {
6505 term_printf("No block device supports snapshots\n");
6506 return;
6509 /* Flush all IO requests so they don't interfere with the new state. */
6510 qemu_aio_flush();
6512 saved_vm_running = vm_running;
6513 vm_stop(0);
6515 for(i = 0; i <= nb_drives; i++) {
6516 bs1 = drives_table[i].bdrv;
6517 if (bdrv_has_snapshot(bs1)) {
6518 ret = bdrv_snapshot_goto(bs1, name);
6519 if (ret < 0) {
6520 if (bs != bs1)
6521 term_printf("Warning: ");
6522 switch(ret) {
6523 case -ENOTSUP:
6524 term_printf("Snapshots not supported on device '%s'\n",
6525 bdrv_get_device_name(bs1));
6526 break;
6527 case -ENOENT:
6528 term_printf("Could not find snapshot '%s' on device '%s'\n",
6529 name, bdrv_get_device_name(bs1));
6530 break;
6531 default:
6532 term_printf("Error %d while activating snapshot on '%s'\n",
6533 ret, bdrv_get_device_name(bs1));
6534 break;
6536 /* fatal on snapshot block device */
6537 if (bs == bs1)
6538 goto the_end;
6543 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6544 term_printf("Device %s does not support VM state snapshots\n",
6545 bdrv_get_device_name(bs));
6546 return;
6549 /* restore the VM state */
6550 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6551 if (!f) {
6552 term_printf("Could not open VM state file\n");
6553 goto the_end;
6555 ret = qemu_loadvm_state(f);
6556 qemu_fclose(f);
6557 if (ret < 0) {
6558 term_printf("Error %d while loading VM state\n", ret);
6560 the_end:
6561 if (saved_vm_running)
6562 vm_start();
6565 void do_delvm(const char *name)
6567 BlockDriverState *bs, *bs1;
6568 int i, ret;
6570 bs = get_bs_snapshots();
6571 if (!bs) {
6572 term_printf("No block device supports snapshots\n");
6573 return;
6576 for(i = 0; i <= nb_drives; i++) {
6577 bs1 = drives_table[i].bdrv;
6578 if (bdrv_has_snapshot(bs1)) {
6579 ret = bdrv_snapshot_delete(bs1, name);
6580 if (ret < 0) {
6581 if (ret == -ENOTSUP)
6582 term_printf("Snapshots not supported on device '%s'\n",
6583 bdrv_get_device_name(bs1));
6584 else
6585 term_printf("Error %d while deleting snapshot on '%s'\n",
6586 ret, bdrv_get_device_name(bs1));
6592 void do_info_snapshots(void)
6594 BlockDriverState *bs, *bs1;
6595 QEMUSnapshotInfo *sn_tab, *sn;
6596 int nb_sns, i;
6597 char buf[256];
6599 bs = get_bs_snapshots();
6600 if (!bs) {
6601 term_printf("No available block device supports snapshots\n");
6602 return;
6604 term_printf("Snapshot devices:");
6605 for(i = 0; i <= nb_drives; i++) {
6606 bs1 = drives_table[i].bdrv;
6607 if (bdrv_has_snapshot(bs1)) {
6608 if (bs == bs1)
6609 term_printf(" %s", bdrv_get_device_name(bs1));
6612 term_printf("\n");
6614 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6615 if (nb_sns < 0) {
6616 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6617 return;
6619 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6620 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6621 for(i = 0; i < nb_sns; i++) {
6622 sn = &sn_tab[i];
6623 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6625 qemu_free(sn_tab);
6628 /***********************************************************/
6629 /* cpu save/restore */
6631 #if defined(TARGET_I386)
6633 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6635 qemu_put_be32(f, dt->selector);
6636 qemu_put_betl(f, dt->base);
6637 qemu_put_be32(f, dt->limit);
6638 qemu_put_be32(f, dt->flags);
6641 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6643 dt->selector = qemu_get_be32(f);
6644 dt->base = qemu_get_betl(f);
6645 dt->limit = qemu_get_be32(f);
6646 dt->flags = qemu_get_be32(f);
6649 void cpu_save(QEMUFile *f, void *opaque)
6651 CPUState *env = opaque;
6652 uint16_t fptag, fpus, fpuc, fpregs_format;
6653 uint32_t hflags;
6654 int i;
6656 if (kvm_enabled())
6657 kvm_save_registers(env);
6659 for(i = 0; i < CPU_NB_REGS; i++)
6660 qemu_put_betls(f, &env->regs[i]);
6661 qemu_put_betls(f, &env->eip);
6662 qemu_put_betls(f, &env->eflags);
6663 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6664 qemu_put_be32s(f, &hflags);
6666 /* FPU */
6667 fpuc = env->fpuc;
6668 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6669 fptag = 0;
6670 for(i = 0; i < 8; i++) {
6671 fptag |= ((!env->fptags[i]) << i);
6674 qemu_put_be16s(f, &fpuc);
6675 qemu_put_be16s(f, &fpus);
6676 qemu_put_be16s(f, &fptag);
6678 #ifdef USE_X86LDOUBLE
6679 fpregs_format = 0;
6680 #else
6681 fpregs_format = 1;
6682 #endif
6683 qemu_put_be16s(f, &fpregs_format);
6685 for(i = 0; i < 8; i++) {
6686 #ifdef USE_X86LDOUBLE
6688 uint64_t mant;
6689 uint16_t exp;
6690 /* we save the real CPU data (in case of MMX usage only 'mant'
6691 contains the MMX register */
6692 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6693 qemu_put_be64(f, mant);
6694 qemu_put_be16(f, exp);
6696 #else
6697 /* if we use doubles for float emulation, we save the doubles to
6698 avoid losing information in case of MMX usage. It can give
6699 problems if the image is restored on a CPU where long
6700 doubles are used instead. */
6701 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6702 #endif
6705 for(i = 0; i < 6; i++)
6706 cpu_put_seg(f, &env->segs[i]);
6707 cpu_put_seg(f, &env->ldt);
6708 cpu_put_seg(f, &env->tr);
6709 cpu_put_seg(f, &env->gdt);
6710 cpu_put_seg(f, &env->idt);
6712 qemu_put_be32s(f, &env->sysenter_cs);
6713 qemu_put_be32s(f, &env->sysenter_esp);
6714 qemu_put_be32s(f, &env->sysenter_eip);
6716 qemu_put_betls(f, &env->cr[0]);
6717 qemu_put_betls(f, &env->cr[2]);
6718 qemu_put_betls(f, &env->cr[3]);
6719 qemu_put_betls(f, &env->cr[4]);
6721 for(i = 0; i < 8; i++)
6722 qemu_put_betls(f, &env->dr[i]);
6724 /* MMU */
6725 qemu_put_be32s(f, &env->a20_mask);
6727 /* XMM */
6728 qemu_put_be32s(f, &env->mxcsr);
6729 for(i = 0; i < CPU_NB_REGS; i++) {
6730 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6731 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6734 #ifdef TARGET_X86_64
6735 qemu_put_be64s(f, &env->efer);
6736 qemu_put_be64s(f, &env->star);
6737 qemu_put_be64s(f, &env->lstar);
6738 qemu_put_be64s(f, &env->cstar);
6739 qemu_put_be64s(f, &env->fmask);
6740 qemu_put_be64s(f, &env->kernelgsbase);
6741 #endif
6742 qemu_put_be32s(f, &env->smbase);
6744 if (kvm_enabled()) {
6745 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6746 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6748 qemu_put_be64s(f, &env->tsc);
6752 #ifdef USE_X86LDOUBLE
6753 /* XXX: add that in a FPU generic layer */
6754 union x86_longdouble {
6755 uint64_t mant;
6756 uint16_t exp;
6759 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6760 #define EXPBIAS1 1023
6761 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6762 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6764 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6766 int e;
6767 /* mantissa */
6768 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6769 /* exponent + sign */
6770 e = EXPD1(temp) - EXPBIAS1 + 16383;
6771 e |= SIGND1(temp) >> 16;
6772 p->exp = e;
6774 #endif
6776 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6778 CPUState *env = opaque;
6779 int i, guess_mmx;
6780 uint32_t hflags;
6781 uint16_t fpus, fpuc, fptag, fpregs_format;
6783 if (version_id != 3 && version_id != 4)
6784 return -EINVAL;
6785 for(i = 0; i < CPU_NB_REGS; i++)
6786 qemu_get_betls(f, &env->regs[i]);
6787 qemu_get_betls(f, &env->eip);
6788 qemu_get_betls(f, &env->eflags);
6789 qemu_get_be32s(f, &hflags);
6791 qemu_get_be16s(f, &fpuc);
6792 qemu_get_be16s(f, &fpus);
6793 qemu_get_be16s(f, &fptag);
6794 qemu_get_be16s(f, &fpregs_format);
6796 /* NOTE: we cannot always restore the FPU state if the image come
6797 from a host with a different 'USE_X86LDOUBLE' define. We guess
6798 if we are in an MMX state to restore correctly in that case. */
6799 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6800 for(i = 0; i < 8; i++) {
6801 uint64_t mant;
6802 uint16_t exp;
6804 switch(fpregs_format) {
6805 case 0:
6806 mant = qemu_get_be64(f);
6807 exp = qemu_get_be16(f);
6808 #ifdef USE_X86LDOUBLE
6809 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6810 #else
6811 /* difficult case */
6812 if (guess_mmx)
6813 env->fpregs[i].mmx.MMX_Q(0) = mant;
6814 else
6815 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6816 #endif
6817 break;
6818 case 1:
6819 mant = qemu_get_be64(f);
6820 #ifdef USE_X86LDOUBLE
6822 union x86_longdouble *p;
6823 /* difficult case */
6824 p = (void *)&env->fpregs[i];
6825 if (guess_mmx) {
6826 p->mant = mant;
6827 p->exp = 0xffff;
6828 } else {
6829 fp64_to_fp80(p, mant);
6832 #else
6833 env->fpregs[i].mmx.MMX_Q(0) = mant;
6834 #endif
6835 break;
6836 default:
6837 return -EINVAL;
6841 env->fpuc = fpuc;
6842 /* XXX: restore FPU round state */
6843 env->fpstt = (fpus >> 11) & 7;
6844 env->fpus = fpus & ~0x3800;
6845 fptag ^= 0xff;
6846 for(i = 0; i < 8; i++) {
6847 env->fptags[i] = (fptag >> i) & 1;
6850 for(i = 0; i < 6; i++)
6851 cpu_get_seg(f, &env->segs[i]);
6852 cpu_get_seg(f, &env->ldt);
6853 cpu_get_seg(f, &env->tr);
6854 cpu_get_seg(f, &env->gdt);
6855 cpu_get_seg(f, &env->idt);
6857 qemu_get_be32s(f, &env->sysenter_cs);
6858 qemu_get_be32s(f, &env->sysenter_esp);
6859 qemu_get_be32s(f, &env->sysenter_eip);
6861 qemu_get_betls(f, &env->cr[0]);
6862 qemu_get_betls(f, &env->cr[2]);
6863 qemu_get_betls(f, &env->cr[3]);
6864 qemu_get_betls(f, &env->cr[4]);
6866 for(i = 0; i < 8; i++)
6867 qemu_get_betls(f, &env->dr[i]);
6869 /* MMU */
6870 qemu_get_be32s(f, &env->a20_mask);
6872 qemu_get_be32s(f, &env->mxcsr);
6873 for(i = 0; i < CPU_NB_REGS; i++) {
6874 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6875 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6878 #ifdef TARGET_X86_64
6879 qemu_get_be64s(f, &env->efer);
6880 qemu_get_be64s(f, &env->star);
6881 qemu_get_be64s(f, &env->lstar);
6882 qemu_get_be64s(f, &env->cstar);
6883 qemu_get_be64s(f, &env->fmask);
6884 qemu_get_be64s(f, &env->kernelgsbase);
6885 #endif
6886 if (version_id >= 4)
6887 qemu_get_be32s(f, &env->smbase);
6889 /* XXX: compute hflags from scratch, except for CPL and IIF */
6890 env->hflags = hflags;
6891 tlb_flush(env, 1);
6892 if (kvm_enabled()) {
6893 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6894 because no userspace IRQs will ever clear this flag */
6895 env->hflags &= ~HF_HALTED_MASK;
6896 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6897 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6899 qemu_get_be64s(f, &env->tsc);
6900 kvm_load_registers(env);
6902 return 0;
6905 #elif defined(TARGET_PPC)
6906 void cpu_save(QEMUFile *f, void *opaque)
6910 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6912 return 0;
6915 #elif defined(TARGET_MIPS)
6916 void cpu_save(QEMUFile *f, void *opaque)
6920 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6922 return 0;
6925 #elif defined(TARGET_SPARC)
6926 void cpu_save(QEMUFile *f, void *opaque)
6928 CPUState *env = opaque;
6929 int i;
6930 uint32_t tmp;
6932 for(i = 0; i < 8; i++)
6933 qemu_put_betls(f, &env->gregs[i]);
6934 for(i = 0; i < NWINDOWS * 16; i++)
6935 qemu_put_betls(f, &env->regbase[i]);
6937 /* FPU */
6938 for(i = 0; i < TARGET_FPREGS; i++) {
6939 union {
6940 float32 f;
6941 uint32_t i;
6942 } u;
6943 u.f = env->fpr[i];
6944 qemu_put_be32(f, u.i);
6947 qemu_put_betls(f, &env->pc);
6948 qemu_put_betls(f, &env->npc);
6949 qemu_put_betls(f, &env->y);
6950 tmp = GET_PSR(env);
6951 qemu_put_be32(f, tmp);
6952 qemu_put_betls(f, &env->fsr);
6953 qemu_put_betls(f, &env->tbr);
6954 #ifndef TARGET_SPARC64
6955 qemu_put_be32s(f, &env->wim);
6956 /* MMU */
6957 for(i = 0; i < 16; i++)
6958 qemu_put_be32s(f, &env->mmuregs[i]);
6959 #endif
6962 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6964 CPUState *env = opaque;
6965 int i;
6966 uint32_t tmp;
6968 for(i = 0; i < 8; i++)
6969 qemu_get_betls(f, &env->gregs[i]);
6970 for(i = 0; i < NWINDOWS * 16; i++)
6971 qemu_get_betls(f, &env->regbase[i]);
6973 /* FPU */
6974 for(i = 0; i < TARGET_FPREGS; i++) {
6975 union {
6976 float32 f;
6977 uint32_t i;
6978 } u;
6979 u.i = qemu_get_be32(f);
6980 env->fpr[i] = u.f;
6983 qemu_get_betls(f, &env->pc);
6984 qemu_get_betls(f, &env->npc);
6985 qemu_get_betls(f, &env->y);
6986 tmp = qemu_get_be32(f);
6987 env->cwp = 0; /* needed to ensure that the wrapping registers are
6988 correctly updated */
6989 PUT_PSR(env, tmp);
6990 qemu_get_betls(f, &env->fsr);
6991 qemu_get_betls(f, &env->tbr);
6992 #ifndef TARGET_SPARC64
6993 qemu_get_be32s(f, &env->wim);
6994 /* MMU */
6995 for(i = 0; i < 16; i++)
6996 qemu_get_be32s(f, &env->mmuregs[i]);
6997 #endif
6998 tlb_flush(env, 1);
6999 return 0;
7002 #elif defined(TARGET_ARM)
7004 void cpu_save(QEMUFile *f, void *opaque)
7006 int i;
7007 CPUARMState *env = (CPUARMState *)opaque;
7009 for (i = 0; i < 16; i++) {
7010 qemu_put_be32(f, env->regs[i]);
7012 qemu_put_be32(f, cpsr_read(env));
7013 qemu_put_be32(f, env->spsr);
7014 for (i = 0; i < 6; i++) {
7015 qemu_put_be32(f, env->banked_spsr[i]);
7016 qemu_put_be32(f, env->banked_r13[i]);
7017 qemu_put_be32(f, env->banked_r14[i]);
7019 for (i = 0; i < 5; i++) {
7020 qemu_put_be32(f, env->usr_regs[i]);
7021 qemu_put_be32(f, env->fiq_regs[i]);
7023 qemu_put_be32(f, env->cp15.c0_cpuid);
7024 qemu_put_be32(f, env->cp15.c0_cachetype);
7025 qemu_put_be32(f, env->cp15.c1_sys);
7026 qemu_put_be32(f, env->cp15.c1_coproc);
7027 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
7028 qemu_put_be32(f, env->cp15.c2_base0);
7029 qemu_put_be32(f, env->cp15.c2_base1);
7030 qemu_put_be32(f, env->cp15.c2_mask);
7031 qemu_put_be32(f, env->cp15.c2_data);
7032 qemu_put_be32(f, env->cp15.c2_insn);
7033 qemu_put_be32(f, env->cp15.c3);
7034 qemu_put_be32(f, env->cp15.c5_insn);
7035 qemu_put_be32(f, env->cp15.c5_data);
7036 for (i = 0; i < 8; i++) {
7037 qemu_put_be32(f, env->cp15.c6_region[i]);
7039 qemu_put_be32(f, env->cp15.c6_insn);
7040 qemu_put_be32(f, env->cp15.c6_data);
7041 qemu_put_be32(f, env->cp15.c9_insn);
7042 qemu_put_be32(f, env->cp15.c9_data);
7043 qemu_put_be32(f, env->cp15.c13_fcse);
7044 qemu_put_be32(f, env->cp15.c13_context);
7045 qemu_put_be32(f, env->cp15.c13_tls1);
7046 qemu_put_be32(f, env->cp15.c13_tls2);
7047 qemu_put_be32(f, env->cp15.c13_tls3);
7048 qemu_put_be32(f, env->cp15.c15_cpar);
7050 qemu_put_be32(f, env->features);
7052 if (arm_feature(env, ARM_FEATURE_VFP)) {
7053 for (i = 0; i < 16; i++) {
7054 CPU_DoubleU u;
7055 u.d = env->vfp.regs[i];
7056 qemu_put_be32(f, u.l.upper);
7057 qemu_put_be32(f, u.l.lower);
7059 for (i = 0; i < 16; i++) {
7060 qemu_put_be32(f, env->vfp.xregs[i]);
7063 /* TODO: Should use proper FPSCR access functions. */
7064 qemu_put_be32(f, env->vfp.vec_len);
7065 qemu_put_be32(f, env->vfp.vec_stride);
7067 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7068 for (i = 16; i < 32; i++) {
7069 CPU_DoubleU u;
7070 u.d = env->vfp.regs[i];
7071 qemu_put_be32(f, u.l.upper);
7072 qemu_put_be32(f, u.l.lower);
7077 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7078 for (i = 0; i < 16; i++) {
7079 qemu_put_be64(f, env->iwmmxt.regs[i]);
7081 for (i = 0; i < 16; i++) {
7082 qemu_put_be32(f, env->iwmmxt.cregs[i]);
7086 if (arm_feature(env, ARM_FEATURE_M)) {
7087 qemu_put_be32(f, env->v7m.other_sp);
7088 qemu_put_be32(f, env->v7m.vecbase);
7089 qemu_put_be32(f, env->v7m.basepri);
7090 qemu_put_be32(f, env->v7m.control);
7091 qemu_put_be32(f, env->v7m.current_sp);
7092 qemu_put_be32(f, env->v7m.exception);
7096 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7098 CPUARMState *env = (CPUARMState *)opaque;
7099 int i;
7101 if (version_id != ARM_CPU_SAVE_VERSION)
7102 return -EINVAL;
7104 for (i = 0; i < 16; i++) {
7105 env->regs[i] = qemu_get_be32(f);
7107 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7108 env->spsr = qemu_get_be32(f);
7109 for (i = 0; i < 6; i++) {
7110 env->banked_spsr[i] = qemu_get_be32(f);
7111 env->banked_r13[i] = qemu_get_be32(f);
7112 env->banked_r14[i] = qemu_get_be32(f);
7114 for (i = 0; i < 5; i++) {
7115 env->usr_regs[i] = qemu_get_be32(f);
7116 env->fiq_regs[i] = qemu_get_be32(f);
7118 env->cp15.c0_cpuid = qemu_get_be32(f);
7119 env->cp15.c0_cachetype = qemu_get_be32(f);
7120 env->cp15.c1_sys = qemu_get_be32(f);
7121 env->cp15.c1_coproc = qemu_get_be32(f);
7122 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7123 env->cp15.c2_base0 = qemu_get_be32(f);
7124 env->cp15.c2_base1 = qemu_get_be32(f);
7125 env->cp15.c2_mask = qemu_get_be32(f);
7126 env->cp15.c2_data = qemu_get_be32(f);
7127 env->cp15.c2_insn = qemu_get_be32(f);
7128 env->cp15.c3 = qemu_get_be32(f);
7129 env->cp15.c5_insn = qemu_get_be32(f);
7130 env->cp15.c5_data = qemu_get_be32(f);
7131 for (i = 0; i < 8; i++) {
7132 env->cp15.c6_region[i] = qemu_get_be32(f);
7134 env->cp15.c6_insn = qemu_get_be32(f);
7135 env->cp15.c6_data = qemu_get_be32(f);
7136 env->cp15.c9_insn = qemu_get_be32(f);
7137 env->cp15.c9_data = qemu_get_be32(f);
7138 env->cp15.c13_fcse = qemu_get_be32(f);
7139 env->cp15.c13_context = qemu_get_be32(f);
7140 env->cp15.c13_tls1 = qemu_get_be32(f);
7141 env->cp15.c13_tls2 = qemu_get_be32(f);
7142 env->cp15.c13_tls3 = qemu_get_be32(f);
7143 env->cp15.c15_cpar = qemu_get_be32(f);
7145 env->features = qemu_get_be32(f);
7147 if (arm_feature(env, ARM_FEATURE_VFP)) {
7148 for (i = 0; i < 16; i++) {
7149 CPU_DoubleU u;
7150 u.l.upper = qemu_get_be32(f);
7151 u.l.lower = qemu_get_be32(f);
7152 env->vfp.regs[i] = u.d;
7154 for (i = 0; i < 16; i++) {
7155 env->vfp.xregs[i] = qemu_get_be32(f);
7158 /* TODO: Should use proper FPSCR access functions. */
7159 env->vfp.vec_len = qemu_get_be32(f);
7160 env->vfp.vec_stride = qemu_get_be32(f);
7162 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7163 for (i = 0; i < 16; i++) {
7164 CPU_DoubleU u;
7165 u.l.upper = qemu_get_be32(f);
7166 u.l.lower = qemu_get_be32(f);
7167 env->vfp.regs[i] = u.d;
7172 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7173 for (i = 0; i < 16; i++) {
7174 env->iwmmxt.regs[i] = qemu_get_be64(f);
7176 for (i = 0; i < 16; i++) {
7177 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7181 if (arm_feature(env, ARM_FEATURE_M)) {
7182 env->v7m.other_sp = qemu_get_be32(f);
7183 env->v7m.vecbase = qemu_get_be32(f);
7184 env->v7m.basepri = qemu_get_be32(f);
7185 env->v7m.control = qemu_get_be32(f);
7186 env->v7m.current_sp = qemu_get_be32(f);
7187 env->v7m.exception = qemu_get_be32(f);
7190 return 0;
7193 #elif defined(TARGET_IA64)
7194 void cpu_save(QEMUFile *f, void *opaque)
7198 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7200 return 0;
7202 #else
7204 //#warning No CPU save/restore functions
7206 #endif
7208 /***********************************************************/
7209 /* ram save/restore */
7211 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7213 int v;
7215 v = qemu_get_byte(f);
7216 switch(v) {
7217 case 0:
7218 if (qemu_get_buffer(f, buf, len) != len)
7219 return -EIO;
7220 break;
7221 case 1:
7222 v = qemu_get_byte(f);
7223 memset(buf, v, len);
7224 break;
7225 default:
7226 return -EINVAL;
7228 return 0;
7231 static int ram_load_v1(QEMUFile *f, void *opaque)
7233 int i, ret;
7235 if (qemu_get_be32(f) != phys_ram_size)
7236 return -EINVAL;
7237 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7238 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7239 continue;
7240 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7241 if (ret)
7242 return ret;
7244 return 0;
7247 #define BDRV_HASH_BLOCK_SIZE 1024
7248 #define IOBUF_SIZE 4096
7249 #define RAM_CBLOCK_MAGIC 0xfabe
7251 typedef struct RamCompressState {
7252 z_stream zstream;
7253 QEMUFile *f;
7254 uint8_t buf[IOBUF_SIZE];
7255 } RamCompressState;
7257 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7259 int ret;
7260 memset(s, 0, sizeof(*s));
7261 s->f = f;
7262 ret = deflateInit2(&s->zstream, 1,
7263 Z_DEFLATED, 15,
7264 9, Z_DEFAULT_STRATEGY);
7265 if (ret != Z_OK)
7266 return -1;
7267 s->zstream.avail_out = IOBUF_SIZE;
7268 s->zstream.next_out = s->buf;
7269 return 0;
7272 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7274 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7275 qemu_put_be16(s->f, len);
7276 qemu_put_buffer(s->f, buf, len);
7279 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7281 int ret;
7283 s->zstream.avail_in = len;
7284 s->zstream.next_in = (uint8_t *)buf;
7285 while (s->zstream.avail_in > 0) {
7286 ret = deflate(&s->zstream, Z_NO_FLUSH);
7287 if (ret != Z_OK)
7288 return -1;
7289 if (s->zstream.avail_out == 0) {
7290 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7291 s->zstream.avail_out = IOBUF_SIZE;
7292 s->zstream.next_out = s->buf;
7295 return 0;
7298 static void ram_compress_close(RamCompressState *s)
7300 int len, ret;
7302 /* compress last bytes */
7303 for(;;) {
7304 ret = deflate(&s->zstream, Z_FINISH);
7305 if (ret == Z_OK || ret == Z_STREAM_END) {
7306 len = IOBUF_SIZE - s->zstream.avail_out;
7307 if (len > 0) {
7308 ram_put_cblock(s, s->buf, len);
7310 s->zstream.avail_out = IOBUF_SIZE;
7311 s->zstream.next_out = s->buf;
7312 if (ret == Z_STREAM_END)
7313 break;
7314 } else {
7315 goto fail;
7318 fail:
7319 deflateEnd(&s->zstream);
7322 typedef struct RamDecompressState {
7323 z_stream zstream;
7324 QEMUFile *f;
7325 uint8_t buf[IOBUF_SIZE];
7326 } RamDecompressState;
7328 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7330 int ret;
7331 memset(s, 0, sizeof(*s));
7332 s->f = f;
7333 ret = inflateInit(&s->zstream);
7334 if (ret != Z_OK)
7335 return -1;
7336 return 0;
7339 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7341 int ret, clen;
7343 s->zstream.avail_out = len;
7344 s->zstream.next_out = buf;
7345 while (s->zstream.avail_out > 0) {
7346 if (s->zstream.avail_in == 0) {
7347 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7348 return -1;
7349 clen = qemu_get_be16(s->f);
7350 if (clen > IOBUF_SIZE)
7351 return -1;
7352 qemu_get_buffer(s->f, s->buf, clen);
7353 s->zstream.avail_in = clen;
7354 s->zstream.next_in = s->buf;
7356 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7357 if (ret != Z_OK && ret != Z_STREAM_END) {
7358 return -1;
7361 return 0;
7364 static void ram_decompress_close(RamDecompressState *s)
7366 inflateEnd(&s->zstream);
7369 static void ram_save_live(QEMUFile *f, void *opaque)
7371 target_ulong addr;
7373 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7374 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7375 continue;
7376 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7377 qemu_put_be32(f, addr);
7378 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7381 qemu_put_be32(f, 1);
7384 static void ram_save_static(QEMUFile *f, void *opaque)
7386 int i;
7387 RamCompressState s1, *s = &s1;
7388 uint8_t buf[10];
7390 qemu_put_be32(f, phys_ram_size);
7391 if (ram_compress_open(s, f) < 0)
7392 return;
7393 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7394 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7395 continue;
7396 #if 0
7397 if (tight_savevm_enabled) {
7398 int64_t sector_num;
7399 int j;
7401 /* find if the memory block is available on a virtual
7402 block device */
7403 sector_num = -1;
7404 for(j = 0; j < nb_drives; j++) {
7405 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7406 phys_ram_base + i,
7407 BDRV_HASH_BLOCK_SIZE);
7408 if (sector_num >= 0)
7409 break;
7411 if (j == nb_drives)
7412 goto normal_compress;
7413 buf[0] = 1;
7414 buf[1] = j;
7415 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7416 ram_compress_buf(s, buf, 10);
7417 } else
7418 #endif
7420 // normal_compress:
7421 buf[0] = 0;
7422 ram_compress_buf(s, buf, 1);
7423 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7426 ram_compress_close(s);
7429 static void ram_save(QEMUFile *f, void *opaque)
7431 int in_migration = cpu_physical_memory_get_dirty_tracking();
7433 qemu_put_byte(f, in_migration);
7435 if (in_migration)
7436 ram_save_live(f, opaque);
7437 else
7438 ram_save_static(f, opaque);
7441 static int ram_load_live(QEMUFile *f, void *opaque)
7443 target_ulong addr;
7445 do {
7446 addr = qemu_get_be32(f);
7447 if (addr == 1)
7448 break;
7450 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7451 } while (1);
7453 return 0;
7456 static int ram_load_static(QEMUFile *f, void *opaque)
7458 RamDecompressState s1, *s = &s1;
7459 uint8_t buf[10];
7460 int i;
7462 if (qemu_get_be32(f) != phys_ram_size)
7463 return -EINVAL;
7464 if (ram_decompress_open(s, f) < 0)
7465 return -EINVAL;
7466 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7467 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7468 continue;
7469 if (ram_decompress_buf(s, buf, 1) < 0) {
7470 fprintf(stderr, "Error while reading ram block header\n");
7471 goto error;
7473 if (buf[0] == 0) {
7474 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7475 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7476 goto error;
7478 } else
7479 #if 0
7480 if (buf[0] == 1) {
7481 int bs_index;
7482 int64_t sector_num;
7484 ram_decompress_buf(s, buf + 1, 9);
7485 bs_index = buf[1];
7486 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7487 if (bs_index >= nb_drives) {
7488 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7489 goto error;
7491 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7492 phys_ram_base + i,
7493 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7494 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7495 bs_index, sector_num);
7496 goto error;
7498 } else
7499 #endif
7501 error:
7502 printf("Error block header\n");
7503 return -EINVAL;
7506 ram_decompress_close(s);
7507 return 0;
7510 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7512 int ret;
7514 switch (version_id) {
7515 case 1:
7516 ret = ram_load_v1(f, opaque);
7517 break;
7518 case 3:
7519 if (qemu_get_byte(f)) {
7520 ret = ram_load_live(f, opaque);
7521 break;
7523 case 2:
7524 ret = ram_load_static(f, opaque);
7525 break;
7526 default:
7527 ret = -EINVAL;
7528 break;
7531 return ret;
7534 /***********************************************************/
7535 /* bottom halves (can be seen as timers which expire ASAP) */
7537 struct QEMUBH {
7538 QEMUBHFunc *cb;
7539 void *opaque;
7540 int scheduled;
7541 QEMUBH *next;
7544 static QEMUBH *first_bh = NULL;
7546 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7548 QEMUBH *bh;
7549 bh = qemu_mallocz(sizeof(QEMUBH));
7550 if (!bh)
7551 return NULL;
7552 bh->cb = cb;
7553 bh->opaque = opaque;
7554 return bh;
7557 int qemu_bh_poll(void)
7559 QEMUBH *bh, **pbh;
7560 int ret;
7562 ret = 0;
7563 for(;;) {
7564 pbh = &first_bh;
7565 bh = *pbh;
7566 if (!bh)
7567 break;
7568 ret = 1;
7569 *pbh = bh->next;
7570 bh->scheduled = 0;
7571 bh->cb(bh->opaque);
7573 return ret;
7576 void qemu_bh_schedule(QEMUBH *bh)
7578 CPUState *env = cpu_single_env;
7579 if (bh->scheduled)
7580 return;
7581 bh->scheduled = 1;
7582 bh->next = first_bh;
7583 first_bh = bh;
7585 /* stop the currently executing CPU to execute the BH ASAP */
7586 if (env) {
7587 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7591 void qemu_bh_cancel(QEMUBH *bh)
7593 QEMUBH **pbh;
7594 if (bh->scheduled) {
7595 pbh = &first_bh;
7596 while (*pbh != bh)
7597 pbh = &(*pbh)->next;
7598 *pbh = bh->next;
7599 bh->scheduled = 0;
7603 void qemu_bh_delete(QEMUBH *bh)
7605 qemu_bh_cancel(bh);
7606 qemu_free(bh);
7609 /***********************************************************/
7610 /* machine registration */
7612 QEMUMachine *first_machine = NULL;
7613 QEMUMachine *current_machine = NULL;
7615 int qemu_register_machine(QEMUMachine *m)
7617 QEMUMachine **pm;
7618 pm = &first_machine;
7619 while (*pm != NULL)
7620 pm = &(*pm)->next;
7621 m->next = NULL;
7622 *pm = m;
7623 return 0;
7626 static QEMUMachine *find_machine(const char *name)
7628 QEMUMachine *m;
7630 for(m = first_machine; m != NULL; m = m->next) {
7631 if (!strcmp(m->name, name))
7632 return m;
7634 return NULL;
7637 /***********************************************************/
7638 /* main execution loop */
7640 static void gui_update(void *opaque)
7642 DisplayState *ds = opaque;
7643 ds->dpy_refresh(ds);
7644 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7647 struct vm_change_state_entry {
7648 VMChangeStateHandler *cb;
7649 void *opaque;
7650 LIST_ENTRY (vm_change_state_entry) entries;
7653 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7655 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7656 void *opaque)
7658 VMChangeStateEntry *e;
7660 e = qemu_mallocz(sizeof (*e));
7661 if (!e)
7662 return NULL;
7664 e->cb = cb;
7665 e->opaque = opaque;
7666 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7667 return e;
7670 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7672 LIST_REMOVE (e, entries);
7673 qemu_free (e);
7676 static void vm_state_notify(int running)
7678 VMChangeStateEntry *e;
7680 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7681 e->cb(e->opaque, running);
7685 /* XXX: support several handlers */
7686 static VMStopHandler *vm_stop_cb;
7687 static void *vm_stop_opaque;
7689 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7691 vm_stop_cb = cb;
7692 vm_stop_opaque = opaque;
7693 return 0;
7696 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7698 vm_stop_cb = NULL;
7701 void vm_start(void)
7703 if (!vm_running) {
7704 cpu_enable_ticks();
7705 vm_running = 1;
7706 vm_state_notify(1);
7707 qemu_rearm_alarm_timer(alarm_timer);
7711 void vm_stop(int reason)
7713 if (vm_running) {
7714 cpu_disable_ticks();
7715 vm_running = 0;
7716 if (reason != 0) {
7717 if (vm_stop_cb) {
7718 vm_stop_cb(vm_stop_opaque, reason);
7721 vm_state_notify(0);
7725 /* reset/shutdown handler */
7727 typedef struct QEMUResetEntry {
7728 QEMUResetHandler *func;
7729 void *opaque;
7730 struct QEMUResetEntry *next;
7731 } QEMUResetEntry;
7733 static QEMUResetEntry *first_reset_entry;
7734 static int reset_requested;
7735 static int shutdown_requested;
7736 static int powerdown_requested;
7738 int qemu_shutdown_requested(void)
7740 int r = shutdown_requested;
7741 shutdown_requested = 0;
7742 return r;
7745 int qemu_reset_requested(void)
7747 int r = reset_requested;
7748 reset_requested = 0;
7749 return r;
7752 int qemu_powerdown_requested(void)
7754 int r = powerdown_requested;
7755 powerdown_requested = 0;
7756 return r;
7759 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7761 QEMUResetEntry **pre, *re;
7763 pre = &first_reset_entry;
7764 while (*pre != NULL)
7765 pre = &(*pre)->next;
7766 re = qemu_mallocz(sizeof(QEMUResetEntry));
7767 re->func = func;
7768 re->opaque = opaque;
7769 re->next = NULL;
7770 *pre = re;
7773 void qemu_system_reset(void)
7775 QEMUResetEntry *re;
7777 /* reset all devices */
7778 for(re = first_reset_entry; re != NULL; re = re->next) {
7779 re->func(re->opaque);
7783 void qemu_system_reset_request(void)
7785 if (no_reboot) {
7786 shutdown_requested = 1;
7787 } else {
7788 reset_requested = 1;
7790 if (cpu_single_env)
7791 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7794 void qemu_system_shutdown_request(void)
7796 shutdown_requested = 1;
7797 if (cpu_single_env)
7798 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7801 void qemu_system_powerdown_request(void)
7803 powerdown_requested = 1;
7804 if (cpu_single_env)
7805 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7808 void main_loop_wait(int timeout)
7810 IOHandlerRecord *ioh;
7811 fd_set rfds, wfds, xfds;
7812 int ret, nfds;
7813 #ifdef _WIN32
7814 int ret2, i;
7815 #endif
7816 struct timeval tv;
7817 PollingEntry *pe;
7820 /* XXX: need to suppress polling by better using win32 events */
7821 ret = 0;
7822 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7823 ret |= pe->func(pe->opaque);
7825 #ifdef _WIN32
7826 if (ret == 0) {
7827 int err;
7828 WaitObjects *w = &wait_objects;
7830 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7831 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7832 if (w->func[ret - WAIT_OBJECT_0])
7833 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7835 /* Check for additional signaled events */
7836 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7838 /* Check if event is signaled */
7839 ret2 = WaitForSingleObject(w->events[i], 0);
7840 if(ret2 == WAIT_OBJECT_0) {
7841 if (w->func[i])
7842 w->func[i](w->opaque[i]);
7843 } else if (ret2 == WAIT_TIMEOUT) {
7844 } else {
7845 err = GetLastError();
7846 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7849 } else if (ret == WAIT_TIMEOUT) {
7850 } else {
7851 err = GetLastError();
7852 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7855 #endif
7856 /* poll any events */
7857 /* XXX: separate device handlers from system ones */
7858 nfds = -1;
7859 FD_ZERO(&rfds);
7860 FD_ZERO(&wfds);
7861 FD_ZERO(&xfds);
7862 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7863 if (ioh->deleted)
7864 continue;
7865 if (ioh->fd_read &&
7866 (!ioh->fd_read_poll ||
7867 ioh->fd_read_poll(ioh->opaque) != 0)) {
7868 FD_SET(ioh->fd, &rfds);
7869 if (ioh->fd > nfds)
7870 nfds = ioh->fd;
7872 if (ioh->fd_write) {
7873 FD_SET(ioh->fd, &wfds);
7874 if (ioh->fd > nfds)
7875 nfds = ioh->fd;
7879 tv.tv_sec = 0;
7880 #ifdef _WIN32
7881 tv.tv_usec = 0;
7882 #else
7883 tv.tv_usec = timeout * 1000;
7884 #endif
7885 #if defined(CONFIG_SLIRP)
7886 if (slirp_inited) {
7887 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7889 #endif
7890 moreio:
7891 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7892 if (ret > 0) {
7893 IOHandlerRecord **pioh;
7894 int more = 0;
7896 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7897 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7898 ioh->fd_read(ioh->opaque);
7899 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7900 more = 1;
7901 else
7902 FD_CLR(ioh->fd, &rfds);
7904 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7905 ioh->fd_write(ioh->opaque);
7906 more = 1;
7910 /* remove deleted IO handlers */
7911 pioh = &first_io_handler;
7912 while (*pioh) {
7913 ioh = *pioh;
7914 if (ioh->deleted) {
7915 *pioh = ioh->next;
7916 qemu_free(ioh);
7917 } else
7918 pioh = &ioh->next;
7920 if (more)
7921 goto moreio;
7923 #if defined(CONFIG_SLIRP)
7924 if (slirp_inited) {
7925 if (ret < 0) {
7926 FD_ZERO(&rfds);
7927 FD_ZERO(&wfds);
7928 FD_ZERO(&xfds);
7930 slirp_select_poll(&rfds, &wfds, &xfds);
7932 #endif
7933 virtio_net_poll();
7935 qemu_aio_poll();
7937 if (vm_running) {
7938 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7939 qemu_get_clock(vm_clock));
7940 /* run dma transfers, if any */
7941 DMA_run();
7944 /* real time timers */
7945 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7946 qemu_get_clock(rt_clock));
7948 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7949 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7950 qemu_rearm_alarm_timer(alarm_timer);
7953 /* Check bottom-halves last in case any of the earlier events triggered
7954 them. */
7955 qemu_bh_poll();
7959 static int main_loop(void)
7961 int ret, timeout;
7962 #ifdef CONFIG_PROFILER
7963 int64_t ti;
7964 #endif
7965 CPUState *env;
7968 if (kvm_enabled()) {
7969 kvm_main_loop();
7970 cpu_disable_ticks();
7971 return 0;
7974 cur_cpu = first_cpu;
7975 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7976 for(;;) {
7977 if (vm_running) {
7979 for(;;) {
7980 /* get next cpu */
7981 env = next_cpu;
7982 #ifdef CONFIG_PROFILER
7983 ti = profile_getclock();
7984 #endif
7985 ret = cpu_exec(env);
7986 #ifdef CONFIG_PROFILER
7987 qemu_time += profile_getclock() - ti;
7988 #endif
7989 next_cpu = env->next_cpu ?: first_cpu;
7990 if (event_pending) {
7991 ret = EXCP_INTERRUPT;
7992 event_pending = 0;
7993 break;
7995 if (ret == EXCP_HLT) {
7996 /* Give the next CPU a chance to run. */
7997 cur_cpu = env;
7998 continue;
8000 if (ret != EXCP_HALTED)
8001 break;
8002 /* all CPUs are halted ? */
8003 if (env == cur_cpu)
8004 break;
8006 cur_cpu = env;
8008 if (shutdown_requested) {
8009 ret = EXCP_INTERRUPT;
8010 break;
8012 if (reset_requested) {
8013 reset_requested = 0;
8014 qemu_system_reset();
8015 if (kvm_enabled())
8016 kvm_load_registers(env);
8017 ret = EXCP_INTERRUPT;
8019 if (powerdown_requested) {
8020 powerdown_requested = 0;
8021 qemu_system_powerdown();
8022 ret = EXCP_INTERRUPT;
8024 if (ret == EXCP_DEBUG) {
8025 vm_stop(EXCP_DEBUG);
8027 /* If all cpus are halted then wait until the next IRQ */
8028 /* XXX: use timeout computed from timers */
8029 if (ret == EXCP_HALTED)
8030 timeout = 10;
8031 else
8032 timeout = 0;
8033 } else {
8034 timeout = 10;
8036 #ifdef CONFIG_PROFILER
8037 ti = profile_getclock();
8038 #endif
8039 main_loop_wait(timeout);
8040 #ifdef CONFIG_PROFILER
8041 dev_time += profile_getclock() - ti;
8042 #endif
8044 cpu_disable_ticks();
8045 return ret;
8048 static void help(int exitcode)
8050 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8051 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8052 "usage: %s [options] [disk_image]\n"
8053 "\n"
8054 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8055 "\n"
8056 "Standard options:\n"
8057 "-M machine select emulated machine (-M ? for list)\n"
8058 "-cpu cpu select CPU (-cpu ? for list)\n"
8059 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8060 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8061 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8062 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8063 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
8064 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
8065 " [,cache=on|off][,boot=on|off]\n"
8066 " use 'file' as a drive image\n"
8067 "-mtdblock file use 'file' as on-board Flash memory image\n"
8068 "-sd file use 'file' as SecureDigital card image\n"
8069 "-pflash file use 'file' as a parallel flash image\n"
8070 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8071 "-snapshot write to temporary files instead of disk image files\n"
8072 #ifdef CONFIG_SDL
8073 "-no-frame open SDL window without a frame and window decorations\n"
8074 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8075 "-no-quit disable SDL window close capability\n"
8076 #endif
8077 #ifdef TARGET_I386
8078 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8079 #endif
8080 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8081 "-smp n set the number of CPUs to 'n' [default=1]\n"
8082 "-nographic disable graphical output and redirect serial I/Os to console\n"
8083 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8084 #ifndef _WIN32
8085 "-k language use keyboard layout (for example \"fr\" for French)\n"
8086 #endif
8087 #ifdef HAS_AUDIO
8088 "-audio-help print list of audio drivers and their options\n"
8089 "-soundhw c1,... enable audio support\n"
8090 " and only specified sound cards (comma separated list)\n"
8091 " use -soundhw ? to get the list of supported cards\n"
8092 " use -soundhw all to enable all of them\n"
8093 #endif
8094 "-localtime set the real time clock to local time [default=utc]\n"
8095 "-full-screen start in full screen\n"
8096 #ifdef TARGET_I386
8097 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8098 #endif
8099 "-usb enable the USB driver (will be the default soon)\n"
8100 "-usbdevice name add the host or guest USB device 'name'\n"
8101 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8102 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8103 #endif
8104 "-name string set the name of the guest\n"
8105 "\n"
8106 "Network options:\n"
8107 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8108 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8109 #ifdef CONFIG_SLIRP
8110 "-net user[,vlan=n][,hostname=host]\n"
8111 " connect the user mode network stack to VLAN 'n' and send\n"
8112 " hostname 'host' to DHCP clients\n"
8113 #endif
8114 #ifdef _WIN32
8115 "-net tap[,vlan=n],ifname=name\n"
8116 " connect the host TAP network interface to VLAN 'n'\n"
8117 #else
8118 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8119 " connect the host TAP network interface to VLAN 'n' and use the\n"
8120 " network scripts 'file' (default=%s)\n"
8121 " and 'dfile' (default=%s);\n"
8122 " use '[down]script=no' to disable script execution;\n"
8123 " use 'fd=h' to connect to an already opened TAP interface\n"
8124 #endif
8125 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8126 " connect the vlan 'n' to another VLAN using a socket connection\n"
8127 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8128 " connect the vlan 'n' to multicast maddr and port\n"
8129 "-net none use it alone to have zero network devices; if no -net option\n"
8130 " is provided, the default is '-net nic -net user'\n"
8131 "\n"
8132 #ifdef CONFIG_SLIRP
8133 "-tftp dir allow tftp access to files in dir [-net user]\n"
8134 "-bootp file advertise file in BOOTP replies\n"
8135 #ifndef _WIN32
8136 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8137 #endif
8138 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8139 " redirect TCP or UDP connections from host to guest [-net user]\n"
8140 #endif
8141 "\n"
8142 "Linux boot specific:\n"
8143 "-kernel bzImage use 'bzImage' as kernel image\n"
8144 "-append cmdline use 'cmdline' as kernel command line\n"
8145 "-initrd file use 'file' as initial ram disk\n"
8146 "\n"
8147 "Debug/Expert options:\n"
8148 "-monitor dev redirect the monitor to char device 'dev'\n"
8149 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8150 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8151 "-serial dev redirect the serial port to char device 'dev'\n"
8152 "-parallel dev redirect the parallel port to char device 'dev'\n"
8153 "-pidfile file Write PID to 'file'\n"
8154 "-S freeze CPU at startup (use 'c' to start execution)\n"
8155 "-s wait gdb connection to port\n"
8156 "-p port set gdb connection port [default=%s]\n"
8157 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8158 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8159 " translation (t=none or lba) (usually qemu can guess them)\n"
8160 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8161 #ifdef USE_KQEMU
8162 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8163 "-no-kqemu disable KQEMU kernel module usage\n"
8164 #endif
8165 #ifdef USE_KVM
8166 #ifndef NO_CPU_EMULATION
8167 "-no-kvm disable KVM hardware virtualization\n"
8168 #endif
8169 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8170 "-no-kvm-pit disable KVM kernel mode PIT\n"
8171 #endif
8172 #ifdef TARGET_I386
8173 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8174 " (default is CL-GD5446 PCI VGA)\n"
8175 "-no-acpi disable ACPI\n"
8176 #endif
8177 #ifdef CONFIG_CURSES
8178 "-curses use a curses/ncurses interface instead of SDL\n"
8179 #endif
8180 "-no-reboot exit instead of rebooting\n"
8181 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8182 "-vnc display start a VNC server on display\n"
8183 #ifndef _WIN32
8184 "-daemonize daemonize QEMU after initializing\n"
8185 #endif
8186 "-tdf inject timer interrupts that got lost\n"
8187 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8188 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8189 "-option-rom rom load a file, rom, into the option ROM space\n"
8190 #ifdef TARGET_SPARC
8191 "-prom-env variable=value set OpenBIOS nvram variables\n"
8192 #endif
8193 "-clock force the use of the given methods for timer alarm.\n"
8194 " To see what timers are available use -clock help\n"
8195 "-startdate select initial date of the clock\n"
8196 "\n"
8197 "During emulation, the following keys are useful:\n"
8198 "ctrl-alt-f toggle full screen\n"
8199 "ctrl-alt-n switch to virtual console 'n'\n"
8200 "ctrl-alt toggle mouse and keyboard grab\n"
8201 "\n"
8202 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8204 "qemu",
8205 DEFAULT_RAM_SIZE,
8206 #ifndef _WIN32
8207 DEFAULT_NETWORK_SCRIPT,
8208 DEFAULT_NETWORK_DOWN_SCRIPT,
8209 #endif
8210 DEFAULT_GDBSTUB_PORT,
8211 "/tmp/qemu.log");
8212 exit(exitcode);
8215 #define HAS_ARG 0x0001
8217 enum {
8218 QEMU_OPTION_h,
8220 QEMU_OPTION_M,
8221 QEMU_OPTION_cpu,
8222 QEMU_OPTION_fda,
8223 QEMU_OPTION_fdb,
8224 QEMU_OPTION_hda,
8225 QEMU_OPTION_hdb,
8226 QEMU_OPTION_hdc,
8227 QEMU_OPTION_hdd,
8228 QEMU_OPTION_drive,
8229 QEMU_OPTION_cdrom,
8230 QEMU_OPTION_mtdblock,
8231 QEMU_OPTION_sd,
8232 QEMU_OPTION_pflash,
8233 QEMU_OPTION_boot,
8234 QEMU_OPTION_snapshot,
8235 #ifdef TARGET_I386
8236 QEMU_OPTION_no_fd_bootchk,
8237 #endif
8238 QEMU_OPTION_m,
8239 QEMU_OPTION_nographic,
8240 QEMU_OPTION_portrait,
8241 #ifdef HAS_AUDIO
8242 QEMU_OPTION_audio_help,
8243 QEMU_OPTION_soundhw,
8244 #endif
8246 QEMU_OPTION_net,
8247 QEMU_OPTION_tftp,
8248 QEMU_OPTION_bootp,
8249 QEMU_OPTION_smb,
8250 QEMU_OPTION_redir,
8252 QEMU_OPTION_kernel,
8253 QEMU_OPTION_append,
8254 QEMU_OPTION_initrd,
8256 QEMU_OPTION_S,
8257 QEMU_OPTION_s,
8258 QEMU_OPTION_p,
8259 QEMU_OPTION_d,
8260 QEMU_OPTION_hdachs,
8261 QEMU_OPTION_L,
8262 QEMU_OPTION_bios,
8263 QEMU_OPTION_no_code_copy,
8264 QEMU_OPTION_k,
8265 QEMU_OPTION_localtime,
8266 QEMU_OPTION_cirrusvga,
8267 QEMU_OPTION_vmsvga,
8268 QEMU_OPTION_g,
8269 QEMU_OPTION_std_vga,
8270 QEMU_OPTION_echr,
8271 QEMU_OPTION_monitor,
8272 QEMU_OPTION_balloon,
8273 QEMU_OPTION_vmchannel,
8274 QEMU_OPTION_serial,
8275 QEMU_OPTION_parallel,
8276 QEMU_OPTION_loadvm,
8277 QEMU_OPTION_full_screen,
8278 QEMU_OPTION_no_frame,
8279 QEMU_OPTION_alt_grab,
8280 QEMU_OPTION_no_quit,
8281 QEMU_OPTION_pidfile,
8282 QEMU_OPTION_no_kqemu,
8283 QEMU_OPTION_kernel_kqemu,
8284 QEMU_OPTION_win2k_hack,
8285 QEMU_OPTION_usb,
8286 QEMU_OPTION_usbdevice,
8287 QEMU_OPTION_smp,
8288 QEMU_OPTION_vnc,
8289 QEMU_OPTION_no_acpi,
8290 QEMU_OPTION_curses,
8291 QEMU_OPTION_no_kvm,
8292 QEMU_OPTION_no_kvm_irqchip,
8293 QEMU_OPTION_no_kvm_pit,
8294 QEMU_OPTION_no_reboot,
8295 QEMU_OPTION_show_cursor,
8296 QEMU_OPTION_daemonize,
8297 QEMU_OPTION_option_rom,
8298 QEMU_OPTION_semihosting,
8299 QEMU_OPTION_cpu_vendor,
8300 QEMU_OPTION_name,
8301 QEMU_OPTION_prom_env,
8302 QEMU_OPTION_old_param,
8303 QEMU_OPTION_clock,
8304 QEMU_OPTION_startdate,
8305 QEMU_OPTION_translation,
8306 QEMU_OPTION_incoming,
8307 QEMU_OPTION_tdf,
8308 QEMU_OPTION_kvm_shadow_memory,
8309 QEMU_OPTION_mempath,
8312 typedef struct QEMUOption {
8313 const char *name;
8314 int flags;
8315 int index;
8316 } QEMUOption;
8318 const QEMUOption qemu_options[] = {
8319 { "h", 0, QEMU_OPTION_h },
8320 { "help", 0, QEMU_OPTION_h },
8322 { "M", HAS_ARG, QEMU_OPTION_M },
8323 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8324 { "fda", HAS_ARG, QEMU_OPTION_fda },
8325 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8326 { "hda", HAS_ARG, QEMU_OPTION_hda },
8327 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8328 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8329 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8330 { "drive", HAS_ARG, QEMU_OPTION_drive },
8331 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8332 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8333 { "sd", HAS_ARG, QEMU_OPTION_sd },
8334 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8335 { "boot", HAS_ARG, QEMU_OPTION_boot },
8336 { "snapshot", 0, QEMU_OPTION_snapshot },
8337 #ifdef TARGET_I386
8338 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8339 #endif
8340 { "m", HAS_ARG, QEMU_OPTION_m },
8341 { "nographic", 0, QEMU_OPTION_nographic },
8342 { "portrait", 0, QEMU_OPTION_portrait },
8343 { "k", HAS_ARG, QEMU_OPTION_k },
8344 #ifdef HAS_AUDIO
8345 { "audio-help", 0, QEMU_OPTION_audio_help },
8346 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8347 #endif
8349 { "net", HAS_ARG, QEMU_OPTION_net},
8350 #ifdef CONFIG_SLIRP
8351 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8352 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8353 #ifndef _WIN32
8354 { "smb", HAS_ARG, QEMU_OPTION_smb },
8355 #endif
8356 { "redir", HAS_ARG, QEMU_OPTION_redir },
8357 #endif
8359 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8360 { "append", HAS_ARG, QEMU_OPTION_append },
8361 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8363 { "S", 0, QEMU_OPTION_S },
8364 { "s", 0, QEMU_OPTION_s },
8365 { "p", HAS_ARG, QEMU_OPTION_p },
8366 { "d", HAS_ARG, QEMU_OPTION_d },
8367 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8368 { "L", HAS_ARG, QEMU_OPTION_L },
8369 { "bios", HAS_ARG, QEMU_OPTION_bios },
8370 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8371 #ifdef USE_KQEMU
8372 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8373 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8374 #endif
8375 #ifdef USE_KVM
8376 #ifndef NO_CPU_EMULATION
8377 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8378 #endif
8379 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8380 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8381 #endif
8382 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8383 { "g", 1, QEMU_OPTION_g },
8384 #endif
8385 { "localtime", 0, QEMU_OPTION_localtime },
8386 { "std-vga", 0, QEMU_OPTION_std_vga },
8387 { "monitor", 1, QEMU_OPTION_monitor },
8388 { "balloon", 1, QEMU_OPTION_balloon },
8389 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8390 { "echr", HAS_ARG, QEMU_OPTION_echr },
8391 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8392 { "serial", HAS_ARG, QEMU_OPTION_serial },
8393 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8394 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8395 { "incoming", 1, QEMU_OPTION_incoming },
8396 { "full-screen", 0, QEMU_OPTION_full_screen },
8397 #ifdef CONFIG_SDL
8398 { "no-frame", 0, QEMU_OPTION_no_frame },
8399 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8400 { "no-quit", 0, QEMU_OPTION_no_quit },
8401 #endif
8402 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8403 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8404 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8405 { "smp", HAS_ARG, QEMU_OPTION_smp },
8406 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8407 #ifdef CONFIG_CURSES
8408 { "curses", 0, QEMU_OPTION_curses },
8409 #endif
8411 /* temporary options */
8412 { "usb", 0, QEMU_OPTION_usb },
8413 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8414 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8415 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8416 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8417 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8418 { "daemonize", 0, QEMU_OPTION_daemonize },
8419 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8420 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8421 { "semihosting", 0, QEMU_OPTION_semihosting },
8422 #endif
8423 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8424 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8425 { "name", HAS_ARG, QEMU_OPTION_name },
8426 #if defined(TARGET_SPARC)
8427 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8428 #endif
8429 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8430 #if defined(TARGET_ARM)
8431 { "old-param", 0, QEMU_OPTION_old_param },
8432 #endif
8433 { "clock", HAS_ARG, QEMU_OPTION_clock },
8434 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8435 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8436 { NULL },
8439 /* password input */
8441 int qemu_key_check(BlockDriverState *bs, const char *name)
8443 char password[256];
8444 int i;
8446 if (!bdrv_is_encrypted(bs))
8447 return 0;
8449 term_printf("%s is encrypted.\n", name);
8450 for(i = 0; i < 3; i++) {
8451 monitor_readline("Password: ", 1, password, sizeof(password));
8452 if (bdrv_set_key(bs, password) == 0)
8453 return 0;
8454 term_printf("invalid password\n");
8456 return -EPERM;
8459 static BlockDriverState *get_bdrv(int index)
8461 if (index > nb_drives)
8462 return NULL;
8463 return drives_table[index].bdrv;
8466 static void read_passwords(void)
8468 BlockDriverState *bs;
8469 int i;
8471 for(i = 0; i < 6; i++) {
8472 bs = get_bdrv(i);
8473 if (bs)
8474 qemu_key_check(bs, bdrv_get_device_name(bs));
8478 /* XXX: currently we cannot use simultaneously different CPUs */
8479 static void register_machines(void)
8481 #if defined(TARGET_I386)
8482 qemu_register_machine(&pc_machine);
8483 qemu_register_machine(&isapc_machine);
8484 #elif defined(TARGET_PPC)
8485 qemu_register_machine(&heathrow_machine);
8486 qemu_register_machine(&core99_machine);
8487 qemu_register_machine(&prep_machine);
8488 qemu_register_machine(&ref405ep_machine);
8489 qemu_register_machine(&taihu_machine);
8490 qemu_register_machine(&bamboo_machine);
8491 #elif defined(TARGET_MIPS)
8492 qemu_register_machine(&mips_machine);
8493 qemu_register_machine(&mips_malta_machine);
8494 qemu_register_machine(&mips_pica61_machine);
8495 qemu_register_machine(&mips_mipssim_machine);
8496 #elif defined(TARGET_SPARC)
8497 #ifdef TARGET_SPARC64
8498 qemu_register_machine(&sun4u_machine);
8499 #else
8500 qemu_register_machine(&ss5_machine);
8501 qemu_register_machine(&ss10_machine);
8502 qemu_register_machine(&ss600mp_machine);
8503 qemu_register_machine(&ss20_machine);
8504 qemu_register_machine(&ss2_machine);
8505 qemu_register_machine(&ss1000_machine);
8506 qemu_register_machine(&ss2000_machine);
8507 #endif
8508 #elif defined(TARGET_ARM)
8509 qemu_register_machine(&integratorcp_machine);
8510 qemu_register_machine(&versatilepb_machine);
8511 qemu_register_machine(&versatileab_machine);
8512 qemu_register_machine(&realview_machine);
8513 qemu_register_machine(&akitapda_machine);
8514 qemu_register_machine(&spitzpda_machine);
8515 qemu_register_machine(&borzoipda_machine);
8516 qemu_register_machine(&terrierpda_machine);
8517 qemu_register_machine(&palmte_machine);
8518 qemu_register_machine(&lm3s811evb_machine);
8519 qemu_register_machine(&lm3s6965evb_machine);
8520 qemu_register_machine(&connex_machine);
8521 qemu_register_machine(&verdex_machine);
8522 qemu_register_machine(&mainstone2_machine);
8523 #elif defined(TARGET_SH4)
8524 qemu_register_machine(&shix_machine);
8525 qemu_register_machine(&r2d_machine);
8526 #elif defined(TARGET_ALPHA)
8527 /* XXX: TODO */
8528 #elif defined(TARGET_M68K)
8529 qemu_register_machine(&mcf5208evb_machine);
8530 qemu_register_machine(&an5206_machine);
8531 qemu_register_machine(&dummy_m68k_machine);
8532 #elif defined(TARGET_CRIS)
8533 qemu_register_machine(&bareetraxfs_machine);
8534 #elif defined(TARGET_IA64)
8535 qemu_register_machine(&ipf_machine);
8536 #else
8537 #error unsupported CPU
8538 #endif
8541 #ifdef HAS_AUDIO
8542 struct soundhw soundhw[] = {
8543 #ifdef HAS_AUDIO_CHOICE
8544 #ifdef TARGET_I386
8546 "pcspk",
8547 "PC speaker",
8550 { .init_isa = pcspk_audio_init }
8552 #endif
8554 "sb16",
8555 "Creative Sound Blaster 16",
8558 { .init_isa = SB16_init }
8561 #ifdef CONFIG_ADLIB
8563 "adlib",
8564 #ifdef HAS_YMF262
8565 "Yamaha YMF262 (OPL3)",
8566 #else
8567 "Yamaha YM3812 (OPL2)",
8568 #endif
8571 { .init_isa = Adlib_init }
8573 #endif
8575 #ifdef CONFIG_GUS
8577 "gus",
8578 "Gravis Ultrasound GF1",
8581 { .init_isa = GUS_init }
8583 #endif
8585 #ifdef CONFIG_AC97
8587 "ac97",
8588 "Intel 82801AA AC97 Audio",
8591 { .init_pci = ac97_init }
8593 #endif
8596 "es1370",
8597 "ENSONIQ AudioPCI ES1370",
8600 { .init_pci = es1370_init }
8602 #endif
8604 { NULL, NULL, 0, 0, { NULL } }
8607 static void select_soundhw (const char *optarg)
8609 struct soundhw *c;
8611 if (*optarg == '?') {
8612 show_valid_cards:
8614 printf ("Valid sound card names (comma separated):\n");
8615 for (c = soundhw; c->name; ++c) {
8616 printf ("%-11s %s\n", c->name, c->descr);
8618 printf ("\n-soundhw all will enable all of the above\n");
8619 exit (*optarg != '?');
8621 else {
8622 size_t l;
8623 const char *p;
8624 char *e;
8625 int bad_card = 0;
8627 if (!strcmp (optarg, "all")) {
8628 for (c = soundhw; c->name; ++c) {
8629 c->enabled = 1;
8631 return;
8634 p = optarg;
8635 while (*p) {
8636 e = strchr (p, ',');
8637 l = !e ? strlen (p) : (size_t) (e - p);
8639 for (c = soundhw; c->name; ++c) {
8640 if (!strncmp (c->name, p, l)) {
8641 c->enabled = 1;
8642 break;
8646 if (!c->name) {
8647 if (l > 80) {
8648 fprintf (stderr,
8649 "Unknown sound card name (too big to show)\n");
8651 else {
8652 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8653 (int) l, p);
8655 bad_card = 1;
8657 p += l + (e != NULL);
8660 if (bad_card)
8661 goto show_valid_cards;
8664 #endif
8666 #ifdef _WIN32
8667 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8669 exit(STATUS_CONTROL_C_EXIT);
8670 return TRUE;
8672 #endif
8674 #define MAX_NET_CLIENTS 32
8676 static int saved_argc;
8677 static char **saved_argv;
8679 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8681 *argc = saved_argc;
8682 *argv = saved_argv;
8683 *opt_daemonize = daemonize;
8684 *opt_incoming = incoming;
8688 static int gethugepagesize(void)
8690 int ret, fd;
8691 char buf[4096];
8692 char *needle = "Hugepagesize:";
8693 char *size;
8694 unsigned long hugepagesize;
8696 fd = open("/proc/meminfo", O_RDONLY);
8697 if (fd < 0) {
8698 perror("open");
8699 exit(0);
8702 ret = read(fd, buf, sizeof(buf));
8703 if (ret < 0) {
8704 perror("read");
8705 exit(0);
8708 size = strstr(buf, needle);
8709 if (!size)
8710 return 0;
8711 size += strlen(needle);
8712 hugepagesize = strtol(size, NULL, 0);
8713 return hugepagesize;
8716 void *alloc_mem_area(unsigned long memory, const char *path)
8718 char *filename;
8719 void *area;
8720 int fd;
8722 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8723 return NULL;
8725 hpagesize = gethugepagesize() * 1024;
8726 if (!hpagesize)
8727 return NULL;
8729 fd = mkstemp(filename);
8730 if (fd < 0) {
8731 perror("mkstemp");
8732 free(filename);
8733 return NULL;
8735 unlink(filename);
8736 free(filename);
8738 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8740 if (ftruncate(fd, memory) == -1) {
8741 perror("ftruncate");
8742 close(fd);
8743 return NULL;
8746 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8747 if (area == MAP_FAILED) {
8748 perror("mmap");
8749 close(fd);
8750 return NULL;
8753 return area;
8756 void *qemu_alloc_physram(unsigned long memory)
8758 void *area = NULL;
8760 if (mem_path)
8761 area = alloc_mem_area(memory, mem_path);
8762 if (!area)
8763 area = qemu_vmalloc(memory);
8765 return area;
8768 int main(int argc, char **argv)
8770 #ifdef CONFIG_GDBSTUB
8771 int use_gdbstub;
8772 const char *gdbstub_port;
8773 #endif
8774 uint32_t boot_devices_bitmap = 0;
8775 int i;
8776 int snapshot, linux_boot, net_boot;
8777 const char *initrd_filename;
8778 const char *kernel_filename, *kernel_cmdline;
8779 const char *boot_devices = "";
8780 DisplayState *ds = &display_state;
8781 int cyls, heads, secs, translation;
8782 char net_clients[MAX_NET_CLIENTS][256];
8783 int nb_net_clients;
8784 int hda_index;
8785 int optind;
8786 const char *r, *optarg;
8787 CharDriverState *monitor_hd;
8788 char monitor_device[128];
8789 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8790 int vmchannel_device_index;
8791 char serial_devices[MAX_SERIAL_PORTS][128];
8792 int serial_device_index;
8793 char parallel_devices[MAX_PARALLEL_PORTS][128];
8794 int parallel_device_index;
8795 const char *loadvm = NULL;
8796 QEMUMachine *machine;
8797 const char *cpu_model;
8798 char usb_devices[MAX_USB_CMDLINE][128];
8799 int usb_devices_index;
8800 int fds[2];
8801 const char *pid_file = NULL;
8802 VLANState *vlan;
8804 saved_argc = argc;
8805 saved_argv = argv;
8807 LIST_INIT (&vm_change_state_head);
8808 #ifndef _WIN32
8810 struct sigaction act;
8811 sigfillset(&act.sa_mask);
8812 act.sa_flags = 0;
8813 act.sa_handler = SIG_IGN;
8814 sigaction(SIGPIPE, &act, NULL);
8816 #else
8817 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8818 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8819 QEMU to run on a single CPU */
8821 HANDLE h;
8822 DWORD mask, smask;
8823 int i;
8824 h = GetCurrentProcess();
8825 if (GetProcessAffinityMask(h, &mask, &smask)) {
8826 for(i = 0; i < 32; i++) {
8827 if (mask & (1 << i))
8828 break;
8830 if (i != 32) {
8831 mask = 1 << i;
8832 SetProcessAffinityMask(h, mask);
8836 #endif
8838 register_machines();
8839 machine = first_machine;
8840 cpu_model = NULL;
8841 initrd_filename = NULL;
8842 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8843 vga_ram_size = VGA_RAM_SIZE;
8844 #ifdef CONFIG_GDBSTUB
8845 use_gdbstub = 0;
8846 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8847 #endif
8848 snapshot = 0;
8849 nographic = 0;
8850 curses = 0;
8851 kernel_filename = NULL;
8852 kernel_cmdline = "";
8853 cyls = heads = secs = 0;
8854 translation = BIOS_ATA_TRANSLATION_AUTO;
8855 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8857 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8858 vmchannel_devices[i][0] = '\0';
8859 vmchannel_device_index = 0;
8861 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8862 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8863 serial_devices[i][0] = '\0';
8864 serial_device_index = 0;
8866 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8867 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8868 parallel_devices[i][0] = '\0';
8869 parallel_device_index = 0;
8871 usb_devices_index = 0;
8873 nb_net_clients = 0;
8874 nb_drives = 0;
8875 nb_drives_opt = 0;
8876 hda_index = -1;
8878 nb_nics = 0;
8879 /* default mac address of the first network interface */
8881 optind = 1;
8882 for(;;) {
8883 if (optind >= argc)
8884 break;
8885 r = argv[optind];
8886 if (r[0] != '-') {
8887 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8888 } else {
8889 const QEMUOption *popt;
8891 optind++;
8892 /* Treat --foo the same as -foo. */
8893 if (r[1] == '-')
8894 r++;
8895 popt = qemu_options;
8896 for(;;) {
8897 if (!popt->name) {
8898 fprintf(stderr, "%s: invalid option -- '%s'\n",
8899 argv[0], r);
8900 exit(1);
8902 if (!strcmp(popt->name, r + 1))
8903 break;
8904 popt++;
8906 if (popt->flags & HAS_ARG) {
8907 if (optind >= argc) {
8908 fprintf(stderr, "%s: option '%s' requires an argument\n",
8909 argv[0], r);
8910 exit(1);
8912 optarg = argv[optind++];
8913 } else {
8914 optarg = NULL;
8917 switch(popt->index) {
8918 case QEMU_OPTION_M:
8919 machine = find_machine(optarg);
8920 if (!machine) {
8921 QEMUMachine *m;
8922 printf("Supported machines are:\n");
8923 for(m = first_machine; m != NULL; m = m->next) {
8924 printf("%-10s %s%s\n",
8925 m->name, m->desc,
8926 m == first_machine ? " (default)" : "");
8928 exit(*optarg != '?');
8930 break;
8931 case QEMU_OPTION_cpu:
8932 /* hw initialization will check this */
8933 if (*optarg == '?') {
8934 /* XXX: implement xxx_cpu_list for targets that still miss it */
8935 #if defined(cpu_list)
8936 cpu_list(stdout, &fprintf);
8937 #endif
8938 exit(0);
8939 } else {
8940 cpu_model = optarg;
8942 break;
8943 case QEMU_OPTION_initrd:
8944 initrd_filename = optarg;
8945 break;
8946 case QEMU_OPTION_hda:
8947 if (cyls == 0)
8948 hda_index = drive_add(optarg, HD_ALIAS, 0);
8949 else
8950 hda_index = drive_add(optarg, HD_ALIAS
8951 ",cyls=%d,heads=%d,secs=%d%s",
8952 0, cyls, heads, secs,
8953 translation == BIOS_ATA_TRANSLATION_LBA ?
8954 ",trans=lba" :
8955 translation == BIOS_ATA_TRANSLATION_NONE ?
8956 ",trans=none" : "");
8957 break;
8958 case QEMU_OPTION_hdb:
8959 case QEMU_OPTION_hdc:
8960 case QEMU_OPTION_hdd:
8961 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8962 break;
8963 case QEMU_OPTION_drive:
8964 drive_add(NULL, "%s", optarg);
8965 break;
8966 case QEMU_OPTION_mtdblock:
8967 drive_add(optarg, MTD_ALIAS);
8968 break;
8969 case QEMU_OPTION_sd:
8970 drive_add(optarg, SD_ALIAS);
8971 break;
8972 case QEMU_OPTION_pflash:
8973 drive_add(optarg, PFLASH_ALIAS);
8974 break;
8975 case QEMU_OPTION_snapshot:
8976 snapshot = 1;
8977 break;
8978 case QEMU_OPTION_hdachs:
8980 const char *p;
8981 p = optarg;
8982 cyls = strtol(p, (char **)&p, 0);
8983 if (cyls < 1 || cyls > 16383)
8984 goto chs_fail;
8985 if (*p != ',')
8986 goto chs_fail;
8987 p++;
8988 heads = strtol(p, (char **)&p, 0);
8989 if (heads < 1 || heads > 16)
8990 goto chs_fail;
8991 if (*p != ',')
8992 goto chs_fail;
8993 p++;
8994 secs = strtol(p, (char **)&p, 0);
8995 if (secs < 1 || secs > 63)
8996 goto chs_fail;
8997 if (*p == ',') {
8998 p++;
8999 if (!strcmp(p, "none"))
9000 translation = BIOS_ATA_TRANSLATION_NONE;
9001 else if (!strcmp(p, "lba"))
9002 translation = BIOS_ATA_TRANSLATION_LBA;
9003 else if (!strcmp(p, "auto"))
9004 translation = BIOS_ATA_TRANSLATION_AUTO;
9005 else
9006 goto chs_fail;
9007 } else if (*p != '\0') {
9008 chs_fail:
9009 fprintf(stderr, "qemu: invalid physical CHS format\n");
9010 exit(1);
9012 if (hda_index != -1)
9013 snprintf(drives_opt[hda_index].opt,
9014 sizeof(drives_opt[hda_index].opt),
9015 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9016 0, cyls, heads, secs,
9017 translation == BIOS_ATA_TRANSLATION_LBA ?
9018 ",trans=lba" :
9019 translation == BIOS_ATA_TRANSLATION_NONE ?
9020 ",trans=none" : "");
9022 break;
9023 case QEMU_OPTION_nographic:
9024 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
9025 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
9026 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
9027 nographic = 1;
9028 break;
9029 #ifdef CONFIG_CURSES
9030 case QEMU_OPTION_curses:
9031 curses = 1;
9032 break;
9033 #endif
9034 case QEMU_OPTION_portrait:
9035 graphic_rotate = 1;
9036 break;
9037 case QEMU_OPTION_kernel:
9038 kernel_filename = optarg;
9039 break;
9040 case QEMU_OPTION_append:
9041 kernel_cmdline = optarg;
9042 break;
9043 case QEMU_OPTION_cdrom:
9044 drive_add(optarg, CDROM_ALIAS);
9045 break;
9046 case QEMU_OPTION_boot:
9047 boot_devices = optarg;
9048 /* We just do some generic consistency checks */
9050 /* Could easily be extended to 64 devices if needed */
9051 const char *p;
9053 boot_devices_bitmap = 0;
9054 for (p = boot_devices; *p != '\0'; p++) {
9055 /* Allowed boot devices are:
9056 * a b : floppy disk drives
9057 * c ... f : IDE disk drives
9058 * g ... m : machine implementation dependant drives
9059 * n ... p : network devices
9060 * It's up to each machine implementation to check
9061 * if the given boot devices match the actual hardware
9062 * implementation and firmware features.
9064 if (*p < 'a' || *p > 'q') {
9065 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9066 exit(1);
9068 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9069 fprintf(stderr,
9070 "Boot device '%c' was given twice\n",*p);
9071 exit(1);
9073 boot_devices_bitmap |= 1 << (*p - 'a');
9076 break;
9077 case QEMU_OPTION_fda:
9078 case QEMU_OPTION_fdb:
9079 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9080 break;
9081 #ifdef TARGET_I386
9082 case QEMU_OPTION_no_fd_bootchk:
9083 fd_bootchk = 0;
9084 break;
9085 #endif
9086 case QEMU_OPTION_no_code_copy:
9087 code_copy_enabled = 0;
9088 break;
9089 case QEMU_OPTION_net:
9090 if (nb_net_clients >= MAX_NET_CLIENTS) {
9091 fprintf(stderr, "qemu: too many network clients\n");
9092 exit(1);
9094 pstrcpy(net_clients[nb_net_clients],
9095 sizeof(net_clients[0]),
9096 optarg);
9097 nb_net_clients++;
9098 break;
9099 #ifdef CONFIG_SLIRP
9100 case QEMU_OPTION_tftp:
9101 tftp_prefix = optarg;
9102 break;
9103 case QEMU_OPTION_bootp:
9104 bootp_filename = optarg;
9105 break;
9106 #ifndef _WIN32
9107 case QEMU_OPTION_smb:
9108 net_slirp_smb(optarg);
9109 break;
9110 #endif
9111 case QEMU_OPTION_redir:
9112 net_slirp_redir(optarg);
9113 break;
9114 #endif
9115 #ifdef HAS_AUDIO
9116 case QEMU_OPTION_audio_help:
9117 AUD_help ();
9118 exit (0);
9119 break;
9120 case QEMU_OPTION_soundhw:
9121 select_soundhw (optarg);
9122 break;
9123 #endif
9124 case QEMU_OPTION_h:
9125 help(0);
9126 break;
9127 case QEMU_OPTION_m:
9128 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9129 if (ram_size <= 0)
9130 help(1);
9131 if (ram_size > PHYS_RAM_MAX_SIZE) {
9132 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9133 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9134 exit(1);
9136 break;
9137 case QEMU_OPTION_d:
9139 int mask;
9140 CPULogItem *item;
9142 mask = cpu_str_to_log_mask(optarg);
9143 if (!mask) {
9144 printf("Log items (comma separated):\n");
9145 for(item = cpu_log_items; item->mask != 0; item++) {
9146 printf("%-10s %s\n", item->name, item->help);
9148 exit(1);
9150 cpu_set_log(mask);
9152 break;
9153 #ifdef CONFIG_GDBSTUB
9154 case QEMU_OPTION_s:
9155 use_gdbstub = 1;
9156 break;
9157 case QEMU_OPTION_p:
9158 gdbstub_port = optarg;
9159 break;
9160 #endif
9161 case QEMU_OPTION_L:
9162 bios_dir = optarg;
9163 break;
9164 case QEMU_OPTION_bios:
9165 bios_name = optarg;
9166 break;
9167 case QEMU_OPTION_S:
9168 autostart = 0;
9169 break;
9170 case QEMU_OPTION_k:
9171 keyboard_layout = optarg;
9172 break;
9173 case QEMU_OPTION_localtime:
9174 rtc_utc = 0;
9175 break;
9176 case QEMU_OPTION_cirrusvga:
9177 cirrus_vga_enabled = 1;
9178 vmsvga_enabled = 0;
9179 break;
9180 case QEMU_OPTION_vmsvga:
9181 cirrus_vga_enabled = 0;
9182 vmsvga_enabled = 1;
9183 break;
9184 case QEMU_OPTION_std_vga:
9185 cirrus_vga_enabled = 0;
9186 vmsvga_enabled = 0;
9187 break;
9188 case QEMU_OPTION_g:
9190 const char *p;
9191 int w, h, depth;
9192 p = optarg;
9193 w = strtol(p, (char **)&p, 10);
9194 if (w <= 0) {
9195 graphic_error:
9196 fprintf(stderr, "qemu: invalid resolution or depth\n");
9197 exit(1);
9199 if (*p != 'x')
9200 goto graphic_error;
9201 p++;
9202 h = strtol(p, (char **)&p, 10);
9203 if (h <= 0)
9204 goto graphic_error;
9205 if (*p == 'x') {
9206 p++;
9207 depth = strtol(p, (char **)&p, 10);
9208 if (depth != 8 && depth != 15 && depth != 16 &&
9209 depth != 24 && depth != 32)
9210 goto graphic_error;
9211 } else if (*p == '\0') {
9212 depth = graphic_depth;
9213 } else {
9214 goto graphic_error;
9217 graphic_width = w;
9218 graphic_height = h;
9219 graphic_depth = depth;
9221 break;
9222 case QEMU_OPTION_echr:
9224 char *r;
9225 term_escape_char = strtol(optarg, &r, 0);
9226 if (r == optarg)
9227 printf("Bad argument to echr\n");
9228 break;
9230 case QEMU_OPTION_monitor:
9231 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9232 break;
9233 case QEMU_OPTION_balloon:
9234 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9235 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9236 exit(1);
9238 if (balloon_used) {
9239 fprintf(stderr, "qemu: only one balloon device can be used\n");
9240 exit(1);
9242 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9243 vmchannel_device_index++;
9244 balloon_used = 1;
9245 break;
9246 case QEMU_OPTION_vmchannel:
9247 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9248 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9249 exit(1);
9251 pstrcpy(vmchannel_devices[vmchannel_device_index],
9252 sizeof(vmchannel_devices[0]), optarg);
9253 vmchannel_device_index++;
9254 break;
9255 case QEMU_OPTION_serial:
9256 if (serial_device_index >= MAX_SERIAL_PORTS) {
9257 fprintf(stderr, "qemu: too many serial ports\n");
9258 exit(1);
9260 pstrcpy(serial_devices[serial_device_index],
9261 sizeof(serial_devices[0]), optarg);
9262 serial_device_index++;
9263 break;
9264 case QEMU_OPTION_parallel:
9265 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9266 fprintf(stderr, "qemu: too many parallel ports\n");
9267 exit(1);
9269 pstrcpy(parallel_devices[parallel_device_index],
9270 sizeof(parallel_devices[0]), optarg);
9271 parallel_device_index++;
9272 break;
9273 case QEMU_OPTION_loadvm:
9274 loadvm = optarg;
9275 break;
9276 case QEMU_OPTION_incoming:
9277 incoming = optarg;
9278 break;
9279 case QEMU_OPTION_full_screen:
9280 full_screen = 1;
9281 break;
9282 #ifdef CONFIG_SDL
9283 case QEMU_OPTION_no_frame:
9284 no_frame = 1;
9285 break;
9286 case QEMU_OPTION_alt_grab:
9287 alt_grab = 1;
9288 break;
9289 case QEMU_OPTION_no_quit:
9290 no_quit = 1;
9291 break;
9292 #endif
9293 case QEMU_OPTION_pidfile:
9294 pid_file = optarg;
9295 break;
9296 #ifdef TARGET_I386
9297 case QEMU_OPTION_win2k_hack:
9298 win2k_install_hack = 1;
9299 break;
9300 #endif
9301 #ifdef USE_KQEMU
9302 case QEMU_OPTION_no_kqemu:
9303 kqemu_allowed = 0;
9304 break;
9305 case QEMU_OPTION_kernel_kqemu:
9306 kqemu_allowed = 2;
9307 break;
9308 #endif
9309 #ifdef USE_KVM
9310 case QEMU_OPTION_no_kvm:
9311 kvm_allowed = 0;
9312 break;
9313 case QEMU_OPTION_no_kvm_irqchip: {
9314 extern int kvm_irqchip, kvm_pit;
9315 kvm_irqchip = 0;
9316 kvm_pit = 0;
9317 break;
9319 case QEMU_OPTION_no_kvm_pit: {
9320 extern int kvm_pit;
9321 kvm_pit = 0;
9322 break;
9324 #endif
9325 case QEMU_OPTION_usb:
9326 usb_enabled = 1;
9327 break;
9328 case QEMU_OPTION_usbdevice:
9329 usb_enabled = 1;
9330 if (usb_devices_index >= MAX_USB_CMDLINE) {
9331 fprintf(stderr, "Too many USB devices\n");
9332 exit(1);
9334 pstrcpy(usb_devices[usb_devices_index],
9335 sizeof(usb_devices[usb_devices_index]),
9336 optarg);
9337 usb_devices_index++;
9338 break;
9339 case QEMU_OPTION_smp:
9340 smp_cpus = atoi(optarg);
9341 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9342 fprintf(stderr, "Invalid number of CPUs\n");
9343 exit(1);
9345 break;
9346 case QEMU_OPTION_vnc:
9347 vnc_display = optarg;
9348 break;
9349 case QEMU_OPTION_no_acpi:
9350 acpi_enabled = 0;
9351 break;
9352 case QEMU_OPTION_no_reboot:
9353 no_reboot = 1;
9354 break;
9355 case QEMU_OPTION_show_cursor:
9356 cursor_hide = 0;
9357 break;
9358 case QEMU_OPTION_daemonize:
9359 daemonize = 1;
9360 break;
9361 case QEMU_OPTION_option_rom:
9362 if (nb_option_roms >= MAX_OPTION_ROMS) {
9363 fprintf(stderr, "Too many option ROMs\n");
9364 exit(1);
9366 option_rom[nb_option_roms] = optarg;
9367 nb_option_roms++;
9368 break;
9369 case QEMU_OPTION_semihosting:
9370 semihosting_enabled = 1;
9371 break;
9372 case QEMU_OPTION_tdf:
9373 time_drift_fix = 1;
9374 break;
9375 case QEMU_OPTION_kvm_shadow_memory:
9376 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9377 break;
9378 case QEMU_OPTION_mempath:
9379 mem_path = optarg;
9380 break;
9381 case QEMU_OPTION_name:
9382 qemu_name = optarg;
9383 break;
9384 #ifdef TARGET_SPARC
9385 case QEMU_OPTION_prom_env:
9386 if (nb_prom_envs >= MAX_PROM_ENVS) {
9387 fprintf(stderr, "Too many prom variables\n");
9388 exit(1);
9390 prom_envs[nb_prom_envs] = optarg;
9391 nb_prom_envs++;
9392 break;
9393 #endif
9394 case QEMU_OPTION_cpu_vendor:
9395 cpu_vendor_string = optarg;
9396 break;
9397 #ifdef TARGET_ARM
9398 case QEMU_OPTION_old_param:
9399 old_param = 1;
9400 break;
9401 #endif
9402 case QEMU_OPTION_clock:
9403 configure_alarms(optarg);
9404 break;
9405 case QEMU_OPTION_startdate:
9407 struct tm tm;
9408 time_t rtc_start_date;
9409 if (!strcmp(optarg, "now")) {
9410 rtc_date_offset = -1;
9411 } else {
9412 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9413 &tm.tm_year,
9414 &tm.tm_mon,
9415 &tm.tm_mday,
9416 &tm.tm_hour,
9417 &tm.tm_min,
9418 &tm.tm_sec) == 6) {
9419 /* OK */
9420 } else if (sscanf(optarg, "%d-%d-%d",
9421 &tm.tm_year,
9422 &tm.tm_mon,
9423 &tm.tm_mday) == 3) {
9424 tm.tm_hour = 0;
9425 tm.tm_min = 0;
9426 tm.tm_sec = 0;
9427 } else {
9428 goto date_fail;
9430 tm.tm_year -= 1900;
9431 tm.tm_mon--;
9432 rtc_start_date = mktimegm(&tm);
9433 if (rtc_start_date == -1) {
9434 date_fail:
9435 fprintf(stderr, "Invalid date format. Valid format are:\n"
9436 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9437 exit(1);
9439 rtc_date_offset = time(NULL) - rtc_start_date;
9442 break;
9447 #ifndef _WIN32
9448 if (daemonize) {
9449 pid_t pid;
9451 if (pipe(fds) == -1)
9452 exit(1);
9454 pid = fork();
9455 if (pid > 0) {
9456 uint8_t status;
9457 ssize_t len;
9459 close(fds[1]);
9461 again:
9462 len = read(fds[0], &status, 1);
9463 if (len == -1 && (errno == EINTR))
9464 goto again;
9466 if (len != 1)
9467 exit(1);
9468 else if (status == 1) {
9469 fprintf(stderr, "Could not acquire pidfile\n");
9470 exit(1);
9471 } else
9472 exit(0);
9473 } else if (pid < 0)
9474 exit(1);
9476 setsid();
9478 pid = fork();
9479 if (pid > 0)
9480 exit(0);
9481 else if (pid < 0)
9482 exit(1);
9484 umask(027);
9486 signal(SIGTSTP, SIG_IGN);
9487 signal(SIGTTOU, SIG_IGN);
9488 signal(SIGTTIN, SIG_IGN);
9490 #endif
9492 #if USE_KVM
9493 if (kvm_enabled()) {
9494 if (kvm_qemu_init() < 0) {
9495 extern int kvm_allowed;
9496 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9497 #ifdef NO_CPU_EMULATION
9498 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9499 exit(1);
9500 #endif
9501 kvm_allowed = 0;
9504 #endif
9506 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9507 if (daemonize) {
9508 uint8_t status = 1;
9509 write(fds[1], &status, 1);
9510 } else
9511 fprintf(stderr, "Could not acquire pid file\n");
9512 exit(1);
9515 #ifdef USE_KQEMU
9516 if (smp_cpus > 1)
9517 kqemu_allowed = 0;
9518 #endif
9519 linux_boot = (kernel_filename != NULL);
9520 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9522 /* XXX: this should not be: some embedded targets just have flash */
9523 if (!linux_boot && net_boot == 0 &&
9524 nb_drives_opt == 0)
9525 help(1);
9527 /* boot to floppy or the default cd if no hard disk defined yet */
9528 if (!boot_devices[0]) {
9529 boot_devices = "cad";
9531 setvbuf(stdout, NULL, _IOLBF, 0);
9533 init_timers();
9534 init_timer_alarm();
9535 qemu_aio_init();
9537 #ifdef _WIN32
9538 socket_init();
9539 #endif
9541 /* init network clients */
9542 if (nb_net_clients == 0) {
9543 /* if no clients, we use a default config */
9544 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9545 "nic");
9546 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9547 "user");
9548 nb_net_clients = 2;
9551 for(i = 0;i < nb_net_clients; i++) {
9552 if (net_client_init(net_clients[i]) < 0)
9553 exit(1);
9555 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9556 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9557 continue;
9558 if (vlan->nb_guest_devs == 0) {
9559 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9560 exit(1);
9562 if (vlan->nb_host_devs == 0)
9563 fprintf(stderr,
9564 "Warning: vlan %d is not connected to host network\n",
9565 vlan->id);
9568 #ifdef TARGET_I386
9569 /* XXX: this should be moved in the PC machine instantiation code */
9570 if (net_boot != 0) {
9571 int netroms = 0;
9572 for (i = 0; i < nb_nics && i < 4; i++) {
9573 const char *model = nd_table[i].model;
9574 char buf[1024];
9575 if (net_boot & (1 << i)) {
9576 if (model == NULL)
9577 model = "rtl8139";
9578 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9579 if (get_image_size(buf) > 0) {
9580 if (nb_option_roms >= MAX_OPTION_ROMS) {
9581 fprintf(stderr, "Too many option ROMs\n");
9582 exit(1);
9584 option_rom[nb_option_roms] = strdup(buf);
9585 nb_option_roms++;
9586 netroms++;
9590 if (netroms == 0) {
9591 fprintf(stderr, "No valid PXE rom found for network device\n");
9592 exit(1);
9595 #endif
9597 /* init the memory */
9598 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9600 /* Initialize kvm */
9601 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9602 #define KVM_EXTRA_PAGES 3
9603 #else
9604 #define KVM_EXTRA_PAGES 0
9605 #endif
9606 if (kvm_enabled()) {
9607 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9608 if (kvm_qemu_create_context() < 0) {
9609 fprintf(stderr, "Could not create KVM context\n");
9610 exit(1);
9612 #ifdef KVM_CAP_USER_MEMORY
9614 int ret;
9616 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9617 if (ret) {
9618 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9619 if (!phys_ram_base) {
9620 fprintf(stderr, "Could not allocate physical memory\n");
9621 exit(1);
9625 #endif
9626 } else {
9627 phys_ram_base = qemu_vmalloc(phys_ram_size);
9628 if (!phys_ram_base) {
9629 fprintf(stderr, "Could not allocate physical memory\n");
9630 exit(1);
9634 bdrv_init();
9636 /* we always create the cdrom drive, even if no disk is there */
9638 if (nb_drives_opt < MAX_DRIVES)
9639 drive_add(NULL, CDROM_ALIAS);
9641 /* we always create at least one floppy */
9643 if (nb_drives_opt < MAX_DRIVES)
9644 drive_add(NULL, FD_ALIAS, 0);
9646 /* we always create one sd slot, even if no card is in it */
9648 if (nb_drives_opt < MAX_DRIVES)
9649 drive_add(NULL, SD_ALIAS);
9651 /* open the virtual block devices
9652 * note that migration with device
9653 * hot add/remove is broken.
9655 for(i = 0; i < nb_drives_opt; i++)
9656 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9657 exit(1);
9659 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9660 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9662 init_ioports();
9664 /* terminal init */
9665 memset(&display_state, 0, sizeof(display_state));
9666 if (nographic) {
9667 if (curses) {
9668 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9669 exit(1);
9671 /* nearly nothing to do */
9672 dumb_display_init(ds);
9673 } else if (vnc_display != NULL) {
9674 vnc_display_init(ds);
9675 if (vnc_display_open(ds, vnc_display) < 0)
9676 exit(1);
9677 } else
9678 #if defined(CONFIG_CURSES)
9679 if (curses) {
9680 curses_display_init(ds, full_screen);
9681 } else
9682 #endif
9684 #if defined(CONFIG_SDL)
9685 sdl_display_init(ds, full_screen, no_frame);
9686 #elif defined(CONFIG_COCOA)
9687 cocoa_display_init(ds, full_screen);
9688 #else
9689 dumb_display_init(ds);
9690 #endif
9693 /* Maintain compatibility with multiple stdio monitors */
9694 if (!strcmp(monitor_device,"stdio")) {
9695 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9696 if (!strcmp(serial_devices[i],"mon:stdio")) {
9697 monitor_device[0] = '\0';
9698 break;
9699 } else if (!strcmp(serial_devices[i],"stdio")) {
9700 monitor_device[0] = '\0';
9701 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9702 break;
9706 if (monitor_device[0] != '\0') {
9707 monitor_hd = qemu_chr_open(monitor_device);
9708 if (!monitor_hd) {
9709 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9710 exit(1);
9712 monitor_init(monitor_hd, !nographic);
9715 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9716 const char *devname = vmchannel_devices[i];
9717 if (devname[0] != '\0' && strcmp(devname, "none")) {
9718 int devid;
9719 char *termn;
9721 if (strstart(devname, "di:", &devname)) {
9722 devid = strtol(devname, &termn, 16);
9723 devname = termn + 1;
9725 else {
9726 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9727 devname);
9728 exit(1);
9730 vmchannel_hds[i] = qemu_chr_open(devname);
9731 if (!vmchannel_hds[i]) {
9732 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9733 devname);
9734 exit(1);
9736 vmchannel_init(vmchannel_hds[i], devid, i);
9740 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9741 const char *devname = serial_devices[i];
9742 if (devname[0] != '\0' && strcmp(devname, "none")) {
9743 serial_hds[i] = qemu_chr_open(devname);
9744 if (!serial_hds[i]) {
9745 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9746 devname);
9747 exit(1);
9749 if (strstart(devname, "vc", 0))
9750 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9754 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9755 const char *devname = parallel_devices[i];
9756 if (devname[0] != '\0' && strcmp(devname, "none")) {
9757 parallel_hds[i] = qemu_chr_open(devname);
9758 if (!parallel_hds[i]) {
9759 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9760 devname);
9761 exit(1);
9763 if (strstart(devname, "vc", 0))
9764 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9768 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9769 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9771 current_machine = machine;
9773 /* init USB devices */
9774 if (usb_enabled) {
9775 for(i = 0; i < usb_devices_index; i++) {
9776 if (usb_device_add(usb_devices[i]) < 0) {
9777 fprintf(stderr, "Warning: could not add USB device %s\n",
9778 usb_devices[i]);
9783 if (display_state.dpy_refresh) {
9784 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9785 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9788 if (kvm_enabled())
9789 kvm_init_ap();
9791 #ifdef CONFIG_GDBSTUB
9792 if (use_gdbstub) {
9793 /* XXX: use standard host:port notation and modify options
9794 accordingly. */
9795 if (gdbserver_start(gdbstub_port) < 0) {
9796 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9797 gdbstub_port);
9798 exit(1);
9801 #endif
9802 if (loadvm)
9803 do_loadvm(loadvm);
9805 if (incoming) {
9806 int rc;
9808 rc = migrate_incoming(incoming);
9809 if (rc != 0) {
9810 fprintf(stderr, "Migration failed rc=%d\n", rc);
9811 exit(rc);
9816 /* XXX: simplify init */
9817 read_passwords();
9818 if (autostart) {
9819 vm_start();
9823 if (daemonize) {
9824 uint8_t status = 0;
9825 ssize_t len;
9826 int fd;
9828 again1:
9829 len = write(fds[1], &status, 1);
9830 if (len == -1 && (errno == EINTR))
9831 goto again1;
9833 if (len != 1)
9834 exit(1);
9836 chdir("/");
9837 TFR(fd = open("/dev/null", O_RDWR));
9838 if (fd == -1)
9839 exit(1);
9841 dup2(fd, 0);
9842 dup2(fd, 1);
9843 dup2(fd, 2);
9845 close(fd);
9848 main_loop();
9849 quit_timers();
9851 #if !defined(_WIN32)
9852 /* close network clients */
9853 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9854 VLANClientState *vc;
9856 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9857 if (vc->fd_read == tap_receive) {
9858 char ifname[64];
9859 TAPState *s = vc->opaque;
9861 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9862 s->down_script[0])
9863 launch_script(s->down_script, ifname, s->fd);
9867 #endif
9868 return 0;