kvm: qemu: dynamic drive/drive_opt index allocation
[kvm-userspace.git] / qemu / vl.c
blob1b33aeca33e145aa40b5f405d5460ea514717822
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 {
255 const char *file;
256 char opt[1024];
257 int used;
258 } drives_opt[MAX_DRIVES];
260 static CPUState *cur_cpu;
261 static CPUState *next_cpu;
262 static int event_pending = 1;
264 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
266 void decorate_application_name(char *appname, int max_len)
268 if (kvm_enabled())
270 int remain = max_len - strlen(appname) - 1;
272 if (remain > 0)
273 strncat(appname, "/KVM", remain);
277 /***********************************************************/
278 /* x86 ISA bus support */
280 target_phys_addr_t isa_mem_base = 0;
281 PicState2 *isa_pic;
283 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
285 #ifdef DEBUG_UNUSED_IOPORT
286 fprintf(stderr, "unused inb: port=0x%04x\n", address);
287 #endif
288 return 0xff;
291 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
293 #ifdef DEBUG_UNUSED_IOPORT
294 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
295 #endif
298 /* default is to make two byte accesses */
299 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
301 uint32_t data;
302 data = ioport_read_table[0][address](ioport_opaque[address], address);
303 address = (address + 1) & (MAX_IOPORTS - 1);
304 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
305 return data;
308 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
310 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
311 address = (address + 1) & (MAX_IOPORTS - 1);
312 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
315 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
317 #ifdef DEBUG_UNUSED_IOPORT
318 fprintf(stderr, "unused inl: port=0x%04x\n", address);
319 #endif
320 return 0xffffffff;
323 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
325 #ifdef DEBUG_UNUSED_IOPORT
326 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
327 #endif
330 static void init_ioports(void)
332 int i;
334 for(i = 0; i < MAX_IOPORTS; i++) {
335 ioport_read_table[0][i] = default_ioport_readb;
336 ioport_write_table[0][i] = default_ioport_writeb;
337 ioport_read_table[1][i] = default_ioport_readw;
338 ioport_write_table[1][i] = default_ioport_writew;
339 ioport_read_table[2][i] = default_ioport_readl;
340 ioport_write_table[2][i] = default_ioport_writel;
344 /* size is the word size in byte */
345 int register_ioport_read(int start, int length, int size,
346 IOPortReadFunc *func, void *opaque)
348 int i, bsize;
350 if (size == 1) {
351 bsize = 0;
352 } else if (size == 2) {
353 bsize = 1;
354 } else if (size == 4) {
355 bsize = 2;
356 } else {
357 hw_error("register_ioport_read: invalid size");
358 return -1;
360 for(i = start; i < start + length; i += size) {
361 ioport_read_table[bsize][i] = func;
362 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
363 hw_error("register_ioport_read: invalid opaque");
364 ioport_opaque[i] = opaque;
366 return 0;
369 /* size is the word size in byte */
370 int register_ioport_write(int start, int length, int size,
371 IOPortWriteFunc *func, void *opaque)
373 int i, bsize;
375 if (size == 1) {
376 bsize = 0;
377 } else if (size == 2) {
378 bsize = 1;
379 } else if (size == 4) {
380 bsize = 2;
381 } else {
382 hw_error("register_ioport_write: invalid size");
383 return -1;
385 for(i = start; i < start + length; i += size) {
386 ioport_write_table[bsize][i] = func;
387 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
388 hw_error("register_ioport_write: invalid opaque");
389 ioport_opaque[i] = opaque;
391 return 0;
394 void isa_unassign_ioport(int start, int length)
396 int i;
398 for(i = start; i < start + length; i++) {
399 ioport_read_table[0][i] = default_ioport_readb;
400 ioport_read_table[1][i] = default_ioport_readw;
401 ioport_read_table[2][i] = default_ioport_readl;
403 ioport_write_table[0][i] = default_ioport_writeb;
404 ioport_write_table[1][i] = default_ioport_writew;
405 ioport_write_table[2][i] = default_ioport_writel;
409 /***********************************************************/
411 void cpu_outb(CPUState *env, int addr, int val)
413 #ifdef DEBUG_IOPORT
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "outb: %04x %02x\n", addr, val);
416 #endif
417 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
418 #ifdef USE_KQEMU
419 if (env)
420 env->last_io_time = cpu_get_time_fast();
421 #endif
424 void cpu_outw(CPUState *env, int addr, int val)
426 #ifdef DEBUG_IOPORT
427 if (loglevel & CPU_LOG_IOPORT)
428 fprintf(logfile, "outw: %04x %04x\n", addr, val);
429 #endif
430 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
431 #ifdef USE_KQEMU
432 if (env)
433 env->last_io_time = cpu_get_time_fast();
434 #endif
437 void cpu_outl(CPUState *env, int addr, int val)
439 #ifdef DEBUG_IOPORT
440 if (loglevel & CPU_LOG_IOPORT)
441 fprintf(logfile, "outl: %04x %08x\n", addr, val);
442 #endif
443 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
444 #ifdef USE_KQEMU
445 if (env)
446 env->last_io_time = cpu_get_time_fast();
447 #endif
450 int cpu_inb(CPUState *env, int addr)
452 int val;
453 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
454 #ifdef DEBUG_IOPORT
455 if (loglevel & CPU_LOG_IOPORT)
456 fprintf(logfile, "inb : %04x %02x\n", addr, val);
457 #endif
458 #ifdef USE_KQEMU
459 if (env)
460 env->last_io_time = cpu_get_time_fast();
461 #endif
462 return val;
465 int cpu_inw(CPUState *env, int addr)
467 int val;
468 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
469 #ifdef DEBUG_IOPORT
470 if (loglevel & CPU_LOG_IOPORT)
471 fprintf(logfile, "inw : %04x %04x\n", addr, val);
472 #endif
473 #ifdef USE_KQEMU
474 if (env)
475 env->last_io_time = cpu_get_time_fast();
476 #endif
477 return val;
480 int cpu_inl(CPUState *env, int addr)
482 int val;
483 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
484 #ifdef DEBUG_IOPORT
485 if (loglevel & CPU_LOG_IOPORT)
486 fprintf(logfile, "inl : %04x %08x\n", addr, val);
487 #endif
488 #ifdef USE_KQEMU
489 if (env)
490 env->last_io_time = cpu_get_time_fast();
491 #endif
492 return val;
495 /***********************************************************/
496 void hw_error(const char *fmt, ...)
498 va_list ap;
499 CPUState *env;
501 va_start(ap, fmt);
502 fprintf(stderr, "qemu: hardware error: ");
503 vfprintf(stderr, fmt, ap);
504 fprintf(stderr, "\n");
505 for(env = first_cpu; env != NULL; env = env->next_cpu) {
506 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
507 #ifdef TARGET_I386
508 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
509 #else
510 cpu_dump_state(env, stderr, fprintf, 0);
511 #endif
513 va_end(ap);
514 abort();
517 /***********************************************************/
518 /* keyboard/mouse */
520 static QEMUPutKBDEvent *qemu_put_kbd_event;
521 static void *qemu_put_kbd_event_opaque;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
523 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
525 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
527 qemu_put_kbd_event_opaque = opaque;
528 qemu_put_kbd_event = func;
531 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
532 void *opaque, int absolute,
533 const char *name)
535 QEMUPutMouseEntry *s, *cursor;
537 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
538 if (!s)
539 return NULL;
541 s->qemu_put_mouse_event = func;
542 s->qemu_put_mouse_event_opaque = opaque;
543 s->qemu_put_mouse_event_absolute = absolute;
544 s->qemu_put_mouse_event_name = qemu_strdup(name);
545 s->next = NULL;
547 if (!qemu_put_mouse_event_head) {
548 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
549 return s;
552 cursor = qemu_put_mouse_event_head;
553 while (cursor->next != NULL)
554 cursor = cursor->next;
556 cursor->next = s;
557 qemu_put_mouse_event_current = s;
559 return s;
562 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
564 QEMUPutMouseEntry *prev = NULL, *cursor;
566 if (!qemu_put_mouse_event_head || entry == NULL)
567 return;
569 cursor = qemu_put_mouse_event_head;
570 while (cursor != NULL && cursor != entry) {
571 prev = cursor;
572 cursor = cursor->next;
575 if (cursor == NULL) // does not exist or list empty
576 return;
577 else if (prev == NULL) { // entry is head
578 qemu_put_mouse_event_head = cursor->next;
579 if (qemu_put_mouse_event_current == entry)
580 qemu_put_mouse_event_current = cursor->next;
581 qemu_free(entry->qemu_put_mouse_event_name);
582 qemu_free(entry);
583 return;
586 prev->next = entry->next;
588 if (qemu_put_mouse_event_current == entry)
589 qemu_put_mouse_event_current = prev;
591 qemu_free(entry->qemu_put_mouse_event_name);
592 qemu_free(entry);
595 void kbd_put_keycode(int keycode)
597 if (qemu_put_kbd_event) {
598 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
602 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
604 QEMUPutMouseEvent *mouse_event;
605 void *mouse_event_opaque;
606 int width;
608 if (!qemu_put_mouse_event_current) {
609 return;
612 mouse_event =
613 qemu_put_mouse_event_current->qemu_put_mouse_event;
614 mouse_event_opaque =
615 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
617 if (mouse_event) {
618 if (graphic_rotate) {
619 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
620 width = 0x7fff;
621 else
622 width = graphic_width;
623 mouse_event(mouse_event_opaque,
624 width - dy, dx, dz, buttons_state);
625 } else
626 mouse_event(mouse_event_opaque,
627 dx, dy, dz, buttons_state);
631 int kbd_mouse_is_absolute(void)
633 if (!qemu_put_mouse_event_current)
634 return 0;
636 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
639 void do_info_mice(void)
641 QEMUPutMouseEntry *cursor;
642 int index = 0;
644 if (!qemu_put_mouse_event_head) {
645 term_printf("No mouse devices connected\n");
646 return;
649 term_printf("Mouse devices available:\n");
650 cursor = qemu_put_mouse_event_head;
651 while (cursor != NULL) {
652 term_printf("%c Mouse #%d: %s\n",
653 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
654 index, cursor->qemu_put_mouse_event_name);
655 index++;
656 cursor = cursor->next;
660 void do_mouse_set(int index)
662 QEMUPutMouseEntry *cursor;
663 int i = 0;
665 if (!qemu_put_mouse_event_head) {
666 term_printf("No mouse devices connected\n");
667 return;
670 cursor = qemu_put_mouse_event_head;
671 while (cursor != NULL && index != i) {
672 i++;
673 cursor = cursor->next;
676 if (cursor != NULL)
677 qemu_put_mouse_event_current = cursor;
678 else
679 term_printf("Mouse at given index not found\n");
682 /* compute with 96 bit intermediate result: (a*b)/c */
683 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
685 union {
686 uint64_t ll;
687 struct {
688 #ifdef WORDS_BIGENDIAN
689 uint32_t high, low;
690 #else
691 uint32_t low, high;
692 #endif
693 } l;
694 } u, res;
695 uint64_t rl, rh;
697 u.ll = a;
698 rl = (uint64_t)u.l.low * (uint64_t)b;
699 rh = (uint64_t)u.l.high * (uint64_t)b;
700 rh += (rl >> 32);
701 res.l.high = rh / c;
702 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
703 return res.ll;
706 /***********************************************************/
707 /* real time host monotonic timer */
709 #define QEMU_TIMER_BASE 1000000000LL
711 #ifdef WIN32
713 static int64_t clock_freq;
715 static void init_get_clock(void)
717 LARGE_INTEGER freq;
718 int ret;
719 ret = QueryPerformanceFrequency(&freq);
720 if (ret == 0) {
721 fprintf(stderr, "Could not calibrate ticks\n");
722 exit(1);
724 clock_freq = freq.QuadPart;
727 static int64_t get_clock(void)
729 LARGE_INTEGER ti;
730 QueryPerformanceCounter(&ti);
731 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
734 #else
736 static int use_rt_clock;
738 static void init_get_clock(void)
740 use_rt_clock = 0;
741 #if defined(__linux__)
743 struct timespec ts;
744 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
745 use_rt_clock = 1;
748 #endif
751 static int64_t get_clock(void)
753 #if defined(__linux__)
754 if (use_rt_clock) {
755 struct timespec ts;
756 clock_gettime(CLOCK_MONOTONIC, &ts);
757 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
758 } else
759 #endif
761 /* XXX: using gettimeofday leads to problems if the date
762 changes, so it should be avoided. */
763 struct timeval tv;
764 gettimeofday(&tv, NULL);
765 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
769 #endif
771 /***********************************************************/
772 /* guest cycle counter */
774 static int64_t cpu_ticks_prev;
775 static int64_t cpu_ticks_offset;
776 static int64_t cpu_clock_offset;
777 static int cpu_ticks_enabled;
779 /* return the host CPU cycle counter and handle stop/restart */
780 int64_t cpu_get_ticks(void)
782 if (!cpu_ticks_enabled) {
783 return cpu_ticks_offset;
784 } else {
785 int64_t ticks;
786 ticks = cpu_get_real_ticks();
787 if (cpu_ticks_prev > ticks) {
788 /* Note: non increasing ticks may happen if the host uses
789 software suspend */
790 cpu_ticks_offset += cpu_ticks_prev - ticks;
792 cpu_ticks_prev = ticks;
793 return ticks + cpu_ticks_offset;
797 /* return the host CPU monotonic timer and handle stop/restart */
798 static int64_t cpu_get_clock(void)
800 int64_t ti;
801 if (!cpu_ticks_enabled) {
802 return cpu_clock_offset;
803 } else {
804 ti = get_clock();
805 return ti + cpu_clock_offset;
809 /* enable cpu_get_ticks() */
810 void cpu_enable_ticks(void)
812 if (!cpu_ticks_enabled) {
813 cpu_ticks_offset -= cpu_get_real_ticks();
814 cpu_clock_offset -= get_clock();
815 cpu_ticks_enabled = 1;
819 /* disable cpu_get_ticks() : the clock is stopped. You must not call
820 cpu_get_ticks() after that. */
821 void cpu_disable_ticks(void)
823 if (cpu_ticks_enabled) {
824 cpu_ticks_offset = cpu_get_ticks();
825 cpu_clock_offset = cpu_get_clock();
826 cpu_ticks_enabled = 0;
830 /***********************************************************/
831 /* timers */
833 #define QEMU_TIMER_REALTIME 0
834 #define QEMU_TIMER_VIRTUAL 1
836 struct QEMUClock {
837 int type;
838 /* XXX: add frequency */
841 struct QEMUTimer {
842 QEMUClock *clock;
843 int64_t expire_time;
844 QEMUTimerCB *cb;
845 void *opaque;
846 struct QEMUTimer *next;
849 struct qemu_alarm_timer {
850 char const *name;
851 unsigned int flags;
853 int (*start)(struct qemu_alarm_timer *t);
854 void (*stop)(struct qemu_alarm_timer *t);
855 void (*rearm)(struct qemu_alarm_timer *t);
856 void *priv;
859 #define ALARM_FLAG_DYNTICKS 0x1
860 #define ALARM_FLAG_EXPIRED 0x2
862 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
864 return t->flags & ALARM_FLAG_DYNTICKS;
867 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
869 if (!alarm_has_dynticks(t))
870 return;
872 t->rearm(t);
875 /* TODO: MIN_TIMER_REARM_US should be optimized */
876 #define MIN_TIMER_REARM_US 250
878 static struct qemu_alarm_timer *alarm_timer;
880 #ifdef _WIN32
882 struct qemu_alarm_win32 {
883 MMRESULT timerId;
884 HANDLE host_alarm;
885 unsigned int period;
886 } alarm_win32_data = {0, NULL, -1};
888 static int win32_start_timer(struct qemu_alarm_timer *t);
889 static void win32_stop_timer(struct qemu_alarm_timer *t);
890 static void win32_rearm_timer(struct qemu_alarm_timer *t);
892 #else
894 static int unix_start_timer(struct qemu_alarm_timer *t);
895 static void unix_stop_timer(struct qemu_alarm_timer *t);
897 #ifdef __linux__
899 static int dynticks_start_timer(struct qemu_alarm_timer *t);
900 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
901 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
903 static int hpet_start_timer(struct qemu_alarm_timer *t);
904 static void hpet_stop_timer(struct qemu_alarm_timer *t);
906 static int rtc_start_timer(struct qemu_alarm_timer *t);
907 static void rtc_stop_timer(struct qemu_alarm_timer *t);
909 #endif /* __linux__ */
911 #endif /* _WIN32 */
913 static struct qemu_alarm_timer alarm_timers[] = {
914 #ifndef _WIN32
915 #ifdef __linux__
916 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
917 dynticks_stop_timer, dynticks_rearm_timer, NULL},
918 /* HPET - if available - is preferred */
919 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
920 /* ...otherwise try RTC */
921 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
922 #endif
923 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
924 #else
925 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
926 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
927 {"win32", 0, win32_start_timer,
928 win32_stop_timer, NULL, &alarm_win32_data},
929 #endif
930 {NULL, }
933 static void show_available_alarms()
935 int i;
937 printf("Available alarm timers, in order of precedence:\n");
938 for (i = 0; alarm_timers[i].name; i++)
939 printf("%s\n", alarm_timers[i].name);
942 static void configure_alarms(char const *opt)
944 int i;
945 int cur = 0;
946 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
947 char *arg;
948 char *name;
950 if (!strcmp(opt, "help")) {
951 show_available_alarms();
952 exit(0);
955 arg = strdup(opt);
957 /* Reorder the array */
958 name = strtok(arg, ",");
959 while (name) {
960 struct qemu_alarm_timer tmp;
962 for (i = 0; i < count && alarm_timers[i].name; i++) {
963 if (!strcmp(alarm_timers[i].name, name))
964 break;
967 if (i == count) {
968 fprintf(stderr, "Unknown clock %s\n", name);
969 goto next;
972 if (i < cur)
973 /* Ignore */
974 goto next;
976 /* Swap */
977 tmp = alarm_timers[i];
978 alarm_timers[i] = alarm_timers[cur];
979 alarm_timers[cur] = tmp;
981 cur++;
982 next:
983 name = strtok(NULL, ",");
986 free(arg);
988 if (cur) {
989 /* Disable remaining timers */
990 for (i = cur; i < count; i++)
991 alarm_timers[i].name = NULL;
994 /* debug */
995 show_available_alarms();
998 QEMUClock *rt_clock;
999 QEMUClock *vm_clock;
1001 static QEMUTimer *active_timers[2];
1003 static QEMUClock *qemu_new_clock(int type)
1005 QEMUClock *clock;
1006 clock = qemu_mallocz(sizeof(QEMUClock));
1007 if (!clock)
1008 return NULL;
1009 clock->type = type;
1010 return clock;
1013 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1015 QEMUTimer *ts;
1017 ts = qemu_mallocz(sizeof(QEMUTimer));
1018 ts->clock = clock;
1019 ts->cb = cb;
1020 ts->opaque = opaque;
1021 return ts;
1024 void qemu_free_timer(QEMUTimer *ts)
1026 qemu_free(ts);
1029 /* stop a timer, but do not dealloc it */
1030 void qemu_del_timer(QEMUTimer *ts)
1032 QEMUTimer **pt, *t;
1034 /* NOTE: this code must be signal safe because
1035 qemu_timer_expired() can be called from a signal. */
1036 pt = &active_timers[ts->clock->type];
1037 for(;;) {
1038 t = *pt;
1039 if (!t)
1040 break;
1041 if (t == ts) {
1042 *pt = t->next;
1043 break;
1045 pt = &t->next;
1049 /* modify the current timer so that it will be fired when current_time
1050 >= expire_time. The corresponding callback will be called. */
1051 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1053 QEMUTimer **pt, *t;
1055 qemu_del_timer(ts);
1057 /* add the timer in the sorted list */
1058 /* NOTE: this code must be signal safe because
1059 qemu_timer_expired() can be called from a signal. */
1060 pt = &active_timers[ts->clock->type];
1061 for(;;) {
1062 t = *pt;
1063 if (!t)
1064 break;
1065 if (t->expire_time > expire_time)
1066 break;
1067 pt = &t->next;
1069 ts->expire_time = expire_time;
1070 ts->next = *pt;
1071 *pt = ts;
1073 /* Rearm if necessary */
1074 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1075 pt == &active_timers[ts->clock->type])
1076 qemu_rearm_alarm_timer(alarm_timer);
1079 int qemu_timer_pending(QEMUTimer *ts)
1081 QEMUTimer *t;
1082 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1083 if (t == ts)
1084 return 1;
1086 return 0;
1089 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1091 if (!timer_head)
1092 return 0;
1093 return (timer_head->expire_time <= current_time);
1096 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1098 QEMUTimer *ts;
1100 for(;;) {
1101 ts = *ptimer_head;
1102 if (!ts || ts->expire_time > current_time)
1103 break;
1104 /* remove timer from the list before calling the callback */
1105 *ptimer_head = ts->next;
1106 ts->next = NULL;
1108 /* run the callback (the timer list can be modified) */
1109 ts->cb(ts->opaque);
1113 int64_t qemu_get_clock(QEMUClock *clock)
1115 switch(clock->type) {
1116 case QEMU_TIMER_REALTIME:
1117 return get_clock() / 1000000;
1118 default:
1119 case QEMU_TIMER_VIRTUAL:
1120 return cpu_get_clock();
1124 static void init_timers(void)
1126 init_get_clock();
1127 ticks_per_sec = QEMU_TIMER_BASE;
1128 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1129 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1132 /* save a timer */
1133 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1135 uint64_t expire_time;
1137 if (qemu_timer_pending(ts)) {
1138 expire_time = ts->expire_time;
1139 } else {
1140 expire_time = -1;
1142 qemu_put_be64(f, expire_time);
1145 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1147 uint64_t expire_time;
1149 expire_time = qemu_get_be64(f);
1150 if (expire_time != -1) {
1151 qemu_mod_timer(ts, expire_time);
1152 } else {
1153 qemu_del_timer(ts);
1157 static void timer_save(QEMUFile *f, void *opaque)
1159 if (cpu_ticks_enabled) {
1160 hw_error("cannot save state if virtual timers are running");
1162 qemu_put_be64(f, cpu_ticks_offset);
1163 qemu_put_be64(f, ticks_per_sec);
1164 qemu_put_be64(f, cpu_clock_offset);
1167 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1169 if (version_id != 1 && version_id != 2)
1170 return -EINVAL;
1171 if (cpu_ticks_enabled) {
1172 return -EINVAL;
1174 cpu_ticks_offset=qemu_get_be64(f);
1175 ticks_per_sec=qemu_get_be64(f);
1176 if (version_id == 2) {
1177 cpu_clock_offset=qemu_get_be64(f);
1179 return 0;
1182 #ifdef _WIN32
1183 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1184 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1185 #else
1186 static void host_alarm_handler(int host_signum)
1187 #endif
1189 #if 0
1190 #define DISP_FREQ 1000
1192 static int64_t delta_min = INT64_MAX;
1193 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1194 static int count;
1195 ti = qemu_get_clock(vm_clock);
1196 if (last_clock != 0) {
1197 delta = ti - last_clock;
1198 if (delta < delta_min)
1199 delta_min = delta;
1200 if (delta > delta_max)
1201 delta_max = delta;
1202 delta_cum += delta;
1203 if (++count == DISP_FREQ) {
1204 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1205 muldiv64(delta_min, 1000000, ticks_per_sec),
1206 muldiv64(delta_max, 1000000, ticks_per_sec),
1207 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1208 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1209 count = 0;
1210 delta_min = INT64_MAX;
1211 delta_max = 0;
1212 delta_cum = 0;
1215 last_clock = ti;
1217 #endif
1218 if (1 ||
1219 alarm_has_dynticks(alarm_timer) ||
1220 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1221 qemu_get_clock(vm_clock)) ||
1222 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1223 qemu_get_clock(rt_clock))) {
1224 #ifdef _WIN32
1225 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1226 SetEvent(data->host_alarm);
1227 #endif
1228 CPUState *env = next_cpu;
1230 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1232 if (env) {
1233 /* stop the currently executing cpu because a timer occured */
1234 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1235 #ifdef USE_KQEMU
1236 if (env->kqemu_enabled) {
1237 kqemu_cpu_interrupt(env);
1239 #endif
1241 event_pending = 1;
1245 static uint64_t qemu_next_deadline(void)
1247 int64_t nearest_delta_us = INT64_MAX;
1248 int64_t vmdelta_us;
1250 if (active_timers[QEMU_TIMER_REALTIME])
1251 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1252 qemu_get_clock(rt_clock))*1000;
1254 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1255 /* round up */
1256 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1257 qemu_get_clock(vm_clock)+999)/1000;
1258 if (vmdelta_us < nearest_delta_us)
1259 nearest_delta_us = vmdelta_us;
1262 /* Avoid arming the timer to negative, zero, or too low values */
1263 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1264 nearest_delta_us = MIN_TIMER_REARM_US;
1266 return nearest_delta_us;
1269 #ifndef _WIN32
1271 #if defined(__linux__)
1273 #define RTC_FREQ 1024
1275 static void enable_sigio_timer(int fd)
1277 struct sigaction act;
1279 /* timer signal */
1280 sigfillset(&act.sa_mask);
1281 act.sa_flags = 0;
1282 act.sa_handler = host_alarm_handler;
1284 sigaction(SIGIO, &act, NULL);
1285 fcntl(fd, F_SETFL, O_ASYNC);
1286 fcntl(fd, F_SETOWN, getpid());
1289 static int hpet_start_timer(struct qemu_alarm_timer *t)
1291 struct hpet_info info;
1292 int r, fd;
1294 fd = open("/dev/hpet", O_RDONLY);
1295 if (fd < 0)
1296 return -1;
1298 /* Set frequency */
1299 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1300 if (r < 0) {
1301 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1302 "error, but for better emulation accuracy type:\n"
1303 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1304 goto fail;
1307 /* Check capabilities */
1308 r = ioctl(fd, HPET_INFO, &info);
1309 if (r < 0)
1310 goto fail;
1312 /* Enable periodic mode */
1313 r = ioctl(fd, HPET_EPI, 0);
1314 if (info.hi_flags && (r < 0))
1315 goto fail;
1317 /* Enable interrupt */
1318 r = ioctl(fd, HPET_IE_ON, 0);
1319 if (r < 0)
1320 goto fail;
1322 enable_sigio_timer(fd);
1323 t->priv = (void *)(long)fd;
1325 return 0;
1326 fail:
1327 close(fd);
1328 return -1;
1331 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1333 int fd = (long)t->priv;
1335 close(fd);
1338 static int rtc_start_timer(struct qemu_alarm_timer *t)
1340 int rtc_fd;
1341 unsigned long current_rtc_freq = 0;
1343 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1344 if (rtc_fd < 0)
1345 return -1;
1346 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1347 if (current_rtc_freq != RTC_FREQ &&
1348 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1349 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1350 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1351 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1352 goto fail;
1354 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1355 fail:
1356 close(rtc_fd);
1357 return -1;
1360 enable_sigio_timer(rtc_fd);
1362 t->priv = (void *)(long)rtc_fd;
1364 return 0;
1367 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1369 int rtc_fd = (long)t->priv;
1371 close(rtc_fd);
1374 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1376 struct sigevent ev;
1377 timer_t host_timer;
1378 struct sigaction act;
1380 sigfillset(&act.sa_mask);
1381 act.sa_flags = 0;
1382 act.sa_handler = host_alarm_handler;
1384 sigaction(SIGALRM, &act, NULL);
1386 ev.sigev_value.sival_int = 0;
1387 ev.sigev_notify = SIGEV_SIGNAL;
1388 ev.sigev_signo = SIGALRM;
1390 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1391 perror("timer_create");
1393 /* disable dynticks */
1394 fprintf(stderr, "Dynamic Ticks disabled\n");
1396 return -1;
1399 t->priv = (void *)host_timer;
1401 return 0;
1404 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1406 timer_t host_timer = (timer_t)t->priv;
1408 timer_delete(host_timer);
1411 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1413 timer_t host_timer = (timer_t)t->priv;
1414 struct itimerspec timeout;
1415 int64_t nearest_delta_us = INT64_MAX;
1416 int64_t current_us;
1418 if (!active_timers[QEMU_TIMER_REALTIME] &&
1419 !active_timers[QEMU_TIMER_VIRTUAL])
1420 return;
1422 nearest_delta_us = qemu_next_deadline();
1424 /* check whether a timer is already running */
1425 if (timer_gettime(host_timer, &timeout)) {
1426 perror("gettime");
1427 fprintf(stderr, "Internal timer error: aborting\n");
1428 exit(1);
1430 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1431 if (current_us && current_us <= nearest_delta_us)
1432 return;
1434 timeout.it_interval.tv_sec = 0;
1435 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1436 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1437 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1438 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1439 perror("settime");
1440 fprintf(stderr, "Internal timer error: aborting\n");
1441 exit(1);
1445 #endif /* defined(__linux__) */
1447 static int unix_start_timer(struct qemu_alarm_timer *t)
1449 struct sigaction act;
1450 struct itimerval itv;
1451 int err;
1453 /* timer signal */
1454 sigfillset(&act.sa_mask);
1455 act.sa_flags = 0;
1456 act.sa_handler = host_alarm_handler;
1458 sigaction(SIGALRM, &act, NULL);
1460 itv.it_interval.tv_sec = 0;
1461 /* for i386 kernel 2.6 to get 1 ms */
1462 itv.it_interval.tv_usec = 999;
1463 itv.it_value.tv_sec = 0;
1464 itv.it_value.tv_usec = 10 * 1000;
1466 err = setitimer(ITIMER_REAL, &itv, NULL);
1467 if (err)
1468 return -1;
1470 return 0;
1473 static void unix_stop_timer(struct qemu_alarm_timer *t)
1475 struct itimerval itv;
1477 memset(&itv, 0, sizeof(itv));
1478 setitimer(ITIMER_REAL, &itv, NULL);
1481 #endif /* !defined(_WIN32) */
1483 #ifdef _WIN32
1485 static int win32_start_timer(struct qemu_alarm_timer *t)
1487 TIMECAPS tc;
1488 struct qemu_alarm_win32 *data = t->priv;
1489 UINT flags;
1491 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1492 if (!data->host_alarm) {
1493 perror("Failed CreateEvent");
1494 return -1;
1497 memset(&tc, 0, sizeof(tc));
1498 timeGetDevCaps(&tc, sizeof(tc));
1500 if (data->period < tc.wPeriodMin)
1501 data->period = tc.wPeriodMin;
1503 timeBeginPeriod(data->period);
1505 flags = TIME_CALLBACK_FUNCTION;
1506 if (alarm_has_dynticks(t))
1507 flags |= TIME_ONESHOT;
1508 else
1509 flags |= TIME_PERIODIC;
1511 data->timerId = timeSetEvent(1, // interval (ms)
1512 data->period, // resolution
1513 host_alarm_handler, // function
1514 (DWORD)t, // parameter
1515 flags);
1517 if (!data->timerId) {
1518 perror("Failed to initialize win32 alarm timer");
1520 timeEndPeriod(data->period);
1521 CloseHandle(data->host_alarm);
1522 return -1;
1525 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1527 return 0;
1530 static void win32_stop_timer(struct qemu_alarm_timer *t)
1532 struct qemu_alarm_win32 *data = t->priv;
1534 timeKillEvent(data->timerId);
1535 timeEndPeriod(data->period);
1537 CloseHandle(data->host_alarm);
1540 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1542 struct qemu_alarm_win32 *data = t->priv;
1543 uint64_t nearest_delta_us;
1545 if (!active_timers[QEMU_TIMER_REALTIME] &&
1546 !active_timers[QEMU_TIMER_VIRTUAL])
1547 return;
1549 nearest_delta_us = qemu_next_deadline();
1550 nearest_delta_us /= 1000;
1552 timeKillEvent(data->timerId);
1554 data->timerId = timeSetEvent(1,
1555 data->period,
1556 host_alarm_handler,
1557 (DWORD)t,
1558 TIME_ONESHOT | TIME_PERIODIC);
1560 if (!data->timerId) {
1561 perror("Failed to re-arm win32 alarm timer");
1563 timeEndPeriod(data->period);
1564 CloseHandle(data->host_alarm);
1565 exit(1);
1569 #endif /* _WIN32 */
1571 static void init_timer_alarm(void)
1573 struct qemu_alarm_timer *t;
1574 int i, err = -1;
1576 for (i = 0; alarm_timers[i].name; i++) {
1577 t = &alarm_timers[i];
1579 err = t->start(t);
1580 if (!err)
1581 break;
1584 if (err) {
1585 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1586 fprintf(stderr, "Terminating\n");
1587 exit(1);
1590 alarm_timer = t;
1593 static void quit_timers(void)
1595 alarm_timer->stop(alarm_timer);
1596 alarm_timer = NULL;
1599 /***********************************************************/
1600 /* host time/date access */
1601 void qemu_get_timedate(struct tm *tm, int offset)
1603 time_t ti;
1604 struct tm *ret;
1606 time(&ti);
1607 ti += offset;
1608 if (rtc_date_offset == -1) {
1609 if (rtc_utc)
1610 ret = gmtime(&ti);
1611 else
1612 ret = localtime(&ti);
1613 } else {
1614 ti -= rtc_date_offset;
1615 ret = gmtime(&ti);
1618 memcpy(tm, ret, sizeof(struct tm));
1621 int qemu_timedate_diff(struct tm *tm)
1623 time_t seconds;
1625 if (rtc_date_offset == -1)
1626 if (rtc_utc)
1627 seconds = mktimegm(tm);
1628 else
1629 seconds = mktime(tm);
1630 else
1631 seconds = mktimegm(tm) + rtc_date_offset;
1633 return seconds - time(NULL);
1636 /***********************************************************/
1637 /* character device */
1639 static void qemu_chr_event(CharDriverState *s, int event)
1641 if (!s->chr_event)
1642 return;
1643 s->chr_event(s->handler_opaque, event);
1646 static void qemu_chr_reset_bh(void *opaque)
1648 CharDriverState *s = opaque;
1649 qemu_chr_event(s, CHR_EVENT_RESET);
1650 qemu_bh_delete(s->bh);
1651 s->bh = NULL;
1654 void qemu_chr_reset(CharDriverState *s)
1656 if (s->bh == NULL) {
1657 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1658 qemu_bh_schedule(s->bh);
1662 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1664 return s->chr_write(s, buf, len);
1667 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1669 if (!s->chr_ioctl)
1670 return -ENOTSUP;
1671 return s->chr_ioctl(s, cmd, arg);
1674 int qemu_chr_can_read(CharDriverState *s)
1676 if (!s->chr_can_read)
1677 return 0;
1678 return s->chr_can_read(s->handler_opaque);
1681 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1683 s->chr_read(s->handler_opaque, buf, len);
1686 void qemu_chr_accept_input(CharDriverState *s)
1688 if (s->chr_accept_input)
1689 s->chr_accept_input(s);
1692 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1694 char buf[4096];
1695 va_list ap;
1696 va_start(ap, fmt);
1697 vsnprintf(buf, sizeof(buf), fmt, ap);
1698 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1699 va_end(ap);
1702 void qemu_chr_send_event(CharDriverState *s, int event)
1704 if (s->chr_send_event)
1705 s->chr_send_event(s, event);
1708 void qemu_chr_add_handlers(CharDriverState *s,
1709 IOCanRWHandler *fd_can_read,
1710 IOReadHandler *fd_read,
1711 IOEventHandler *fd_event,
1712 void *opaque)
1714 s->chr_can_read = fd_can_read;
1715 s->chr_read = fd_read;
1716 s->chr_event = fd_event;
1717 s->handler_opaque = opaque;
1718 if (s->chr_update_read_handler)
1719 s->chr_update_read_handler(s);
1722 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1724 return len;
1727 static CharDriverState *qemu_chr_open_null(void)
1729 CharDriverState *chr;
1731 chr = qemu_mallocz(sizeof(CharDriverState));
1732 if (!chr)
1733 return NULL;
1734 chr->chr_write = null_chr_write;
1735 return chr;
1738 /* MUX driver for serial I/O splitting */
1739 static int term_timestamps;
1740 static int64_t term_timestamps_start;
1741 #define MAX_MUX 4
1742 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1743 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1744 typedef struct {
1745 IOCanRWHandler *chr_can_read[MAX_MUX];
1746 IOReadHandler *chr_read[MAX_MUX];
1747 IOEventHandler *chr_event[MAX_MUX];
1748 void *ext_opaque[MAX_MUX];
1749 CharDriverState *drv;
1750 unsigned char buffer[MUX_BUFFER_SIZE];
1751 int prod;
1752 int cons;
1753 int mux_cnt;
1754 int term_got_escape;
1755 int max_size;
1756 } MuxDriver;
1759 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1761 MuxDriver *d = chr->opaque;
1762 int ret;
1763 if (!term_timestamps) {
1764 ret = d->drv->chr_write(d->drv, buf, len);
1765 } else {
1766 int i;
1768 ret = 0;
1769 for(i = 0; i < len; i++) {
1770 ret += d->drv->chr_write(d->drv, buf+i, 1);
1771 if (buf[i] == '\n') {
1772 char buf1[64];
1773 int64_t ti;
1774 int secs;
1776 ti = get_clock();
1777 if (term_timestamps_start == -1)
1778 term_timestamps_start = ti;
1779 ti -= term_timestamps_start;
1780 secs = ti / 1000000000;
1781 snprintf(buf1, sizeof(buf1),
1782 "[%02d:%02d:%02d.%03d] ",
1783 secs / 3600,
1784 (secs / 60) % 60,
1785 secs % 60,
1786 (int)((ti / 1000000) % 1000));
1787 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1791 return ret;
1794 static char *mux_help[] = {
1795 "% h print this help\n\r",
1796 "% x exit emulator\n\r",
1797 "% s save disk data back to file (if -snapshot)\n\r",
1798 "% t toggle console timestamps\n\r"
1799 "% b send break (magic sysrq)\n\r",
1800 "% c switch between console and monitor\n\r",
1801 "% % sends %\n\r",
1802 NULL
1805 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1806 static void mux_print_help(CharDriverState *chr)
1808 int i, j;
1809 char ebuf[15] = "Escape-Char";
1810 char cbuf[50] = "\n\r";
1812 if (term_escape_char > 0 && term_escape_char < 26) {
1813 sprintf(cbuf,"\n\r");
1814 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1815 } else {
1816 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1817 term_escape_char);
1819 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1820 for (i = 0; mux_help[i] != NULL; i++) {
1821 for (j=0; mux_help[i][j] != '\0'; j++) {
1822 if (mux_help[i][j] == '%')
1823 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1824 else
1825 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1830 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1832 if (d->term_got_escape) {
1833 d->term_got_escape = 0;
1834 if (ch == term_escape_char)
1835 goto send_char;
1836 switch(ch) {
1837 case '?':
1838 case 'h':
1839 mux_print_help(chr);
1840 break;
1841 case 'x':
1843 char *term = "QEMU: Terminated\n\r";
1844 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1845 exit(0);
1846 break;
1848 case 's':
1850 int i;
1851 for (i = 0; i < nb_drives; i++) {
1852 bdrv_commit(drives_table[i].bdrv);
1855 break;
1856 case 'b':
1857 qemu_chr_event(chr, CHR_EVENT_BREAK);
1858 break;
1859 case 'c':
1860 /* Switch to the next registered device */
1861 chr->focus++;
1862 if (chr->focus >= d->mux_cnt)
1863 chr->focus = 0;
1864 break;
1865 case 't':
1866 term_timestamps = !term_timestamps;
1867 term_timestamps_start = -1;
1868 break;
1870 } else if (ch == term_escape_char) {
1871 d->term_got_escape = 1;
1872 } else {
1873 send_char:
1874 return 1;
1876 return 0;
1879 static void mux_chr_accept_input(CharDriverState *chr)
1881 int m = chr->focus;
1882 MuxDriver *d = chr->opaque;
1884 while (d->prod != d->cons &&
1885 d->chr_can_read[m] &&
1886 d->chr_can_read[m](d->ext_opaque[m])) {
1887 d->chr_read[m](d->ext_opaque[m],
1888 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1892 static int mux_chr_can_read(void *opaque)
1894 CharDriverState *chr = opaque;
1895 MuxDriver *d = chr->opaque;
1897 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1898 return 1;
1899 if (d->chr_can_read[chr->focus])
1900 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1901 return 0;
1904 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1906 CharDriverState *chr = opaque;
1907 MuxDriver *d = chr->opaque;
1908 int m = chr->focus;
1909 int i;
1911 mux_chr_accept_input (opaque);
1913 for(i = 0; i < size; i++)
1914 if (mux_proc_byte(chr, d, buf[i])) {
1915 if (d->prod == d->cons &&
1916 d->chr_can_read[m] &&
1917 d->chr_can_read[m](d->ext_opaque[m]))
1918 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1919 else
1920 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1924 static void mux_chr_event(void *opaque, int event)
1926 CharDriverState *chr = opaque;
1927 MuxDriver *d = chr->opaque;
1928 int i;
1930 /* Send the event to all registered listeners */
1931 for (i = 0; i < d->mux_cnt; i++)
1932 if (d->chr_event[i])
1933 d->chr_event[i](d->ext_opaque[i], event);
1936 static void mux_chr_update_read_handler(CharDriverState *chr)
1938 MuxDriver *d = chr->opaque;
1940 if (d->mux_cnt >= MAX_MUX) {
1941 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1942 return;
1944 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1945 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1946 d->chr_read[d->mux_cnt] = chr->chr_read;
1947 d->chr_event[d->mux_cnt] = chr->chr_event;
1948 /* Fix up the real driver with mux routines */
1949 if (d->mux_cnt == 0) {
1950 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1951 mux_chr_event, chr);
1953 chr->focus = d->mux_cnt;
1954 d->mux_cnt++;
1957 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1959 CharDriverState *chr;
1960 MuxDriver *d;
1962 chr = qemu_mallocz(sizeof(CharDriverState));
1963 if (!chr)
1964 return NULL;
1965 d = qemu_mallocz(sizeof(MuxDriver));
1966 if (!d) {
1967 free(chr);
1968 return NULL;
1971 chr->opaque = d;
1972 d->drv = drv;
1973 chr->focus = -1;
1974 chr->chr_write = mux_chr_write;
1975 chr->chr_update_read_handler = mux_chr_update_read_handler;
1976 chr->chr_accept_input = mux_chr_accept_input;
1977 return chr;
1981 #ifdef _WIN32
1983 static void socket_cleanup(void)
1985 WSACleanup();
1988 static int socket_init(void)
1990 WSADATA Data;
1991 int ret, err;
1993 ret = WSAStartup(MAKEWORD(2,2), &Data);
1994 if (ret != 0) {
1995 err = WSAGetLastError();
1996 fprintf(stderr, "WSAStartup: %d\n", err);
1997 return -1;
1999 atexit(socket_cleanup);
2000 return 0;
2003 static int send_all(int fd, const uint8_t *buf, int len1)
2005 int ret, len;
2007 len = len1;
2008 while (len > 0) {
2009 ret = send(fd, buf, len, 0);
2010 if (ret < 0) {
2011 int errno;
2012 errno = WSAGetLastError();
2013 if (errno != WSAEWOULDBLOCK) {
2014 return -1;
2016 } else if (ret == 0) {
2017 break;
2018 } else {
2019 buf += ret;
2020 len -= ret;
2023 return len1 - len;
2026 void socket_set_nonblock(int fd)
2028 unsigned long opt = 1;
2029 ioctlsocket(fd, FIONBIO, &opt);
2032 #else
2034 static int unix_write(int fd, const uint8_t *buf, int len1)
2036 int ret, len;
2038 len = len1;
2039 while (len > 0) {
2040 ret = write(fd, buf, len);
2041 if (ret < 0) {
2042 if (errno != EINTR && errno != EAGAIN)
2043 return -1;
2044 } else if (ret == 0) {
2045 break;
2046 } else {
2047 buf += ret;
2048 len -= ret;
2051 return len1 - len;
2054 static inline int send_all(int fd, const uint8_t *buf, int len1)
2056 return unix_write(fd, buf, len1);
2059 void socket_set_nonblock(int fd)
2061 fcntl(fd, F_SETFL, O_NONBLOCK);
2063 #endif /* !_WIN32 */
2065 #ifndef _WIN32
2067 typedef struct {
2068 int fd_in, fd_out;
2069 int max_size;
2070 } FDCharDriver;
2072 #define STDIO_MAX_CLIENTS 1
2073 static int stdio_nb_clients = 0;
2075 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2077 FDCharDriver *s = chr->opaque;
2078 return unix_write(s->fd_out, buf, len);
2081 static int fd_chr_read_poll(void *opaque)
2083 CharDriverState *chr = opaque;
2084 FDCharDriver *s = chr->opaque;
2086 s->max_size = qemu_chr_can_read(chr);
2087 return s->max_size;
2090 static void fd_chr_read(void *opaque)
2092 CharDriverState *chr = opaque;
2093 FDCharDriver *s = chr->opaque;
2094 int size, len;
2095 uint8_t buf[1024];
2097 len = sizeof(buf);
2098 if (len > s->max_size)
2099 len = s->max_size;
2100 if (len == 0)
2101 return;
2102 size = read(s->fd_in, buf, len);
2103 if (size == 0) {
2104 /* FD has been closed. Remove it from the active list. */
2105 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2106 return;
2108 if (size > 0) {
2109 qemu_chr_read(chr, buf, size);
2113 static void fd_chr_update_read_handler(CharDriverState *chr)
2115 FDCharDriver *s = chr->opaque;
2117 if (s->fd_in >= 0) {
2118 if (nographic && s->fd_in == 0) {
2119 } else {
2120 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2121 fd_chr_read, NULL, chr);
2126 static void fd_chr_close(struct CharDriverState *chr)
2128 FDCharDriver *s = chr->opaque;
2130 if (s->fd_in >= 0) {
2131 if (nographic && s->fd_in == 0) {
2132 } else {
2133 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2137 qemu_free(s);
2140 /* open a character device to a unix fd */
2141 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2143 CharDriverState *chr;
2144 FDCharDriver *s;
2146 chr = qemu_mallocz(sizeof(CharDriverState));
2147 if (!chr)
2148 return NULL;
2149 s = qemu_mallocz(sizeof(FDCharDriver));
2150 if (!s) {
2151 free(chr);
2152 return NULL;
2154 s->fd_in = fd_in;
2155 s->fd_out = fd_out;
2156 chr->opaque = s;
2157 chr->chr_write = fd_chr_write;
2158 chr->chr_update_read_handler = fd_chr_update_read_handler;
2159 chr->chr_close = fd_chr_close;
2161 qemu_chr_reset(chr);
2163 return chr;
2166 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2168 int fd_out;
2170 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2171 if (fd_out < 0)
2172 return NULL;
2173 return qemu_chr_open_fd(-1, fd_out);
2176 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2178 int fd_in, fd_out;
2179 char filename_in[256], filename_out[256];
2181 snprintf(filename_in, 256, "%s.in", filename);
2182 snprintf(filename_out, 256, "%s.out", filename);
2183 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2184 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2185 if (fd_in < 0 || fd_out < 0) {
2186 if (fd_in >= 0)
2187 close(fd_in);
2188 if (fd_out >= 0)
2189 close(fd_out);
2190 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2191 if (fd_in < 0)
2192 return NULL;
2194 return qemu_chr_open_fd(fd_in, fd_out);
2198 /* for STDIO, we handle the case where several clients use it
2199 (nographic mode) */
2201 #define TERM_FIFO_MAX_SIZE 1
2203 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2204 static int term_fifo_size;
2206 static int stdio_read_poll(void *opaque)
2208 CharDriverState *chr = opaque;
2210 /* try to flush the queue if needed */
2211 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2212 qemu_chr_read(chr, term_fifo, 1);
2213 term_fifo_size = 0;
2215 /* see if we can absorb more chars */
2216 if (term_fifo_size == 0)
2217 return 1;
2218 else
2219 return 0;
2222 static void stdio_read(void *opaque)
2224 int size;
2225 uint8_t buf[1];
2226 CharDriverState *chr = opaque;
2228 size = read(0, buf, 1);
2229 if (size == 0) {
2230 /* stdin has been closed. Remove it from the active list. */
2231 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2232 return;
2234 if (size > 0) {
2235 if (qemu_chr_can_read(chr) > 0) {
2236 qemu_chr_read(chr, buf, 1);
2237 } else if (term_fifo_size == 0) {
2238 term_fifo[term_fifo_size++] = buf[0];
2243 /* init terminal so that we can grab keys */
2244 static struct termios oldtty;
2245 static int old_fd0_flags;
2246 static int term_atexit_done;
2248 static void term_exit(void)
2250 tcsetattr (0, TCSANOW, &oldtty);
2251 fcntl(0, F_SETFL, old_fd0_flags);
2254 static void term_init(void)
2256 struct termios tty;
2258 tcgetattr (0, &tty);
2259 oldtty = tty;
2260 old_fd0_flags = fcntl(0, F_GETFL);
2262 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2263 |INLCR|IGNCR|ICRNL|IXON);
2264 tty.c_oflag |= OPOST;
2265 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2266 /* if graphical mode, we allow Ctrl-C handling */
2267 if (nographic)
2268 tty.c_lflag &= ~ISIG;
2269 tty.c_cflag &= ~(CSIZE|PARENB);
2270 tty.c_cflag |= CS8;
2271 tty.c_cc[VMIN] = 1;
2272 tty.c_cc[VTIME] = 0;
2274 tcsetattr (0, TCSANOW, &tty);
2276 if (!term_atexit_done++)
2277 atexit(term_exit);
2279 fcntl(0, F_SETFL, O_NONBLOCK);
2282 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2284 term_exit();
2285 stdio_nb_clients--;
2286 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2287 fd_chr_close(chr);
2290 static CharDriverState *qemu_chr_open_stdio(void)
2292 CharDriverState *chr;
2294 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2295 return NULL;
2296 chr = qemu_chr_open_fd(0, 1);
2297 chr->chr_close = qemu_chr_close_stdio;
2298 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2299 stdio_nb_clients++;
2300 term_init();
2302 return chr;
2305 #if defined(__linux__) || defined(__sun__)
2306 static CharDriverState *qemu_chr_open_pty(void)
2308 struct termios tty;
2309 char slave_name[1024];
2310 int master_fd, slave_fd;
2312 #if defined(__linux__)
2313 /* Not satisfying */
2314 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2315 return NULL;
2317 #endif
2319 /* Disabling local echo and line-buffered output */
2320 tcgetattr (master_fd, &tty);
2321 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2322 tty.c_cc[VMIN] = 1;
2323 tty.c_cc[VTIME] = 0;
2324 tcsetattr (master_fd, TCSAFLUSH, &tty);
2326 fprintf(stderr, "char device redirected to %s\n", slave_name);
2327 return qemu_chr_open_fd(master_fd, master_fd);
2330 static void tty_serial_init(int fd, int speed,
2331 int parity, int data_bits, int stop_bits)
2333 struct termios tty;
2334 speed_t spd;
2336 #if 0
2337 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2338 speed, parity, data_bits, stop_bits);
2339 #endif
2340 tcgetattr (fd, &tty);
2342 #define MARGIN 1.1
2343 if (speed <= 50 * MARGIN)
2344 spd = B50;
2345 else if (speed <= 75 * MARGIN)
2346 spd = B75;
2347 else if (speed <= 300 * MARGIN)
2348 spd = B300;
2349 else if (speed <= 600 * MARGIN)
2350 spd = B600;
2351 else if (speed <= 1200 * MARGIN)
2352 spd = B1200;
2353 else if (speed <= 2400 * MARGIN)
2354 spd = B2400;
2355 else if (speed <= 4800 * MARGIN)
2356 spd = B4800;
2357 else if (speed <= 9600 * MARGIN)
2358 spd = B9600;
2359 else if (speed <= 19200 * MARGIN)
2360 spd = B19200;
2361 else if (speed <= 38400 * MARGIN)
2362 spd = B38400;
2363 else if (speed <= 57600 * MARGIN)
2364 spd = B57600;
2365 else if (speed <= 115200 * MARGIN)
2366 spd = B115200;
2367 else
2368 spd = B115200;
2370 cfsetispeed(&tty, spd);
2371 cfsetospeed(&tty, spd);
2373 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2374 |INLCR|IGNCR|ICRNL|IXON);
2375 tty.c_oflag |= OPOST;
2376 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2377 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2378 switch(data_bits) {
2379 default:
2380 case 8:
2381 tty.c_cflag |= CS8;
2382 break;
2383 case 7:
2384 tty.c_cflag |= CS7;
2385 break;
2386 case 6:
2387 tty.c_cflag |= CS6;
2388 break;
2389 case 5:
2390 tty.c_cflag |= CS5;
2391 break;
2393 switch(parity) {
2394 default:
2395 case 'N':
2396 break;
2397 case 'E':
2398 tty.c_cflag |= PARENB;
2399 break;
2400 case 'O':
2401 tty.c_cflag |= PARENB | PARODD;
2402 break;
2404 if (stop_bits == 2)
2405 tty.c_cflag |= CSTOPB;
2407 tcsetattr (fd, TCSANOW, &tty);
2410 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2412 FDCharDriver *s = chr->opaque;
2414 switch(cmd) {
2415 case CHR_IOCTL_SERIAL_SET_PARAMS:
2417 QEMUSerialSetParams *ssp = arg;
2418 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2419 ssp->data_bits, ssp->stop_bits);
2421 break;
2422 case CHR_IOCTL_SERIAL_SET_BREAK:
2424 int enable = *(int *)arg;
2425 if (enable)
2426 tcsendbreak(s->fd_in, 1);
2428 break;
2429 default:
2430 return -ENOTSUP;
2432 return 0;
2435 static CharDriverState *qemu_chr_open_tty(const char *filename)
2437 CharDriverState *chr;
2438 int fd;
2440 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2441 fcntl(fd, F_SETFL, O_NONBLOCK);
2442 tty_serial_init(fd, 115200, 'N', 8, 1);
2443 chr = qemu_chr_open_fd(fd, fd);
2444 if (!chr) {
2445 close(fd);
2446 return NULL;
2448 chr->chr_ioctl = tty_serial_ioctl;
2449 qemu_chr_reset(chr);
2450 return chr;
2452 #else /* ! __linux__ && ! __sun__ */
2453 static CharDriverState *qemu_chr_open_pty(void)
2455 return NULL;
2457 #endif /* __linux__ || __sun__ */
2459 #if defined(__linux__)
2460 typedef struct {
2461 int fd;
2462 int mode;
2463 } ParallelCharDriver;
2465 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2467 if (s->mode != mode) {
2468 int m = mode;
2469 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2470 return 0;
2471 s->mode = mode;
2473 return 1;
2476 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2478 ParallelCharDriver *drv = chr->opaque;
2479 int fd = drv->fd;
2480 uint8_t b;
2482 switch(cmd) {
2483 case CHR_IOCTL_PP_READ_DATA:
2484 if (ioctl(fd, PPRDATA, &b) < 0)
2485 return -ENOTSUP;
2486 *(uint8_t *)arg = b;
2487 break;
2488 case CHR_IOCTL_PP_WRITE_DATA:
2489 b = *(uint8_t *)arg;
2490 if (ioctl(fd, PPWDATA, &b) < 0)
2491 return -ENOTSUP;
2492 break;
2493 case CHR_IOCTL_PP_READ_CONTROL:
2494 if (ioctl(fd, PPRCONTROL, &b) < 0)
2495 return -ENOTSUP;
2496 /* Linux gives only the lowest bits, and no way to know data
2497 direction! For better compatibility set the fixed upper
2498 bits. */
2499 *(uint8_t *)arg = b | 0xc0;
2500 break;
2501 case CHR_IOCTL_PP_WRITE_CONTROL:
2502 b = *(uint8_t *)arg;
2503 if (ioctl(fd, PPWCONTROL, &b) < 0)
2504 return -ENOTSUP;
2505 break;
2506 case CHR_IOCTL_PP_READ_STATUS:
2507 if (ioctl(fd, PPRSTATUS, &b) < 0)
2508 return -ENOTSUP;
2509 *(uint8_t *)arg = b;
2510 break;
2511 case CHR_IOCTL_PP_EPP_READ_ADDR:
2512 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2513 struct ParallelIOArg *parg = arg;
2514 int n = read(fd, parg->buffer, parg->count);
2515 if (n != parg->count) {
2516 return -EIO;
2519 break;
2520 case CHR_IOCTL_PP_EPP_READ:
2521 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2522 struct ParallelIOArg *parg = arg;
2523 int n = read(fd, parg->buffer, parg->count);
2524 if (n != parg->count) {
2525 return -EIO;
2528 break;
2529 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2530 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2531 struct ParallelIOArg *parg = arg;
2532 int n = write(fd, parg->buffer, parg->count);
2533 if (n != parg->count) {
2534 return -EIO;
2537 break;
2538 case CHR_IOCTL_PP_EPP_WRITE:
2539 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2540 struct ParallelIOArg *parg = arg;
2541 int n = write(fd, parg->buffer, parg->count);
2542 if (n != parg->count) {
2543 return -EIO;
2546 break;
2547 default:
2548 return -ENOTSUP;
2550 return 0;
2553 static void pp_close(CharDriverState *chr)
2555 ParallelCharDriver *drv = chr->opaque;
2556 int fd = drv->fd;
2558 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2559 ioctl(fd, PPRELEASE);
2560 close(fd);
2561 qemu_free(drv);
2564 static CharDriverState *qemu_chr_open_pp(const char *filename)
2566 CharDriverState *chr;
2567 ParallelCharDriver *drv;
2568 int fd;
2570 TFR(fd = open(filename, O_RDWR));
2571 if (fd < 0)
2572 return NULL;
2574 if (ioctl(fd, PPCLAIM) < 0) {
2575 close(fd);
2576 return NULL;
2579 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2580 if (!drv) {
2581 close(fd);
2582 return NULL;
2584 drv->fd = fd;
2585 drv->mode = IEEE1284_MODE_COMPAT;
2587 chr = qemu_mallocz(sizeof(CharDriverState));
2588 if (!chr) {
2589 qemu_free(drv);
2590 close(fd);
2591 return NULL;
2593 chr->chr_write = null_chr_write;
2594 chr->chr_ioctl = pp_ioctl;
2595 chr->chr_close = pp_close;
2596 chr->opaque = drv;
2598 qemu_chr_reset(chr);
2600 return chr;
2602 #endif /* __linux__ */
2604 #else /* _WIN32 */
2606 typedef struct {
2607 int max_size;
2608 HANDLE hcom, hrecv, hsend;
2609 OVERLAPPED orecv, osend;
2610 BOOL fpipe;
2611 DWORD len;
2612 } WinCharState;
2614 #define NSENDBUF 2048
2615 #define NRECVBUF 2048
2616 #define MAXCONNECT 1
2617 #define NTIMEOUT 5000
2619 static int win_chr_poll(void *opaque);
2620 static int win_chr_pipe_poll(void *opaque);
2622 static void win_chr_close(CharDriverState *chr)
2624 WinCharState *s = chr->opaque;
2626 if (s->hsend) {
2627 CloseHandle(s->hsend);
2628 s->hsend = NULL;
2630 if (s->hrecv) {
2631 CloseHandle(s->hrecv);
2632 s->hrecv = NULL;
2634 if (s->hcom) {
2635 CloseHandle(s->hcom);
2636 s->hcom = NULL;
2638 if (s->fpipe)
2639 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2640 else
2641 qemu_del_polling_cb(win_chr_poll, chr);
2644 static int win_chr_init(CharDriverState *chr, const char *filename)
2646 WinCharState *s = chr->opaque;
2647 COMMCONFIG comcfg;
2648 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2649 COMSTAT comstat;
2650 DWORD size;
2651 DWORD err;
2653 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2654 if (!s->hsend) {
2655 fprintf(stderr, "Failed CreateEvent\n");
2656 goto fail;
2658 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2659 if (!s->hrecv) {
2660 fprintf(stderr, "Failed CreateEvent\n");
2661 goto fail;
2664 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2665 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2666 if (s->hcom == INVALID_HANDLE_VALUE) {
2667 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2668 s->hcom = NULL;
2669 goto fail;
2672 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2673 fprintf(stderr, "Failed SetupComm\n");
2674 goto fail;
2677 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2678 size = sizeof(COMMCONFIG);
2679 GetDefaultCommConfig(filename, &comcfg, &size);
2680 comcfg.dcb.DCBlength = sizeof(DCB);
2681 CommConfigDialog(filename, NULL, &comcfg);
2683 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2684 fprintf(stderr, "Failed SetCommState\n");
2685 goto fail;
2688 if (!SetCommMask(s->hcom, EV_ERR)) {
2689 fprintf(stderr, "Failed SetCommMask\n");
2690 goto fail;
2693 cto.ReadIntervalTimeout = MAXDWORD;
2694 if (!SetCommTimeouts(s->hcom, &cto)) {
2695 fprintf(stderr, "Failed SetCommTimeouts\n");
2696 goto fail;
2699 if (!ClearCommError(s->hcom, &err, &comstat)) {
2700 fprintf(stderr, "Failed ClearCommError\n");
2701 goto fail;
2703 qemu_add_polling_cb(win_chr_poll, chr);
2704 return 0;
2706 fail:
2707 win_chr_close(chr);
2708 return -1;
2711 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2713 WinCharState *s = chr->opaque;
2714 DWORD len, ret, size, err;
2716 len = len1;
2717 ZeroMemory(&s->osend, sizeof(s->osend));
2718 s->osend.hEvent = s->hsend;
2719 while (len > 0) {
2720 if (s->hsend)
2721 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2722 else
2723 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2724 if (!ret) {
2725 err = GetLastError();
2726 if (err == ERROR_IO_PENDING) {
2727 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2728 if (ret) {
2729 buf += size;
2730 len -= size;
2731 } else {
2732 break;
2734 } else {
2735 break;
2737 } else {
2738 buf += size;
2739 len -= size;
2742 return len1 - len;
2745 static int win_chr_read_poll(CharDriverState *chr)
2747 WinCharState *s = chr->opaque;
2749 s->max_size = qemu_chr_can_read(chr);
2750 return s->max_size;
2753 static void win_chr_readfile(CharDriverState *chr)
2755 WinCharState *s = chr->opaque;
2756 int ret, err;
2757 uint8_t buf[1024];
2758 DWORD size;
2760 ZeroMemory(&s->orecv, sizeof(s->orecv));
2761 s->orecv.hEvent = s->hrecv;
2762 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2763 if (!ret) {
2764 err = GetLastError();
2765 if (err == ERROR_IO_PENDING) {
2766 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2770 if (size > 0) {
2771 qemu_chr_read(chr, buf, size);
2775 static void win_chr_read(CharDriverState *chr)
2777 WinCharState *s = chr->opaque;
2779 if (s->len > s->max_size)
2780 s->len = s->max_size;
2781 if (s->len == 0)
2782 return;
2784 win_chr_readfile(chr);
2787 static int win_chr_poll(void *opaque)
2789 CharDriverState *chr = opaque;
2790 WinCharState *s = chr->opaque;
2791 COMSTAT status;
2792 DWORD comerr;
2794 ClearCommError(s->hcom, &comerr, &status);
2795 if (status.cbInQue > 0) {
2796 s->len = status.cbInQue;
2797 win_chr_read_poll(chr);
2798 win_chr_read(chr);
2799 return 1;
2801 return 0;
2804 static CharDriverState *qemu_chr_open_win(const char *filename)
2806 CharDriverState *chr;
2807 WinCharState *s;
2809 chr = qemu_mallocz(sizeof(CharDriverState));
2810 if (!chr)
2811 return NULL;
2812 s = qemu_mallocz(sizeof(WinCharState));
2813 if (!s) {
2814 free(chr);
2815 return NULL;
2817 chr->opaque = s;
2818 chr->chr_write = win_chr_write;
2819 chr->chr_close = win_chr_close;
2821 if (win_chr_init(chr, filename) < 0) {
2822 free(s);
2823 free(chr);
2824 return NULL;
2826 qemu_chr_reset(chr);
2827 return chr;
2830 static int win_chr_pipe_poll(void *opaque)
2832 CharDriverState *chr = opaque;
2833 WinCharState *s = chr->opaque;
2834 DWORD size;
2836 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2837 if (size > 0) {
2838 s->len = size;
2839 win_chr_read_poll(chr);
2840 win_chr_read(chr);
2841 return 1;
2843 return 0;
2846 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2848 WinCharState *s = chr->opaque;
2849 OVERLAPPED ov;
2850 int ret;
2851 DWORD size;
2852 char openname[256];
2854 s->fpipe = TRUE;
2856 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2857 if (!s->hsend) {
2858 fprintf(stderr, "Failed CreateEvent\n");
2859 goto fail;
2861 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2862 if (!s->hrecv) {
2863 fprintf(stderr, "Failed CreateEvent\n");
2864 goto fail;
2867 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2868 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2869 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2870 PIPE_WAIT,
2871 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2872 if (s->hcom == INVALID_HANDLE_VALUE) {
2873 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2874 s->hcom = NULL;
2875 goto fail;
2878 ZeroMemory(&ov, sizeof(ov));
2879 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2880 ret = ConnectNamedPipe(s->hcom, &ov);
2881 if (ret) {
2882 fprintf(stderr, "Failed ConnectNamedPipe\n");
2883 goto fail;
2886 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2887 if (!ret) {
2888 fprintf(stderr, "Failed GetOverlappedResult\n");
2889 if (ov.hEvent) {
2890 CloseHandle(ov.hEvent);
2891 ov.hEvent = NULL;
2893 goto fail;
2896 if (ov.hEvent) {
2897 CloseHandle(ov.hEvent);
2898 ov.hEvent = NULL;
2900 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2901 return 0;
2903 fail:
2904 win_chr_close(chr);
2905 return -1;
2909 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2911 CharDriverState *chr;
2912 WinCharState *s;
2914 chr = qemu_mallocz(sizeof(CharDriverState));
2915 if (!chr)
2916 return NULL;
2917 s = qemu_mallocz(sizeof(WinCharState));
2918 if (!s) {
2919 free(chr);
2920 return NULL;
2922 chr->opaque = s;
2923 chr->chr_write = win_chr_write;
2924 chr->chr_close = win_chr_close;
2926 if (win_chr_pipe_init(chr, filename) < 0) {
2927 free(s);
2928 free(chr);
2929 return NULL;
2931 qemu_chr_reset(chr);
2932 return chr;
2935 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2937 CharDriverState *chr;
2938 WinCharState *s;
2940 chr = qemu_mallocz(sizeof(CharDriverState));
2941 if (!chr)
2942 return NULL;
2943 s = qemu_mallocz(sizeof(WinCharState));
2944 if (!s) {
2945 free(chr);
2946 return NULL;
2948 s->hcom = fd_out;
2949 chr->opaque = s;
2950 chr->chr_write = win_chr_write;
2951 qemu_chr_reset(chr);
2952 return chr;
2955 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2957 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2960 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2962 HANDLE fd_out;
2964 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2965 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2966 if (fd_out == INVALID_HANDLE_VALUE)
2967 return NULL;
2969 return qemu_chr_open_win_file(fd_out);
2971 #endif /* !_WIN32 */
2973 /***********************************************************/
2974 /* UDP Net console */
2976 typedef struct {
2977 int fd;
2978 struct sockaddr_in daddr;
2979 uint8_t buf[1024];
2980 int bufcnt;
2981 int bufptr;
2982 int max_size;
2983 } NetCharDriver;
2985 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2987 NetCharDriver *s = chr->opaque;
2989 return sendto(s->fd, buf, len, 0,
2990 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2993 static int udp_chr_read_poll(void *opaque)
2995 CharDriverState *chr = opaque;
2996 NetCharDriver *s = chr->opaque;
2998 s->max_size = qemu_chr_can_read(chr);
3000 /* If there were any stray characters in the queue process them
3001 * first
3003 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3004 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3005 s->bufptr++;
3006 s->max_size = qemu_chr_can_read(chr);
3008 return s->max_size;
3011 static void udp_chr_read(void *opaque)
3013 CharDriverState *chr = opaque;
3014 NetCharDriver *s = chr->opaque;
3016 if (s->max_size == 0)
3017 return;
3018 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3019 s->bufptr = s->bufcnt;
3020 if (s->bufcnt <= 0)
3021 return;
3023 s->bufptr = 0;
3024 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3025 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3026 s->bufptr++;
3027 s->max_size = qemu_chr_can_read(chr);
3031 static void udp_chr_update_read_handler(CharDriverState *chr)
3033 NetCharDriver *s = chr->opaque;
3035 if (s->fd >= 0) {
3036 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3037 udp_chr_read, NULL, chr);
3041 #ifndef _WIN32
3042 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3043 #endif
3044 int parse_host_src_port(struct sockaddr_in *haddr,
3045 struct sockaddr_in *saddr,
3046 const char *str);
3048 static CharDriverState *qemu_chr_open_udp(const char *def)
3050 CharDriverState *chr = NULL;
3051 NetCharDriver *s = NULL;
3052 int fd = -1;
3053 struct sockaddr_in saddr;
3055 chr = qemu_mallocz(sizeof(CharDriverState));
3056 if (!chr)
3057 goto return_err;
3058 s = qemu_mallocz(sizeof(NetCharDriver));
3059 if (!s)
3060 goto return_err;
3062 fd = socket(PF_INET, SOCK_DGRAM, 0);
3063 if (fd < 0) {
3064 perror("socket(PF_INET, SOCK_DGRAM)");
3065 goto return_err;
3068 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3069 printf("Could not parse: %s\n", def);
3070 goto return_err;
3073 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3075 perror("bind");
3076 goto return_err;
3079 s->fd = fd;
3080 s->bufcnt = 0;
3081 s->bufptr = 0;
3082 chr->opaque = s;
3083 chr->chr_write = udp_chr_write;
3084 chr->chr_update_read_handler = udp_chr_update_read_handler;
3085 return chr;
3087 return_err:
3088 if (chr)
3089 free(chr);
3090 if (s)
3091 free(s);
3092 if (fd >= 0)
3093 closesocket(fd);
3094 return NULL;
3097 /***********************************************************/
3098 /* TCP Net console */
3100 typedef struct {
3101 int fd, listen_fd;
3102 int connected;
3103 int max_size;
3104 int do_telnetopt;
3105 int do_nodelay;
3106 int is_unix;
3107 } TCPCharDriver;
3109 static void tcp_chr_accept(void *opaque);
3111 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3113 TCPCharDriver *s = chr->opaque;
3114 if (s->connected) {
3115 return send_all(s->fd, buf, len);
3116 } else {
3117 /* XXX: indicate an error ? */
3118 return len;
3122 static int tcp_chr_read_poll(void *opaque)
3124 CharDriverState *chr = opaque;
3125 TCPCharDriver *s = chr->opaque;
3126 if (!s->connected)
3127 return 0;
3128 s->max_size = qemu_chr_can_read(chr);
3129 return s->max_size;
3132 #define IAC 255
3133 #define IAC_BREAK 243
3134 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3135 TCPCharDriver *s,
3136 uint8_t *buf, int *size)
3138 /* Handle any telnet client's basic IAC options to satisfy char by
3139 * char mode with no echo. All IAC options will be removed from
3140 * the buf and the do_telnetopt variable will be used to track the
3141 * state of the width of the IAC information.
3143 * IAC commands come in sets of 3 bytes with the exception of the
3144 * "IAC BREAK" command and the double IAC.
3147 int i;
3148 int j = 0;
3150 for (i = 0; i < *size; i++) {
3151 if (s->do_telnetopt > 1) {
3152 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3153 /* Double IAC means send an IAC */
3154 if (j != i)
3155 buf[j] = buf[i];
3156 j++;
3157 s->do_telnetopt = 1;
3158 } else {
3159 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3160 /* Handle IAC break commands by sending a serial break */
3161 qemu_chr_event(chr, CHR_EVENT_BREAK);
3162 s->do_telnetopt++;
3164 s->do_telnetopt++;
3166 if (s->do_telnetopt >= 4) {
3167 s->do_telnetopt = 1;
3169 } else {
3170 if ((unsigned char)buf[i] == IAC) {
3171 s->do_telnetopt = 2;
3172 } else {
3173 if (j != i)
3174 buf[j] = buf[i];
3175 j++;
3179 *size = j;
3182 static void tcp_chr_read(void *opaque)
3184 CharDriverState *chr = opaque;
3185 TCPCharDriver *s = chr->opaque;
3186 uint8_t buf[1024];
3187 int len, size;
3189 if (!s->connected || s->max_size <= 0)
3190 return;
3191 len = sizeof(buf);
3192 if (len > s->max_size)
3193 len = s->max_size;
3194 size = recv(s->fd, buf, len, 0);
3195 if (size == 0) {
3196 /* connection closed */
3197 s->connected = 0;
3198 if (s->listen_fd >= 0) {
3199 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3201 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3202 closesocket(s->fd);
3203 s->fd = -1;
3204 } else if (size > 0) {
3205 if (s->do_telnetopt)
3206 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3207 if (size > 0)
3208 qemu_chr_read(chr, buf, size);
3212 static void tcp_chr_connect(void *opaque)
3214 CharDriverState *chr = opaque;
3215 TCPCharDriver *s = chr->opaque;
3217 s->connected = 1;
3218 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3219 tcp_chr_read, NULL, chr);
3220 qemu_chr_reset(chr);
3223 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3224 static void tcp_chr_telnet_init(int fd)
3226 char buf[3];
3227 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3228 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3229 send(fd, (char *)buf, 3, 0);
3230 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3231 send(fd, (char *)buf, 3, 0);
3232 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3233 send(fd, (char *)buf, 3, 0);
3234 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3235 send(fd, (char *)buf, 3, 0);
3238 static void socket_set_nodelay(int fd)
3240 int val = 1;
3241 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3244 static void tcp_chr_accept(void *opaque)
3246 CharDriverState *chr = opaque;
3247 TCPCharDriver *s = chr->opaque;
3248 struct sockaddr_in saddr;
3249 #ifndef _WIN32
3250 struct sockaddr_un uaddr;
3251 #endif
3252 struct sockaddr *addr;
3253 socklen_t len;
3254 int fd;
3256 for(;;) {
3257 #ifndef _WIN32
3258 if (s->is_unix) {
3259 len = sizeof(uaddr);
3260 addr = (struct sockaddr *)&uaddr;
3261 } else
3262 #endif
3264 len = sizeof(saddr);
3265 addr = (struct sockaddr *)&saddr;
3267 fd = accept(s->listen_fd, addr, &len);
3268 if (fd < 0 && errno != EINTR) {
3269 return;
3270 } else if (fd >= 0) {
3271 if (s->do_telnetopt)
3272 tcp_chr_telnet_init(fd);
3273 break;
3276 socket_set_nonblock(fd);
3277 if (s->do_nodelay)
3278 socket_set_nodelay(fd);
3279 s->fd = fd;
3280 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3281 tcp_chr_connect(chr);
3284 static void tcp_chr_close(CharDriverState *chr)
3286 TCPCharDriver *s = chr->opaque;
3287 if (s->fd >= 0)
3288 closesocket(s->fd);
3289 if (s->listen_fd >= 0)
3290 closesocket(s->listen_fd);
3291 qemu_free(s);
3294 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3295 int is_telnet,
3296 int is_unix)
3298 CharDriverState *chr = NULL;
3299 TCPCharDriver *s = NULL;
3300 int fd = -1, ret, err, val;
3301 int is_listen = 0;
3302 int is_waitconnect = 1;
3303 int do_nodelay = 0;
3304 const char *ptr;
3305 struct sockaddr_in saddr;
3306 #ifndef _WIN32
3307 struct sockaddr_un uaddr;
3308 #endif
3309 struct sockaddr *addr;
3310 socklen_t addrlen;
3312 #ifndef _WIN32
3313 if (is_unix) {
3314 addr = (struct sockaddr *)&uaddr;
3315 addrlen = sizeof(uaddr);
3316 if (parse_unix_path(&uaddr, host_str) < 0)
3317 goto fail;
3318 } else
3319 #endif
3321 addr = (struct sockaddr *)&saddr;
3322 addrlen = sizeof(saddr);
3323 if (parse_host_port(&saddr, host_str) < 0)
3324 goto fail;
3327 ptr = host_str;
3328 while((ptr = strchr(ptr,','))) {
3329 ptr++;
3330 if (!strncmp(ptr,"server",6)) {
3331 is_listen = 1;
3332 } else if (!strncmp(ptr,"nowait",6)) {
3333 is_waitconnect = 0;
3334 } else if (!strncmp(ptr,"nodelay",6)) {
3335 do_nodelay = 1;
3336 } else {
3337 printf("Unknown option: %s\n", ptr);
3338 goto fail;
3341 if (!is_listen)
3342 is_waitconnect = 0;
3344 chr = qemu_mallocz(sizeof(CharDriverState));
3345 if (!chr)
3346 goto fail;
3347 s = qemu_mallocz(sizeof(TCPCharDriver));
3348 if (!s)
3349 goto fail;
3351 #ifndef _WIN32
3352 if (is_unix)
3353 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3354 else
3355 #endif
3356 fd = socket(PF_INET, SOCK_STREAM, 0);
3358 if (fd < 0)
3359 goto fail;
3361 if (!is_waitconnect)
3362 socket_set_nonblock(fd);
3364 s->connected = 0;
3365 s->fd = -1;
3366 s->listen_fd = -1;
3367 s->is_unix = is_unix;
3368 s->do_nodelay = do_nodelay && !is_unix;
3370 chr->opaque = s;
3371 chr->chr_write = tcp_chr_write;
3372 chr->chr_close = tcp_chr_close;
3374 if (is_listen) {
3375 /* allow fast reuse */
3376 #ifndef _WIN32
3377 if (is_unix) {
3378 char path[109];
3379 strncpy(path, uaddr.sun_path, 108);
3380 path[108] = 0;
3381 unlink(path);
3382 } else
3383 #endif
3385 val = 1;
3386 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3389 ret = bind(fd, addr, addrlen);
3390 if (ret < 0)
3391 goto fail;
3393 ret = listen(fd, 0);
3394 if (ret < 0)
3395 goto fail;
3397 s->listen_fd = fd;
3398 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3399 if (is_telnet)
3400 s->do_telnetopt = 1;
3401 } else {
3402 for(;;) {
3403 ret = connect(fd, addr, addrlen);
3404 if (ret < 0) {
3405 err = socket_error();
3406 if (err == EINTR || err == EWOULDBLOCK) {
3407 } else if (err == EINPROGRESS) {
3408 break;
3409 #ifdef _WIN32
3410 } else if (err == WSAEALREADY) {
3411 break;
3412 #endif
3413 } else {
3414 goto fail;
3416 } else {
3417 s->connected = 1;
3418 break;
3421 s->fd = fd;
3422 socket_set_nodelay(fd);
3423 if (s->connected)
3424 tcp_chr_connect(chr);
3425 else
3426 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3429 if (is_listen && is_waitconnect) {
3430 printf("QEMU waiting for connection on: %s\n", host_str);
3431 tcp_chr_accept(chr);
3432 socket_set_nonblock(s->listen_fd);
3435 return chr;
3436 fail:
3437 if (fd >= 0)
3438 closesocket(fd);
3439 qemu_free(s);
3440 qemu_free(chr);
3441 return NULL;
3444 CharDriverState *qemu_chr_open(const char *filename)
3446 const char *p;
3448 if (!strcmp(filename, "vc")) {
3449 return text_console_init(&display_state, 0);
3450 } else if (strstart(filename, "vc:", &p)) {
3451 return text_console_init(&display_state, p);
3452 } else if (!strcmp(filename, "null")) {
3453 return qemu_chr_open_null();
3454 } else
3455 if (strstart(filename, "tcp:", &p)) {
3456 return qemu_chr_open_tcp(p, 0, 0);
3457 } else
3458 if (strstart(filename, "telnet:", &p)) {
3459 return qemu_chr_open_tcp(p, 1, 0);
3460 } else
3461 if (strstart(filename, "udp:", &p)) {
3462 return qemu_chr_open_udp(p);
3463 } else
3464 if (strstart(filename, "mon:", &p)) {
3465 CharDriverState *drv = qemu_chr_open(p);
3466 if (drv) {
3467 drv = qemu_chr_open_mux(drv);
3468 monitor_init(drv, !nographic);
3469 return drv;
3471 printf("Unable to open driver: %s\n", p);
3472 return 0;
3473 } else
3474 #ifndef _WIN32
3475 if (strstart(filename, "unix:", &p)) {
3476 return qemu_chr_open_tcp(p, 0, 1);
3477 } else if (strstart(filename, "file:", &p)) {
3478 return qemu_chr_open_file_out(p);
3479 } else if (strstart(filename, "pipe:", &p)) {
3480 return qemu_chr_open_pipe(p);
3481 } else if (!strcmp(filename, "pty")) {
3482 return qemu_chr_open_pty();
3483 } else if (!strcmp(filename, "stdio")) {
3484 return qemu_chr_open_stdio();
3485 } else
3486 #if defined(__linux__)
3487 if (strstart(filename, "/dev/parport", NULL)) {
3488 return qemu_chr_open_pp(filename);
3489 } else
3490 #endif
3491 #if defined(__linux__) || defined(__sun__)
3492 if (strstart(filename, "/dev/", NULL)) {
3493 return qemu_chr_open_tty(filename);
3494 } else
3495 #endif
3496 #else /* !_WIN32 */
3497 if (strstart(filename, "COM", NULL)) {
3498 return qemu_chr_open_win(filename);
3499 } else
3500 if (strstart(filename, "pipe:", &p)) {
3501 return qemu_chr_open_win_pipe(p);
3502 } else
3503 if (strstart(filename, "con:", NULL)) {
3504 return qemu_chr_open_win_con(filename);
3505 } else
3506 if (strstart(filename, "file:", &p)) {
3507 return qemu_chr_open_win_file_out(p);
3509 #endif
3511 return NULL;
3515 void qemu_chr_close(CharDriverState *chr)
3517 if (chr->chr_close)
3518 chr->chr_close(chr);
3519 qemu_free(chr);
3522 /***********************************************************/
3523 /* network device redirectors */
3525 __attribute__ (( unused ))
3526 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3528 int len, i, j, c;
3530 for(i=0;i<size;i+=16) {
3531 len = size - i;
3532 if (len > 16)
3533 len = 16;
3534 fprintf(f, "%08x ", i);
3535 for(j=0;j<16;j++) {
3536 if (j < len)
3537 fprintf(f, " %02x", buf[i+j]);
3538 else
3539 fprintf(f, " ");
3541 fprintf(f, " ");
3542 for(j=0;j<len;j++) {
3543 c = buf[i+j];
3544 if (c < ' ' || c > '~')
3545 c = '.';
3546 fprintf(f, "%c", c);
3548 fprintf(f, "\n");
3552 static int parse_macaddr(uint8_t *macaddr, const char *p)
3554 int i;
3555 char *last_char;
3556 long int offset;
3558 errno = 0;
3559 offset = strtol(p, &last_char, 0);
3560 if (0 == errno && '\0' == *last_char &&
3561 offset >= 0 && offset <= 0xFFFFFF) {
3562 macaddr[3] = (offset & 0xFF0000) >> 16;
3563 macaddr[4] = (offset & 0xFF00) >> 8;
3564 macaddr[5] = offset & 0xFF;
3565 return 0;
3566 } else {
3567 for(i = 0; i < 6; i++) {
3568 macaddr[i] = strtol(p, (char **)&p, 16);
3569 if (i == 5) {
3570 if (*p != '\0')
3571 return -1;
3572 } else {
3573 if (*p != ':' && *p != '-')
3574 return -1;
3575 p++;
3578 return 0;
3581 return -1;
3584 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3586 const char *p, *p1;
3587 int len;
3588 p = *pp;
3589 p1 = strchr(p, sep);
3590 if (!p1)
3591 return -1;
3592 len = p1 - p;
3593 p1++;
3594 if (buf_size > 0) {
3595 if (len > buf_size - 1)
3596 len = buf_size - 1;
3597 memcpy(buf, p, len);
3598 buf[len] = '\0';
3600 *pp = p1;
3601 return 0;
3604 int parse_host_src_port(struct sockaddr_in *haddr,
3605 struct sockaddr_in *saddr,
3606 const char *input_str)
3608 char *str = strdup(input_str);
3609 char *host_str = str;
3610 char *src_str;
3611 char *ptr;
3614 * Chop off any extra arguments at the end of the string which
3615 * would start with a comma, then fill in the src port information
3616 * if it was provided else use the "any address" and "any port".
3618 if ((ptr = strchr(str,',')))
3619 *ptr = '\0';
3621 if ((src_str = strchr(input_str,'@'))) {
3622 *src_str = '\0';
3623 src_str++;
3626 if (parse_host_port(haddr, host_str) < 0)
3627 goto fail;
3629 if (!src_str || *src_str == '\0')
3630 src_str = ":0";
3632 if (parse_host_port(saddr, src_str) < 0)
3633 goto fail;
3635 free(str);
3636 return(0);
3638 fail:
3639 free(str);
3640 return -1;
3643 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3645 char buf[512];
3646 struct hostent *he;
3647 const char *p, *r;
3648 int port;
3650 p = str;
3651 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3652 return -1;
3653 saddr->sin_family = AF_INET;
3654 if (buf[0] == '\0') {
3655 saddr->sin_addr.s_addr = 0;
3656 } else {
3657 if (isdigit(buf[0])) {
3658 if (!inet_aton(buf, &saddr->sin_addr))
3659 return -1;
3660 } else {
3661 if ((he = gethostbyname(buf)) == NULL)
3662 return - 1;
3663 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3666 port = strtol(p, (char **)&r, 0);
3667 if (r == p)
3668 return -1;
3669 saddr->sin_port = htons(port);
3670 return 0;
3673 #ifndef _WIN32
3674 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3676 const char *p;
3677 int len;
3679 len = MIN(108, strlen(str));
3680 p = strchr(str, ',');
3681 if (p)
3682 len = MIN(len, p - str);
3684 memset(uaddr, 0, sizeof(*uaddr));
3686 uaddr->sun_family = AF_UNIX;
3687 memcpy(uaddr->sun_path, str, len);
3689 return 0;
3691 #endif
3693 /* find or alloc a new VLAN */
3694 VLANState *qemu_find_vlan(int id)
3696 VLANState **pvlan, *vlan;
3697 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3698 if (vlan->id == id)
3699 return vlan;
3701 vlan = qemu_mallocz(sizeof(VLANState));
3702 if (!vlan)
3703 return NULL;
3704 vlan->id = id;
3705 vlan->next = NULL;
3706 pvlan = &first_vlan;
3707 while (*pvlan != NULL)
3708 pvlan = &(*pvlan)->next;
3709 *pvlan = vlan;
3710 return vlan;
3713 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3714 IOReadHandler *fd_read,
3715 IOCanRWHandler *fd_can_read,
3716 void *opaque)
3718 VLANClientState *vc, **pvc;
3719 vc = qemu_mallocz(sizeof(VLANClientState));
3720 if (!vc)
3721 return NULL;
3722 vc->fd_read = fd_read;
3723 vc->fd_can_read = fd_can_read;
3724 vc->opaque = opaque;
3725 vc->vlan = vlan;
3727 vc->next = NULL;
3728 pvc = &vlan->first_client;
3729 while (*pvc != NULL)
3730 pvc = &(*pvc)->next;
3731 *pvc = vc;
3732 return vc;
3735 int qemu_can_send_packet(VLANClientState *vc1)
3737 VLANState *vlan = vc1->vlan;
3738 VLANClientState *vc;
3740 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3741 if (vc != vc1) {
3742 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3743 return 1;
3746 return 0;
3749 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3751 VLANState *vlan = vc1->vlan;
3752 VLANClientState *vc;
3754 #if 0
3755 printf("vlan %d send:\n", vlan->id);
3756 hex_dump(stdout, buf, size);
3757 #endif
3758 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3759 if (vc != vc1) {
3760 vc->fd_read(vc->opaque, buf, size);
3765 #if defined(CONFIG_SLIRP)
3767 /* slirp network adapter */
3769 static int slirp_inited;
3770 static VLANClientState *slirp_vc;
3772 int slirp_can_output(void)
3774 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3777 void slirp_output(const uint8_t *pkt, int pkt_len)
3779 #if 0
3780 printf("slirp output:\n");
3781 hex_dump(stdout, pkt, pkt_len);
3782 #endif
3783 if (!slirp_vc)
3784 return;
3785 qemu_send_packet(slirp_vc, pkt, pkt_len);
3788 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3790 #if 0
3791 printf("slirp input:\n");
3792 hex_dump(stdout, buf, size);
3793 #endif
3794 slirp_input(buf, size);
3797 static int net_slirp_init(VLANState *vlan)
3799 if (!slirp_inited) {
3800 slirp_inited = 1;
3801 slirp_init();
3803 slirp_vc = qemu_new_vlan_client(vlan,
3804 slirp_receive, NULL, NULL);
3805 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3806 return 0;
3809 static void net_slirp_redir(const char *redir_str)
3811 int is_udp;
3812 char buf[256], *r;
3813 const char *p;
3814 struct in_addr guest_addr;
3815 int host_port, guest_port;
3817 if (!slirp_inited) {
3818 slirp_inited = 1;
3819 slirp_init();
3822 p = redir_str;
3823 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3824 goto fail;
3825 if (!strcmp(buf, "tcp")) {
3826 is_udp = 0;
3827 } else if (!strcmp(buf, "udp")) {
3828 is_udp = 1;
3829 } else {
3830 goto fail;
3833 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3834 goto fail;
3835 host_port = strtol(buf, &r, 0);
3836 if (r == buf)
3837 goto fail;
3839 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3840 goto fail;
3841 if (buf[0] == '\0') {
3842 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3844 if (!inet_aton(buf, &guest_addr))
3845 goto fail;
3847 guest_port = strtol(p, &r, 0);
3848 if (r == p)
3849 goto fail;
3851 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3852 fprintf(stderr, "qemu: could not set up redirection\n");
3853 exit(1);
3855 return;
3856 fail:
3857 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3858 exit(1);
3861 #ifndef _WIN32
3863 char smb_dir[1024];
3865 static void erase_dir(char *dir_name)
3867 DIR *d;
3868 struct dirent *de;
3869 char filename[1024];
3871 /* erase all the files in the directory */
3872 if ((d = opendir(dir_name)) != 0) {
3873 for(;;) {
3874 de = readdir(d);
3875 if (!de)
3876 break;
3877 if (strcmp(de->d_name, ".") != 0 &&
3878 strcmp(de->d_name, "..") != 0) {
3879 snprintf(filename, sizeof(filename), "%s/%s",
3880 smb_dir, de->d_name);
3881 if (unlink(filename) != 0) /* is it a directory? */
3882 erase_dir(filename);
3885 closedir(d);
3886 rmdir(dir_name);
3890 /* automatic user mode samba server configuration */
3891 static void smb_exit(void)
3893 erase_dir(smb_dir);
3896 /* automatic user mode samba server configuration */
3897 static void net_slirp_smb(const char *exported_dir)
3899 char smb_conf[1024];
3900 char smb_cmdline[1024];
3901 FILE *f;
3903 if (!slirp_inited) {
3904 slirp_inited = 1;
3905 slirp_init();
3908 /* XXX: better tmp dir construction */
3909 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3910 if (mkdir(smb_dir, 0700) < 0) {
3911 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3912 exit(1);
3914 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3916 f = fopen(smb_conf, "w");
3917 if (!f) {
3918 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3919 exit(1);
3921 fprintf(f,
3922 "[global]\n"
3923 "private dir=%s\n"
3924 "smb ports=0\n"
3925 "socket address=127.0.0.1\n"
3926 "pid directory=%s\n"
3927 "lock directory=%s\n"
3928 "log file=%s/log.smbd\n"
3929 "smb passwd file=%s/smbpasswd\n"
3930 "security = share\n"
3931 "[qemu]\n"
3932 "path=%s\n"
3933 "read only=no\n"
3934 "guest ok=yes\n",
3935 smb_dir,
3936 smb_dir,
3937 smb_dir,
3938 smb_dir,
3939 smb_dir,
3940 exported_dir
3942 fclose(f);
3943 atexit(smb_exit);
3945 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3946 SMBD_COMMAND, smb_conf);
3948 slirp_add_exec(0, smb_cmdline, 4, 139);
3951 #endif /* !defined(_WIN32) */
3952 void do_info_slirp(void)
3954 slirp_stats();
3957 #endif /* CONFIG_SLIRP */
3959 #if !defined(_WIN32)
3961 typedef struct TAPState {
3962 VLANClientState *vc;
3963 int fd;
3964 char down_script[1024];
3965 int no_poll;
3966 } TAPState;
3968 static int tap_read_poll(void *opaque)
3970 TAPState *s = opaque;
3971 return (!s->no_poll);
3974 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3976 TAPState *s = opaque;
3977 int ret;
3978 for(;;) {
3979 ret = write(s->fd, buf, size);
3980 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3981 } else {
3982 break;
3987 static void tap_send(void *opaque)
3989 TAPState *s = opaque;
3990 uint8_t buf[4096];
3991 int size;
3993 #ifdef __sun__
3994 struct strbuf sbuf;
3995 int f = 0;
3996 sbuf.maxlen = sizeof(buf);
3997 sbuf.buf = buf;
3998 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3999 #else
4000 size = read(s->fd, buf, sizeof(buf));
4001 #endif
4002 if (size > 0) {
4003 qemu_send_packet(s->vc, buf, size);
4007 int hack_around_tap(void *opaque)
4009 VLANClientState *vc = opaque;
4010 TAPState *ts = vc->opaque;
4012 if (vc->fd_read != tap_receive)
4013 return -1;
4015 if (ts) {
4016 ts->no_poll = 1;
4017 return ts->fd;
4020 return -1;
4023 /* fd support */
4025 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4027 TAPState *s;
4029 s = qemu_mallocz(sizeof(TAPState));
4030 if (!s)
4031 return NULL;
4032 s->fd = fd;
4033 s->no_poll = 0;
4034 enable_sigio_timer(fd);
4035 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4036 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4037 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4038 return s;
4041 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4042 static int tap_open(char *ifname, int ifname_size)
4044 int fd;
4045 char *dev;
4046 struct stat s;
4048 TFR(fd = open("/dev/tap", O_RDWR));
4049 if (fd < 0) {
4050 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4051 return -1;
4054 fstat(fd, &s);
4055 dev = devname(s.st_rdev, S_IFCHR);
4056 pstrcpy(ifname, ifname_size, dev);
4058 fcntl(fd, F_SETFL, O_NONBLOCK);
4059 return fd;
4061 #elif defined(__sun__)
4062 #define TUNNEWPPA (('T'<<16) | 0x0001)
4064 * Allocate TAP device, returns opened fd.
4065 * Stores dev name in the first arg(must be large enough).
4067 int tap_alloc(char *dev)
4069 int tap_fd, if_fd, ppa = -1;
4070 static int ip_fd = 0;
4071 char *ptr;
4073 static int arp_fd = 0;
4074 int ip_muxid, arp_muxid;
4075 struct strioctl strioc_if, strioc_ppa;
4076 int link_type = I_PLINK;;
4077 struct lifreq ifr;
4078 char actual_name[32] = "";
4080 memset(&ifr, 0x0, sizeof(ifr));
4082 if( *dev ){
4083 ptr = dev;
4084 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4085 ppa = atoi(ptr);
4088 /* Check if IP device was opened */
4089 if( ip_fd )
4090 close(ip_fd);
4092 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4093 if (ip_fd < 0) {
4094 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4095 return -1;
4098 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4099 if (tap_fd < 0) {
4100 syslog(LOG_ERR, "Can't open /dev/tap");
4101 return -1;
4104 /* Assign a new PPA and get its unit number. */
4105 strioc_ppa.ic_cmd = TUNNEWPPA;
4106 strioc_ppa.ic_timout = 0;
4107 strioc_ppa.ic_len = sizeof(ppa);
4108 strioc_ppa.ic_dp = (char *)&ppa;
4109 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4110 syslog (LOG_ERR, "Can't assign new interface");
4112 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4113 if (if_fd < 0) {
4114 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4115 return -1;
4117 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4118 syslog(LOG_ERR, "Can't push IP module");
4119 return -1;
4122 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4123 syslog(LOG_ERR, "Can't get flags\n");
4125 snprintf (actual_name, 32, "tap%d", ppa);
4126 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4128 ifr.lifr_ppa = ppa;
4129 /* Assign ppa according to the unit number returned by tun device */
4131 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4132 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4133 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4134 syslog (LOG_ERR, "Can't get flags\n");
4135 /* Push arp module to if_fd */
4136 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4137 syslog (LOG_ERR, "Can't push ARP module (2)");
4139 /* Push arp module to ip_fd */
4140 if (ioctl (ip_fd, I_POP, NULL) < 0)
4141 syslog (LOG_ERR, "I_POP failed\n");
4142 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4143 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4144 /* Open arp_fd */
4145 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4146 if (arp_fd < 0)
4147 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4149 /* Set ifname to arp */
4150 strioc_if.ic_cmd = SIOCSLIFNAME;
4151 strioc_if.ic_timout = 0;
4152 strioc_if.ic_len = sizeof(ifr);
4153 strioc_if.ic_dp = (char *)&ifr;
4154 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4155 syslog (LOG_ERR, "Can't set ifname to arp\n");
4158 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4159 syslog(LOG_ERR, "Can't link TAP device to IP");
4160 return -1;
4163 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4164 syslog (LOG_ERR, "Can't link TAP device to ARP");
4166 close (if_fd);
4168 memset(&ifr, 0x0, sizeof(ifr));
4169 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4170 ifr.lifr_ip_muxid = ip_muxid;
4171 ifr.lifr_arp_muxid = arp_muxid;
4173 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4175 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4176 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4177 syslog (LOG_ERR, "Can't set multiplexor id");
4180 sprintf(dev, "tap%d", ppa);
4181 return tap_fd;
4184 static int tap_open(char *ifname, int ifname_size)
4186 char dev[10]="";
4187 int fd;
4188 if( (fd = tap_alloc(dev)) < 0 ){
4189 fprintf(stderr, "Cannot allocate TAP device\n");
4190 return -1;
4192 pstrcpy(ifname, ifname_size, dev);
4193 fcntl(fd, F_SETFL, O_NONBLOCK);
4194 return fd;
4196 #else
4197 static int tap_open(char *ifname, int ifname_size)
4199 struct ifreq ifr;
4200 int fd, ret;
4202 TFR(fd = open("/dev/net/tun", O_RDWR));
4203 if (fd < 0) {
4204 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4205 return -1;
4207 memset(&ifr, 0, sizeof(ifr));
4208 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4209 if (ifname[0] != '\0')
4210 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4211 else
4212 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4213 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4214 if (ret != 0) {
4215 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4216 close(fd);
4217 return -1;
4219 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4220 fcntl(fd, F_SETFL, O_NONBLOCK);
4221 return fd;
4223 #endif
4225 static int launch_script(const char *setup_script, const char *ifname, int fd)
4227 int pid, status;
4228 char *args[3];
4229 char **parg;
4231 /* try to launch network script */
4232 pid = fork();
4233 if (pid >= 0) {
4234 if (pid == 0) {
4235 int open_max = sysconf (_SC_OPEN_MAX), i;
4236 for (i = 0; i < open_max; i++)
4237 if (i != STDIN_FILENO &&
4238 i != STDOUT_FILENO &&
4239 i != STDERR_FILENO &&
4240 i != fd)
4241 close(i);
4243 parg = args;
4244 *parg++ = (char *)setup_script;
4245 *parg++ = (char *)ifname;
4246 *parg++ = NULL;
4247 execv(setup_script, args);
4248 _exit(1);
4250 while (waitpid(pid, &status, 0) != pid);
4251 if (!WIFEXITED(status) ||
4252 WEXITSTATUS(status) != 0) {
4253 fprintf(stderr, "%s: could not launch network script\n",
4254 setup_script);
4255 return -1;
4258 return 0;
4261 static int net_tap_init(VLANState *vlan, const char *ifname1,
4262 const char *setup_script, const char *down_script)
4264 TAPState *s;
4265 int fd;
4266 char ifname[128];
4268 if (ifname1 != NULL)
4269 pstrcpy(ifname, sizeof(ifname), ifname1);
4270 else
4271 ifname[0] = '\0';
4272 TFR(fd = tap_open(ifname, sizeof(ifname)));
4273 if (fd < 0)
4274 return -1;
4276 if (!setup_script || !strcmp(setup_script, "no"))
4277 setup_script = "";
4278 if (setup_script[0] != '\0') {
4279 if (launch_script(setup_script, ifname, fd))
4280 return -1;
4282 s = net_tap_fd_init(vlan, fd);
4283 if (!s)
4284 return -1;
4285 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4286 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4287 if (down_script && strcmp(down_script, "no"))
4288 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4289 return 0;
4292 #endif /* !_WIN32 */
4294 /* network connection */
4295 typedef struct NetSocketState {
4296 VLANClientState *vc;
4297 int fd;
4298 int state; /* 0 = getting length, 1 = getting data */
4299 int index;
4300 int packet_len;
4301 uint8_t buf[4096];
4302 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4303 } NetSocketState;
4305 typedef struct NetSocketListenState {
4306 VLANState *vlan;
4307 int fd;
4308 } NetSocketListenState;
4310 /* XXX: we consider we can send the whole packet without blocking */
4311 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4313 NetSocketState *s = opaque;
4314 uint32_t len;
4315 len = htonl(size);
4317 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4318 send_all(s->fd, buf, size);
4321 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4323 NetSocketState *s = opaque;
4324 sendto(s->fd, buf, size, 0,
4325 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4328 static void net_socket_send(void *opaque)
4330 NetSocketState *s = opaque;
4331 int l, size, err;
4332 uint8_t buf1[4096];
4333 const uint8_t *buf;
4335 size = recv(s->fd, buf1, sizeof(buf1), 0);
4336 if (size < 0) {
4337 err = socket_error();
4338 if (err != EWOULDBLOCK)
4339 goto eoc;
4340 } else if (size == 0) {
4341 /* end of connection */
4342 eoc:
4343 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4344 closesocket(s->fd);
4345 return;
4347 buf = buf1;
4348 while (size > 0) {
4349 /* reassemble a packet from the network */
4350 switch(s->state) {
4351 case 0:
4352 l = 4 - s->index;
4353 if (l > size)
4354 l = size;
4355 memcpy(s->buf + s->index, buf, l);
4356 buf += l;
4357 size -= l;
4358 s->index += l;
4359 if (s->index == 4) {
4360 /* got length */
4361 s->packet_len = ntohl(*(uint32_t *)s->buf);
4362 s->index = 0;
4363 s->state = 1;
4365 break;
4366 case 1:
4367 l = s->packet_len - s->index;
4368 if (l > size)
4369 l = size;
4370 memcpy(s->buf + s->index, buf, l);
4371 s->index += l;
4372 buf += l;
4373 size -= l;
4374 if (s->index >= s->packet_len) {
4375 qemu_send_packet(s->vc, s->buf, s->packet_len);
4376 s->index = 0;
4377 s->state = 0;
4379 break;
4384 static void net_socket_send_dgram(void *opaque)
4386 NetSocketState *s = opaque;
4387 int size;
4389 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4390 if (size < 0)
4391 return;
4392 if (size == 0) {
4393 /* end of connection */
4394 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4395 return;
4397 qemu_send_packet(s->vc, s->buf, size);
4400 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4402 struct ip_mreq imr;
4403 int fd;
4404 int val, ret;
4405 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4406 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4407 inet_ntoa(mcastaddr->sin_addr),
4408 (int)ntohl(mcastaddr->sin_addr.s_addr));
4409 return -1;
4412 fd = socket(PF_INET, SOCK_DGRAM, 0);
4413 if (fd < 0) {
4414 perror("socket(PF_INET, SOCK_DGRAM)");
4415 return -1;
4418 val = 1;
4419 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4420 (const char *)&val, sizeof(val));
4421 if (ret < 0) {
4422 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4423 goto fail;
4426 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4427 if (ret < 0) {
4428 perror("bind");
4429 goto fail;
4432 /* Add host to multicast group */
4433 imr.imr_multiaddr = mcastaddr->sin_addr;
4434 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4436 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4437 (const char *)&imr, sizeof(struct ip_mreq));
4438 if (ret < 0) {
4439 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4440 goto fail;
4443 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4444 val = 1;
4445 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4446 (const char *)&val, sizeof(val));
4447 if (ret < 0) {
4448 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4449 goto fail;
4452 socket_set_nonblock(fd);
4453 return fd;
4454 fail:
4455 if (fd >= 0)
4456 closesocket(fd);
4457 return -1;
4460 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4461 int is_connected)
4463 struct sockaddr_in saddr;
4464 int newfd;
4465 socklen_t saddr_len;
4466 NetSocketState *s;
4468 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4469 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4470 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4473 if (is_connected) {
4474 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4475 /* must be bound */
4476 if (saddr.sin_addr.s_addr==0) {
4477 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4478 fd);
4479 return NULL;
4481 /* clone dgram socket */
4482 newfd = net_socket_mcast_create(&saddr);
4483 if (newfd < 0) {
4484 /* error already reported by net_socket_mcast_create() */
4485 close(fd);
4486 return NULL;
4488 /* clone newfd to fd, close newfd */
4489 dup2(newfd, fd);
4490 close(newfd);
4492 } else {
4493 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4494 fd, strerror(errno));
4495 return NULL;
4499 s = qemu_mallocz(sizeof(NetSocketState));
4500 if (!s)
4501 return NULL;
4502 s->fd = fd;
4504 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4505 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4507 /* mcast: save bound address as dst */
4508 if (is_connected) s->dgram_dst=saddr;
4510 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4511 "socket: fd=%d (%s mcast=%s:%d)",
4512 fd, is_connected? "cloned" : "",
4513 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4514 return s;
4517 static void net_socket_connect(void *opaque)
4519 NetSocketState *s = opaque;
4520 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4523 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4524 int is_connected)
4526 NetSocketState *s;
4527 s = qemu_mallocz(sizeof(NetSocketState));
4528 if (!s)
4529 return NULL;
4530 s->fd = fd;
4531 s->vc = qemu_new_vlan_client(vlan,
4532 net_socket_receive, NULL, s);
4533 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4534 "socket: fd=%d", fd);
4535 if (is_connected) {
4536 net_socket_connect(s);
4537 } else {
4538 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4540 return s;
4543 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4544 int is_connected)
4546 int so_type=-1, optlen=sizeof(so_type);
4548 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4549 (socklen_t *)&optlen)< 0) {
4550 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4551 return NULL;
4553 switch(so_type) {
4554 case SOCK_DGRAM:
4555 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4556 case SOCK_STREAM:
4557 return net_socket_fd_init_stream(vlan, fd, is_connected);
4558 default:
4559 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4560 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4561 return net_socket_fd_init_stream(vlan, fd, is_connected);
4563 return NULL;
4566 static void net_socket_accept(void *opaque)
4568 NetSocketListenState *s = opaque;
4569 NetSocketState *s1;
4570 struct sockaddr_in saddr;
4571 socklen_t len;
4572 int fd;
4574 for(;;) {
4575 len = sizeof(saddr);
4576 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4577 if (fd < 0 && errno != EINTR) {
4578 return;
4579 } else if (fd >= 0) {
4580 break;
4583 s1 = net_socket_fd_init(s->vlan, fd, 1);
4584 if (!s1) {
4585 closesocket(fd);
4586 } else {
4587 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4588 "socket: connection from %s:%d",
4589 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4593 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4595 NetSocketListenState *s;
4596 int fd, val, ret;
4597 struct sockaddr_in saddr;
4599 if (parse_host_port(&saddr, host_str) < 0)
4600 return -1;
4602 s = qemu_mallocz(sizeof(NetSocketListenState));
4603 if (!s)
4604 return -1;
4606 fd = socket(PF_INET, SOCK_STREAM, 0);
4607 if (fd < 0) {
4608 perror("socket");
4609 return -1;
4611 socket_set_nonblock(fd);
4613 /* allow fast reuse */
4614 val = 1;
4615 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4617 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4618 if (ret < 0) {
4619 perror("bind");
4620 return -1;
4622 ret = listen(fd, 0);
4623 if (ret < 0) {
4624 perror("listen");
4625 return -1;
4627 s->vlan = vlan;
4628 s->fd = fd;
4629 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4630 return 0;
4633 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4635 NetSocketState *s;
4636 int fd, connected, ret, err;
4637 struct sockaddr_in saddr;
4639 if (parse_host_port(&saddr, host_str) < 0)
4640 return -1;
4642 fd = socket(PF_INET, SOCK_STREAM, 0);
4643 if (fd < 0) {
4644 perror("socket");
4645 return -1;
4647 socket_set_nonblock(fd);
4649 connected = 0;
4650 for(;;) {
4651 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4652 if (ret < 0) {
4653 err = socket_error();
4654 if (err == EINTR || err == EWOULDBLOCK) {
4655 } else if (err == EINPROGRESS) {
4656 break;
4657 #ifdef _WIN32
4658 } else if (err == WSAEALREADY) {
4659 break;
4660 #endif
4661 } else {
4662 perror("connect");
4663 closesocket(fd);
4664 return -1;
4666 } else {
4667 connected = 1;
4668 break;
4671 s = net_socket_fd_init(vlan, fd, connected);
4672 if (!s)
4673 return -1;
4674 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4675 "socket: connect to %s:%d",
4676 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4677 return 0;
4680 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4682 NetSocketState *s;
4683 int fd;
4684 struct sockaddr_in saddr;
4686 if (parse_host_port(&saddr, host_str) < 0)
4687 return -1;
4690 fd = net_socket_mcast_create(&saddr);
4691 if (fd < 0)
4692 return -1;
4694 s = net_socket_fd_init(vlan, fd, 0);
4695 if (!s)
4696 return -1;
4698 s->dgram_dst = saddr;
4700 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4701 "socket: mcast=%s:%d",
4702 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4703 return 0;
4707 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4709 char *q;
4711 q = buf;
4712 while (*p != '\0' && *p != '=') {
4713 if (q && (q - buf) < buf_size - 1)
4714 *q++ = *p;
4715 p++;
4717 if (q)
4718 *q = '\0';
4720 return p;
4723 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4725 char *q;
4727 q = buf;
4728 while (*p != '\0') {
4729 if (*p == ',') {
4730 if (*(p + 1) != ',')
4731 break;
4732 p++;
4734 if (q && (q - buf) < buf_size - 1)
4735 *q++ = *p;
4736 p++;
4738 if (q)
4739 *q = '\0';
4741 return p;
4744 static int get_param_value(char *buf, int buf_size,
4745 const char *tag, const char *str)
4747 const char *p;
4748 char option[128];
4750 p = str;
4751 for(;;) {
4752 p = get_opt_name(option, sizeof(option), p);
4753 if (*p != '=')
4754 break;
4755 p++;
4756 if (!strcmp(tag, option)) {
4757 (void)get_opt_value(buf, buf_size, p);
4758 return strlen(buf);
4759 } else {
4760 p = get_opt_value(NULL, 0, p);
4762 if (*p != ',')
4763 break;
4764 p++;
4766 return 0;
4769 static int check_params(char *buf, int buf_size,
4770 char **params, const char *str)
4772 const char *p;
4773 int i;
4775 p = str;
4776 for(;;) {
4777 p = get_opt_name(buf, buf_size, p);
4778 if (*p != '=')
4779 return -1;
4780 p++;
4781 for(i = 0; params[i] != NULL; i++)
4782 if (!strcmp(params[i], buf))
4783 break;
4784 if (params[i] == NULL)
4785 return -1;
4786 p = get_opt_value(NULL, 0, p);
4787 if (*p != ',')
4788 break;
4789 p++;
4791 return 0;
4795 static int net_client_init(const char *str)
4797 const char *p;
4798 char *q;
4799 char device[64];
4800 char buf[1024];
4801 int vlan_id, ret;
4802 VLANState *vlan;
4804 p = str;
4805 q = device;
4806 while (*p != '\0' && *p != ',') {
4807 if ((q - device) < sizeof(device) - 1)
4808 *q++ = *p;
4809 p++;
4811 *q = '\0';
4812 if (*p == ',')
4813 p++;
4814 vlan_id = 0;
4815 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4816 vlan_id = strtol(buf, NULL, 0);
4818 vlan = qemu_find_vlan(vlan_id);
4819 if (!vlan) {
4820 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4821 return -1;
4823 if (!strcmp(device, "nic")) {
4824 NICInfo *nd;
4825 uint8_t *macaddr;
4827 if (nb_nics >= MAX_NICS) {
4828 fprintf(stderr, "Too Many NICs\n");
4829 return -1;
4831 nd = &nd_table[nb_nics];
4832 macaddr = nd->macaddr;
4833 macaddr[0] = 0x52;
4834 macaddr[1] = 0x54;
4835 macaddr[2] = 0x00;
4836 macaddr[3] = 0x12;
4837 macaddr[4] = 0x34;
4838 macaddr[5] = 0x56 + nb_nics;
4840 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4841 if (parse_macaddr(macaddr, buf) < 0) {
4842 fprintf(stderr, "invalid syntax for ethernet address\n");
4843 return -1;
4846 if (get_param_value(buf, sizeof(buf), "model", p)) {
4847 nd->model = strdup(buf);
4849 nd->vlan = vlan;
4850 nb_nics++;
4851 vlan->nb_guest_devs++;
4852 ret = 0;
4853 } else
4854 if (!strcmp(device, "none")) {
4855 /* does nothing. It is needed to signal that no network cards
4856 are wanted */
4857 ret = 0;
4858 } else
4859 #ifdef CONFIG_SLIRP
4860 if (!strcmp(device, "user")) {
4861 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4862 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4864 vlan->nb_host_devs++;
4865 ret = net_slirp_init(vlan);
4866 } else
4867 #endif
4868 #ifdef _WIN32
4869 if (!strcmp(device, "tap")) {
4870 char ifname[64];
4871 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4872 fprintf(stderr, "tap: no interface name\n");
4873 return -1;
4875 vlan->nb_host_devs++;
4876 ret = tap_win32_init(vlan, ifname);
4877 } else
4878 #else
4879 if (!strcmp(device, "tap")) {
4880 char ifname[64];
4881 char setup_script[1024], down_script[1024];
4882 int fd;
4883 vlan->nb_host_devs++;
4884 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4885 fd = strtol(buf, NULL, 0);
4886 ret = -1;
4887 if (net_tap_fd_init(vlan, fd))
4888 ret = 0;
4889 } else {
4890 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4891 ifname[0] = '\0';
4893 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4894 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4896 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4897 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4899 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4901 } else
4902 #endif
4903 if (!strcmp(device, "socket")) {
4904 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4905 int fd;
4906 fd = strtol(buf, NULL, 0);
4907 ret = -1;
4908 if (net_socket_fd_init(vlan, fd, 1))
4909 ret = 0;
4910 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4911 ret = net_socket_listen_init(vlan, buf);
4912 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4913 ret = net_socket_connect_init(vlan, buf);
4914 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4915 ret = net_socket_mcast_init(vlan, buf);
4916 } else {
4917 fprintf(stderr, "Unknown socket options: %s\n", p);
4918 return -1;
4920 vlan->nb_host_devs++;
4921 } else
4923 fprintf(stderr, "Unknown network device: %s\n", device);
4924 return -1;
4926 if (ret < 0) {
4927 fprintf(stderr, "Could not initialize device '%s'\n", device);
4930 return ret;
4933 void do_info_network(void)
4935 VLANState *vlan;
4936 VLANClientState *vc;
4938 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4939 term_printf("VLAN %d devices:\n", vlan->id);
4940 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4941 term_printf(" %s\n", vc->info_str);
4945 #define HD_ALIAS "index=%d,media=disk"
4946 #ifdef TARGET_PPC
4947 #define CDROM_ALIAS "index=1,media=cdrom"
4948 #else
4949 #define CDROM_ALIAS "index=2,media=cdrom"
4950 #endif
4951 #define FD_ALIAS "index=%d,if=floppy"
4952 #define PFLASH_ALIAS "if=pflash"
4953 #define MTD_ALIAS "if=mtd"
4954 #define SD_ALIAS "index=0,if=sd"
4956 static int drive_opt_get_free_idx(void)
4958 int index;
4960 for (index = 0; index < MAX_DRIVES; index++)
4961 if (!drives_opt[index].used) {
4962 drives_opt[index].used = 1;
4963 return index;
4966 return -1;
4969 static int drive_get_free_idx(void)
4971 int index;
4973 for (index = 0; index < MAX_DRIVES; index++)
4974 if (!drives_table[index].used) {
4975 drives_table[index].used = 1;
4976 return index;
4979 return -1;
4982 static int drive_add(const char *file, const char *fmt, ...)
4984 va_list ap;
4985 int index = drive_opt_get_free_idx();
4987 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
4988 fprintf(stderr, "qemu: too many drives\n");
4989 exit(1);
4992 drives_opt[index].file = file;
4993 va_start(ap, fmt);
4994 vsnprintf(drives_opt[index].opt,
4995 sizeof(drives_opt[0].opt), fmt, ap);
4996 va_end(ap);
4998 nb_drives_opt++;
4999 return index;
5002 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5004 int index;
5006 /* seek interface, bus and unit */
5008 for (index = 0; index < MAX_DRIVES; index++)
5009 if (drives_table[index].type == type &&
5010 drives_table[index].bus == bus &&
5011 drives_table[index].unit == unit &&
5012 drives_table[index].used)
5013 return index;
5015 return -1;
5018 int drive_get_max_bus(BlockInterfaceType type)
5020 int max_bus;
5021 int index;
5023 max_bus = -1;
5024 for (index = 0; index < nb_drives; index++) {
5025 if(drives_table[index].type == type &&
5026 drives_table[index].bus > max_bus)
5027 max_bus = drives_table[index].bus;
5029 return max_bus;
5032 static int drive_init(struct drive_opt *arg, int snapshot,
5033 QEMUMachine *machine)
5035 char buf[128];
5036 char file[1024];
5037 char devname[128];
5038 const char *mediastr = "";
5039 BlockInterfaceType type;
5040 enum { MEDIA_DISK, MEDIA_CDROM } media;
5041 int bus_id, unit_id;
5042 int cyls, heads, secs, translation;
5043 BlockDriverState *bdrv;
5044 int max_devs;
5045 int index;
5046 int cache;
5047 int bdrv_flags;
5048 int drives_table_idx;
5049 char *str = arg->opt;
5050 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5051 "secs", "trans", "media", "snapshot", "file",
5052 "cache", "boot", NULL };
5054 if (check_params(buf, sizeof(buf), params, str) < 0) {
5055 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5056 buf, str);
5057 return -1;
5060 file[0] = 0;
5061 cyls = heads = secs = 0;
5062 bus_id = 0;
5063 unit_id = -1;
5064 translation = BIOS_ATA_TRANSLATION_AUTO;
5065 index = -1;
5066 cache = 1;
5068 if (!strcmp(machine->name, "realview") ||
5069 !strcmp(machine->name, "SS-5") ||
5070 !strcmp(machine->name, "SS-10") ||
5071 !strcmp(machine->name, "SS-600MP") ||
5072 !strcmp(machine->name, "versatilepb") ||
5073 !strcmp(machine->name, "versatileab")) {
5074 type = IF_SCSI;
5075 max_devs = MAX_SCSI_DEVS;
5076 strcpy(devname, "scsi");
5077 } else {
5078 type = IF_IDE;
5079 max_devs = MAX_IDE_DEVS;
5080 strcpy(devname, "ide");
5082 media = MEDIA_DISK;
5084 /* extract parameters */
5086 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5087 bus_id = strtol(buf, NULL, 0);
5088 if (bus_id < 0) {
5089 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5090 return -1;
5094 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5095 unit_id = strtol(buf, NULL, 0);
5096 if (unit_id < 0) {
5097 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5098 return -1;
5102 if (get_param_value(buf, sizeof(buf), "if", str)) {
5103 strncpy(devname, buf, sizeof(devname));
5104 if (!strcmp(buf, "ide")) {
5105 type = IF_IDE;
5106 max_devs = MAX_IDE_DEVS;
5107 } else if (!strcmp(buf, "scsi")) {
5108 type = IF_SCSI;
5109 max_devs = MAX_SCSI_DEVS;
5110 } else if (!strcmp(buf, "floppy")) {
5111 type = IF_FLOPPY;
5112 max_devs = 0;
5113 } else if (!strcmp(buf, "pflash")) {
5114 type = IF_PFLASH;
5115 max_devs = 0;
5116 } else if (!strcmp(buf, "mtd")) {
5117 type = IF_MTD;
5118 max_devs = 0;
5119 } else if (!strcmp(buf, "sd")) {
5120 type = IF_SD;
5121 max_devs = 0;
5122 } else if (!strcmp(buf, "virtio")) {
5123 type = IF_VIRTIO;
5124 max_devs = 0;
5125 } else {
5126 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5127 return -1;
5131 if (get_param_value(buf, sizeof(buf), "index", str)) {
5132 index = strtol(buf, NULL, 0);
5133 if (index < 0) {
5134 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5135 return -1;
5139 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5140 cyls = strtol(buf, NULL, 0);
5143 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5144 heads = strtol(buf, NULL, 0);
5147 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5148 secs = strtol(buf, NULL, 0);
5151 if (cyls || heads || secs) {
5152 if (cyls < 1 || cyls > 16383) {
5153 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5154 return -1;
5156 if (heads < 1 || heads > 16) {
5157 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5158 return -1;
5160 if (secs < 1 || secs > 63) {
5161 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5162 return -1;
5166 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5167 if (!cyls) {
5168 fprintf(stderr,
5169 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5170 str);
5171 return -1;
5173 if (!strcmp(buf, "none"))
5174 translation = BIOS_ATA_TRANSLATION_NONE;
5175 else if (!strcmp(buf, "lba"))
5176 translation = BIOS_ATA_TRANSLATION_LBA;
5177 else if (!strcmp(buf, "auto"))
5178 translation = BIOS_ATA_TRANSLATION_AUTO;
5179 else {
5180 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5181 return -1;
5185 if (get_param_value(buf, sizeof(buf), "media", str)) {
5186 if (!strcmp(buf, "disk")) {
5187 media = MEDIA_DISK;
5188 } else if (!strcmp(buf, "cdrom")) {
5189 if (cyls || secs || heads) {
5190 fprintf(stderr,
5191 "qemu: '%s' invalid physical CHS format\n", str);
5192 return -1;
5194 media = MEDIA_CDROM;
5195 } else {
5196 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5197 return -1;
5201 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5202 if (!strcmp(buf, "on"))
5203 snapshot = 1;
5204 else if (!strcmp(buf, "off"))
5205 snapshot = 0;
5206 else {
5207 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5208 return -1;
5212 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5213 if (!strcmp(buf, "off"))
5214 cache = 0;
5215 else if (!strcmp(buf, "on"))
5216 cache = 1;
5217 else {
5218 fprintf(stderr, "qemu: invalid cache option\n");
5219 return -1;
5223 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5224 if (!strcmp(buf, "on")) {
5225 if (extboot_drive != -1) {
5226 fprintf(stderr, "qemu: two bootable drives specified\n");
5227 return -1;
5229 extboot_drive = nb_drives;
5230 } else if (strcmp(buf, "off")) {
5231 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5232 return -1;
5236 if (arg->file == NULL)
5237 get_param_value(file, sizeof(file), "file", str);
5238 else
5239 pstrcpy(file, sizeof(file), arg->file);
5241 /* compute bus and unit according index */
5243 if (index != -1) {
5244 if (bus_id != 0 || unit_id != -1) {
5245 fprintf(stderr,
5246 "qemu: '%s' index cannot be used with bus and unit\n", str);
5247 return -1;
5249 if (max_devs == 0)
5251 unit_id = index;
5252 bus_id = 0;
5253 } else {
5254 unit_id = index % max_devs;
5255 bus_id = index / max_devs;
5259 /* if user doesn't specify a unit_id,
5260 * try to find the first free
5263 if (unit_id == -1) {
5264 unit_id = 0;
5265 while (drive_get_index(type, bus_id, unit_id) != -1) {
5266 unit_id++;
5267 if (max_devs && unit_id >= max_devs) {
5268 unit_id -= max_devs;
5269 bus_id++;
5274 /* check unit id */
5276 if (max_devs && unit_id >= max_devs) {
5277 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5278 str, unit_id, max_devs - 1);
5279 return -1;
5283 * ignore multiple definitions
5286 if (drive_get_index(type, bus_id, unit_id) != -1)
5287 return 0;
5289 /* init */
5291 if (type == IF_IDE || type == IF_SCSI)
5292 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5293 if (max_devs)
5294 snprintf(buf, sizeof(buf), "%s%i%s%i",
5295 devname, bus_id, mediastr, unit_id);
5296 else
5297 snprintf(buf, sizeof(buf), "%s%s%i",
5298 devname, mediastr, unit_id);
5299 bdrv = bdrv_new(buf);
5300 drives_table_idx = drive_get_free_idx();
5301 drives_table[drives_table_idx].bdrv = bdrv;
5302 drives_table[drives_table_idx].type = type;
5303 drives_table[drives_table_idx].bus = bus_id;
5304 drives_table[drives_table_idx].unit = unit_id;
5305 nb_drives++;
5307 switch(type) {
5308 case IF_IDE:
5309 case IF_SCSI:
5310 switch(media) {
5311 case MEDIA_DISK:
5312 if (cyls != 0) {
5313 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5314 bdrv_set_translation_hint(bdrv, translation);
5316 break;
5317 case MEDIA_CDROM:
5318 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5319 break;
5321 break;
5322 case IF_SD:
5323 /* FIXME: This isn't really a floppy, but it's a reasonable
5324 approximation. */
5325 case IF_FLOPPY:
5326 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5327 break;
5328 case IF_PFLASH:
5329 case IF_MTD:
5330 case IF_VIRTIO:
5331 break;
5333 if (!file[0])
5334 return 0;
5335 bdrv_flags = 0;
5336 if (snapshot)
5337 bdrv_flags |= BDRV_O_SNAPSHOT;
5338 if (!cache)
5339 bdrv_flags |= BDRV_O_DIRECT;
5340 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5341 fprintf(stderr, "qemu: could not open disk image %s\n",
5342 file);
5343 return -1;
5345 return 0;
5348 /***********************************************************/
5349 /* USB devices */
5351 static USBPort *used_usb_ports;
5352 static USBPort *free_usb_ports;
5354 /* ??? Maybe change this to register a hub to keep track of the topology. */
5355 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5356 usb_attachfn attach)
5358 port->opaque = opaque;
5359 port->index = index;
5360 port->attach = attach;
5361 port->next = free_usb_ports;
5362 free_usb_ports = port;
5365 static int usb_device_add(const char *devname)
5367 const char *p;
5368 USBDevice *dev;
5369 USBPort *port;
5371 if (!free_usb_ports)
5372 return -1;
5374 if (strstart(devname, "host:", &p)) {
5375 dev = usb_host_device_open(p);
5376 } else if (!strcmp(devname, "mouse")) {
5377 dev = usb_mouse_init();
5378 } else if (!strcmp(devname, "tablet")) {
5379 dev = usb_tablet_init();
5380 } else if (!strcmp(devname, "keyboard")) {
5381 dev = usb_keyboard_init();
5382 } else if (strstart(devname, "disk:", &p)) {
5383 dev = usb_msd_init(p);
5384 } else if (!strcmp(devname, "wacom-tablet")) {
5385 dev = usb_wacom_init();
5386 } else if (strstart(devname, "serial:", &p)) {
5387 dev = usb_serial_init(p);
5388 } else {
5389 return -1;
5391 if (!dev)
5392 return -1;
5394 /* Find a USB port to add the device to. */
5395 port = free_usb_ports;
5396 if (!port->next) {
5397 USBDevice *hub;
5399 /* Create a new hub and chain it on. */
5400 free_usb_ports = NULL;
5401 port->next = used_usb_ports;
5402 used_usb_ports = port;
5404 hub = usb_hub_init(VM_USB_HUB_SIZE);
5405 usb_attach(port, hub);
5406 port = free_usb_ports;
5409 free_usb_ports = port->next;
5410 port->next = used_usb_ports;
5411 used_usb_ports = port;
5412 usb_attach(port, dev);
5413 return 0;
5416 static int usb_device_del(const char *devname)
5418 USBPort *port;
5419 USBPort **lastp;
5420 USBDevice *dev;
5421 int bus_num, addr;
5422 const char *p;
5424 if (!used_usb_ports)
5425 return -1;
5427 p = strchr(devname, '.');
5428 if (!p)
5429 return -1;
5430 bus_num = strtoul(devname, NULL, 0);
5431 addr = strtoul(p + 1, NULL, 0);
5432 if (bus_num != 0)
5433 return -1;
5435 lastp = &used_usb_ports;
5436 port = used_usb_ports;
5437 while (port && port->dev->addr != addr) {
5438 lastp = &port->next;
5439 port = port->next;
5442 if (!port)
5443 return -1;
5445 dev = port->dev;
5446 *lastp = port->next;
5447 usb_attach(port, NULL);
5448 dev->handle_destroy(dev);
5449 port->next = free_usb_ports;
5450 free_usb_ports = port;
5451 return 0;
5454 void do_usb_add(const char *devname)
5456 int ret;
5457 ret = usb_device_add(devname);
5458 if (ret < 0)
5459 term_printf("Could not add USB device '%s'\n", devname);
5462 void do_usb_del(const char *devname)
5464 int ret;
5465 ret = usb_device_del(devname);
5466 if (ret < 0)
5467 term_printf("Could not remove USB device '%s'\n", devname);
5470 void usb_info(void)
5472 USBDevice *dev;
5473 USBPort *port;
5474 const char *speed_str;
5476 if (!usb_enabled) {
5477 term_printf("USB support not enabled\n");
5478 return;
5481 for (port = used_usb_ports; port; port = port->next) {
5482 dev = port->dev;
5483 if (!dev)
5484 continue;
5485 switch(dev->speed) {
5486 case USB_SPEED_LOW:
5487 speed_str = "1.5";
5488 break;
5489 case USB_SPEED_FULL:
5490 speed_str = "12";
5491 break;
5492 case USB_SPEED_HIGH:
5493 speed_str = "480";
5494 break;
5495 default:
5496 speed_str = "?";
5497 break;
5499 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5500 0, dev->addr, speed_str, dev->devname);
5504 /***********************************************************/
5505 /* PCMCIA/Cardbus */
5507 static struct pcmcia_socket_entry_s {
5508 struct pcmcia_socket_s *socket;
5509 struct pcmcia_socket_entry_s *next;
5510 } *pcmcia_sockets = 0;
5512 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5514 struct pcmcia_socket_entry_s *entry;
5516 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5517 entry->socket = socket;
5518 entry->next = pcmcia_sockets;
5519 pcmcia_sockets = entry;
5522 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5524 struct pcmcia_socket_entry_s *entry, **ptr;
5526 ptr = &pcmcia_sockets;
5527 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5528 if (entry->socket == socket) {
5529 *ptr = entry->next;
5530 qemu_free(entry);
5534 void pcmcia_info(void)
5536 struct pcmcia_socket_entry_s *iter;
5537 if (!pcmcia_sockets)
5538 term_printf("No PCMCIA sockets\n");
5540 for (iter = pcmcia_sockets; iter; iter = iter->next)
5541 term_printf("%s: %s\n", iter->socket->slot_string,
5542 iter->socket->attached ? iter->socket->card_string :
5543 "Empty");
5546 /***********************************************************/
5547 /* dumb display */
5549 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5553 static void dumb_resize(DisplayState *ds, int w, int h)
5557 static void dumb_refresh(DisplayState *ds)
5559 #if defined(CONFIG_SDL)
5560 vga_hw_update();
5561 #endif
5564 static void dumb_display_init(DisplayState *ds)
5566 ds->data = NULL;
5567 ds->linesize = 0;
5568 ds->depth = 0;
5569 ds->dpy_update = dumb_update;
5570 ds->dpy_resize = dumb_resize;
5571 ds->dpy_refresh = dumb_refresh;
5574 /***********************************************************/
5575 /* I/O handling */
5577 #define MAX_IO_HANDLERS 64
5579 typedef struct IOHandlerRecord {
5580 int fd;
5581 IOCanRWHandler *fd_read_poll;
5582 IOHandler *fd_read;
5583 IOHandler *fd_write;
5584 int deleted;
5585 void *opaque;
5586 /* temporary data */
5587 struct pollfd *ufd;
5588 struct IOHandlerRecord *next;
5589 } IOHandlerRecord;
5591 static IOHandlerRecord *first_io_handler;
5593 /* XXX: fd_read_poll should be suppressed, but an API change is
5594 necessary in the character devices to suppress fd_can_read(). */
5595 int qemu_set_fd_handler2(int fd,
5596 IOCanRWHandler *fd_read_poll,
5597 IOHandler *fd_read,
5598 IOHandler *fd_write,
5599 void *opaque)
5601 IOHandlerRecord **pioh, *ioh;
5603 if (!fd_read && !fd_write) {
5604 pioh = &first_io_handler;
5605 for(;;) {
5606 ioh = *pioh;
5607 if (ioh == NULL)
5608 break;
5609 if (ioh->fd == fd) {
5610 ioh->deleted = 1;
5611 break;
5613 pioh = &ioh->next;
5615 } else {
5616 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5617 if (ioh->fd == fd)
5618 goto found;
5620 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5621 if (!ioh)
5622 return -1;
5623 ioh->next = first_io_handler;
5624 first_io_handler = ioh;
5625 found:
5626 ioh->fd = fd;
5627 ioh->fd_read_poll = fd_read_poll;
5628 ioh->fd_read = fd_read;
5629 ioh->fd_write = fd_write;
5630 ioh->opaque = opaque;
5631 ioh->deleted = 0;
5633 return 0;
5636 int qemu_set_fd_handler(int fd,
5637 IOHandler *fd_read,
5638 IOHandler *fd_write,
5639 void *opaque)
5641 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5644 /***********************************************************/
5645 /* Polling handling */
5647 typedef struct PollingEntry {
5648 PollingFunc *func;
5649 void *opaque;
5650 struct PollingEntry *next;
5651 } PollingEntry;
5653 static PollingEntry *first_polling_entry;
5655 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5657 PollingEntry **ppe, *pe;
5658 pe = qemu_mallocz(sizeof(PollingEntry));
5659 if (!pe)
5660 return -1;
5661 pe->func = func;
5662 pe->opaque = opaque;
5663 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5664 *ppe = pe;
5665 return 0;
5668 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5670 PollingEntry **ppe, *pe;
5671 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5672 pe = *ppe;
5673 if (pe->func == func && pe->opaque == opaque) {
5674 *ppe = pe->next;
5675 qemu_free(pe);
5676 break;
5681 #ifdef _WIN32
5682 /***********************************************************/
5683 /* Wait objects support */
5684 typedef struct WaitObjects {
5685 int num;
5686 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5687 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5688 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5689 } WaitObjects;
5691 static WaitObjects wait_objects = {0};
5693 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5695 WaitObjects *w = &wait_objects;
5697 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5698 return -1;
5699 w->events[w->num] = handle;
5700 w->func[w->num] = func;
5701 w->opaque[w->num] = opaque;
5702 w->num++;
5703 return 0;
5706 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5708 int i, found;
5709 WaitObjects *w = &wait_objects;
5711 found = 0;
5712 for (i = 0; i < w->num; i++) {
5713 if (w->events[i] == handle)
5714 found = 1;
5715 if (found) {
5716 w->events[i] = w->events[i + 1];
5717 w->func[i] = w->func[i + 1];
5718 w->opaque[i] = w->opaque[i + 1];
5721 if (found)
5722 w->num--;
5724 #endif
5726 #define SELF_ANNOUNCE_ROUNDS 5
5727 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5728 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5729 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5731 static int announce_self_create(uint8_t *buf,
5732 uint8_t *mac_addr)
5734 uint32_t magic = EXPERIMENTAL_MAGIC;
5735 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5737 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5739 memset(buf, 0xff, 6); /* h_dst */
5740 memcpy(buf + 6, mac_addr, 6); /* h_src */
5741 memcpy(buf + 12, &proto, 2); /* h_proto */
5742 memcpy(buf + 14, &magic, 4); /* magic */
5744 return 18; /* len */
5747 static void qemu_announce_self(void)
5749 int i, j, len;
5750 VLANState *vlan;
5751 VLANClientState *vc;
5752 uint8_t buf[256];
5754 for (i = 0; i < nb_nics; i++) {
5755 len = announce_self_create(buf, nd_table[i].macaddr);
5756 vlan = nd_table[i].vlan;
5757 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5758 if (vc->fd_read == tap_receive) /* send only if tap */
5759 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5760 vc->fd_read(vc->opaque, buf, len);
5765 /***********************************************************/
5766 /* savevm/loadvm support */
5768 #define IO_BUF_SIZE 32768
5770 struct QEMUFile {
5771 QEMUFilePutBufferFunc *put_buffer;
5772 QEMUFileGetBufferFunc *get_buffer;
5773 QEMUFileCloseFunc *close;
5774 void *opaque;
5776 int64_t buf_offset; /* start of buffer when writing, end of buffer
5777 when reading */
5778 int buf_index;
5779 int buf_size; /* 0 when writing */
5780 uint8_t buf[IO_BUF_SIZE];
5783 typedef struct QEMUFileFD
5785 int fd;
5786 } QEMUFileFD;
5788 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5790 QEMUFileFD *s = opaque;
5791 int offset = 0;
5792 ssize_t len;
5794 again:
5795 len = read(s->fd, buf + offset, size - offset);
5796 if (len == -1) {
5797 if (errno == EINTR || errno == EAGAIN)
5798 goto again;
5801 return len;
5804 QEMUFile *qemu_fopen_fd(int fd)
5806 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5807 s->fd = fd;
5808 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5811 typedef struct QEMUFileUnix
5813 FILE *outfile;
5814 } QEMUFileUnix;
5816 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5818 QEMUFileUnix *s = opaque;
5819 fseek(s->outfile, pos, SEEK_SET);
5820 fwrite(buf, 1, size, s->outfile);
5823 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5825 QEMUFileUnix *s = opaque;
5826 fseek(s->outfile, pos, SEEK_SET);
5827 return fread(buf, 1, size, s->outfile);
5830 static void file_close(void *opaque)
5832 QEMUFileUnix *s = opaque;
5833 fclose(s->outfile);
5834 qemu_free(s);
5837 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5839 QEMUFileUnix *s;
5841 s = qemu_mallocz(sizeof(QEMUFileUnix));
5842 if (!s)
5843 return NULL;
5845 s->outfile = fopen(filename, mode);
5846 if (!s->outfile)
5847 goto fail;
5849 if (!strcmp(mode, "wb"))
5850 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5851 else if (!strcmp(mode, "rb"))
5852 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5854 fail:
5855 if (s->outfile)
5856 fclose(s->outfile);
5857 qemu_free(s);
5858 return NULL;
5861 typedef struct QEMUFileBdrv
5863 BlockDriverState *bs;
5864 int64_t base_offset;
5865 } QEMUFileBdrv;
5867 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5869 QEMUFileBdrv *s = opaque;
5870 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5873 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5875 QEMUFileBdrv *s = opaque;
5876 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5879 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5881 QEMUFileBdrv *s;
5883 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5884 if (!s)
5885 return NULL;
5887 s->bs = bs;
5888 s->base_offset = offset;
5890 if (is_writable)
5891 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5893 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5896 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5897 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5899 QEMUFile *f;
5901 f = qemu_mallocz(sizeof(QEMUFile));
5902 if (!f)
5903 return NULL;
5905 f->opaque = opaque;
5906 f->put_buffer = put_buffer;
5907 f->get_buffer = get_buffer;
5908 f->close = close;
5910 return f;
5913 void qemu_fflush(QEMUFile *f)
5915 if (!f->put_buffer)
5916 return;
5918 if (f->buf_index > 0) {
5919 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5920 f->buf_offset += f->buf_index;
5921 f->buf_index = 0;
5925 static void qemu_fill_buffer(QEMUFile *f)
5927 int len;
5929 if (!f->get_buffer)
5930 return;
5932 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5933 if (len < 0)
5934 len = 0;
5936 f->buf_index = 0;
5937 f->buf_size = len;
5938 f->buf_offset += len;
5941 void qemu_fclose(QEMUFile *f)
5943 qemu_fflush(f);
5944 if (f->close)
5945 f->close(f->opaque);
5946 qemu_free(f);
5949 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5951 int l;
5952 while (size > 0) {
5953 l = IO_BUF_SIZE - f->buf_index;
5954 if (l > size)
5955 l = size;
5956 memcpy(f->buf + f->buf_index, buf, l);
5957 f->buf_index += l;
5958 buf += l;
5959 size -= l;
5960 if (f->buf_index >= IO_BUF_SIZE)
5961 qemu_fflush(f);
5965 void qemu_put_byte(QEMUFile *f, int v)
5967 f->buf[f->buf_index++] = v;
5968 if (f->buf_index >= IO_BUF_SIZE)
5969 qemu_fflush(f);
5972 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5974 int size, l;
5976 size = size1;
5977 while (size > 0) {
5978 l = f->buf_size - f->buf_index;
5979 if (l == 0) {
5980 qemu_fill_buffer(f);
5981 l = f->buf_size - f->buf_index;
5982 if (l == 0)
5983 break;
5985 if (l > size)
5986 l = size;
5987 memcpy(buf, f->buf + f->buf_index, l);
5988 f->buf_index += l;
5989 buf += l;
5990 size -= l;
5992 return size1 - size;
5995 int qemu_get_byte(QEMUFile *f)
5997 if (f->buf_index >= f->buf_size) {
5998 qemu_fill_buffer(f);
5999 if (f->buf_index >= f->buf_size)
6000 return 0;
6002 return f->buf[f->buf_index++];
6005 int64_t qemu_ftell(QEMUFile *f)
6007 return f->buf_offset - f->buf_size + f->buf_index;
6010 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6012 if (whence == SEEK_SET) {
6013 /* nothing to do */
6014 } else if (whence == SEEK_CUR) {
6015 pos += qemu_ftell(f);
6016 } else {
6017 /* SEEK_END not supported */
6018 return -1;
6020 if (f->put_buffer) {
6021 qemu_fflush(f);
6022 f->buf_offset = pos;
6023 } else {
6024 f->buf_offset = pos;
6025 f->buf_index = 0;
6026 f->buf_size = 0;
6028 return pos;
6031 void qemu_put_be16(QEMUFile *f, unsigned int v)
6033 qemu_put_byte(f, v >> 8);
6034 qemu_put_byte(f, v);
6037 void qemu_put_be32(QEMUFile *f, unsigned int v)
6039 qemu_put_byte(f, v >> 24);
6040 qemu_put_byte(f, v >> 16);
6041 qemu_put_byte(f, v >> 8);
6042 qemu_put_byte(f, v);
6045 void qemu_put_be64(QEMUFile *f, uint64_t v)
6047 qemu_put_be32(f, v >> 32);
6048 qemu_put_be32(f, v);
6051 unsigned int qemu_get_be16(QEMUFile *f)
6053 unsigned int v;
6054 v = qemu_get_byte(f) << 8;
6055 v |= qemu_get_byte(f);
6056 return v;
6059 unsigned int qemu_get_be32(QEMUFile *f)
6061 unsigned int v;
6062 v = qemu_get_byte(f) << 24;
6063 v |= qemu_get_byte(f) << 16;
6064 v |= qemu_get_byte(f) << 8;
6065 v |= qemu_get_byte(f);
6066 return v;
6069 uint64_t qemu_get_be64(QEMUFile *f)
6071 uint64_t v;
6072 v = (uint64_t)qemu_get_be32(f) << 32;
6073 v |= qemu_get_be32(f);
6074 return v;
6077 typedef struct SaveStateEntry {
6078 char idstr[256];
6079 int instance_id;
6080 int version_id;
6081 SaveStateHandler *save_state;
6082 LoadStateHandler *load_state;
6083 void *opaque;
6084 struct SaveStateEntry *next;
6085 } SaveStateEntry;
6087 static SaveStateEntry *first_se;
6089 int register_savevm(const char *idstr,
6090 int instance_id,
6091 int version_id,
6092 SaveStateHandler *save_state,
6093 LoadStateHandler *load_state,
6094 void *opaque)
6096 SaveStateEntry *se, **pse;
6098 se = qemu_malloc(sizeof(SaveStateEntry));
6099 if (!se)
6100 return -1;
6101 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6102 se->instance_id = instance_id;
6103 se->version_id = version_id;
6104 se->save_state = save_state;
6105 se->load_state = load_state;
6106 se->opaque = opaque;
6107 se->next = NULL;
6109 /* add at the end of list */
6110 pse = &first_se;
6111 while (*pse != NULL)
6112 pse = &(*pse)->next;
6113 *pse = se;
6114 return 0;
6117 #define QEMU_VM_FILE_MAGIC 0x5145564d
6118 #define QEMU_VM_FILE_VERSION 0x00000002
6120 static int qemu_savevm_state(QEMUFile *f)
6122 SaveStateEntry *se;
6123 int len, ret;
6124 int64_t cur_pos, len_pos, total_len_pos;
6126 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6127 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6128 total_len_pos = qemu_ftell(f);
6129 qemu_put_be64(f, 0); /* total size */
6131 for(se = first_se; se != NULL; se = se->next) {
6132 /* ID string */
6133 len = strlen(se->idstr);
6134 qemu_put_byte(f, len);
6135 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6137 qemu_put_be32(f, se->instance_id);
6138 qemu_put_be32(f, se->version_id);
6140 /* record size: filled later */
6141 len_pos = qemu_ftell(f);
6142 qemu_put_be32(f, 0);
6143 se->save_state(f, se->opaque);
6145 /* fill record size */
6146 cur_pos = qemu_ftell(f);
6147 len = cur_pos - len_pos - 4;
6148 qemu_fseek(f, len_pos, SEEK_SET);
6149 qemu_put_be32(f, len);
6150 qemu_fseek(f, cur_pos, SEEK_SET);
6152 cur_pos = qemu_ftell(f);
6153 qemu_fseek(f, total_len_pos, SEEK_SET);
6154 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6155 qemu_fseek(f, cur_pos, SEEK_SET);
6157 ret = 0;
6158 return ret;
6161 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6163 SaveStateEntry *se;
6165 for(se = first_se; se != NULL; se = se->next) {
6166 if (!strcmp(se->idstr, idstr) &&
6167 instance_id == se->instance_id)
6168 return se;
6170 return NULL;
6173 static int qemu_loadvm_state(QEMUFile *f)
6175 SaveStateEntry *se;
6176 int len, ret, instance_id, record_len, version_id;
6177 int64_t total_len, end_pos, cur_pos;
6178 unsigned int v;
6179 char idstr[256];
6181 v = qemu_get_be32(f);
6182 if (v != QEMU_VM_FILE_MAGIC)
6183 goto fail;
6184 v = qemu_get_be32(f);
6185 if (v != QEMU_VM_FILE_VERSION) {
6186 fail:
6187 ret = -1;
6188 goto the_end;
6190 total_len = qemu_get_be64(f);
6191 end_pos = total_len + qemu_ftell(f);
6192 for(;;) {
6193 if (qemu_ftell(f) >= end_pos)
6194 break;
6195 len = qemu_get_byte(f);
6196 qemu_get_buffer(f, (uint8_t *)idstr, len);
6197 idstr[len] = '\0';
6198 instance_id = qemu_get_be32(f);
6199 version_id = qemu_get_be32(f);
6200 record_len = qemu_get_be32(f);
6201 #if 0
6202 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6203 idstr, instance_id, version_id, record_len);
6204 #endif
6205 cur_pos = qemu_ftell(f);
6206 se = find_se(idstr, instance_id);
6207 if (!se) {
6208 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6209 instance_id, idstr);
6210 } else {
6211 ret = se->load_state(f, se->opaque, version_id);
6212 if (ret < 0) {
6213 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6214 instance_id, idstr);
6215 goto the_end;
6218 /* always seek to exact end of record */
6219 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6221 ret = 0;
6222 the_end:
6223 return ret;
6226 int qemu_live_savevm_state(QEMUFile *f)
6228 SaveStateEntry *se;
6229 int len, ret;
6231 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6232 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6234 for(se = first_se; se != NULL; se = se->next) {
6235 len = strlen(se->idstr);
6237 qemu_put_byte(f, len);
6238 qemu_put_buffer(f, se->idstr, len);
6239 qemu_put_be32(f, se->instance_id);
6240 qemu_put_be32(f, se->version_id);
6242 se->save_state(f, se->opaque);
6245 qemu_put_byte(f, 0);
6247 ret = 0;
6248 return ret;
6251 int qemu_live_loadvm_state(QEMUFile *f)
6253 SaveStateEntry *se;
6254 int len, ret, instance_id, version_id;
6255 unsigned int v;
6256 char idstr[256];
6258 v = qemu_get_be32(f);
6259 if (v != QEMU_VM_FILE_MAGIC)
6260 goto fail;
6261 v = qemu_get_be32(f);
6262 if (v != QEMU_VM_FILE_VERSION) {
6263 fail:
6264 ret = -1;
6265 goto the_end;
6268 for(;;) {
6269 len = qemu_get_byte(f);
6270 if (len == 0)
6271 break;
6272 qemu_get_buffer(f, idstr, len);
6273 idstr[len] = '\0';
6274 instance_id = qemu_get_be32(f);
6275 version_id = qemu_get_be32(f);
6276 se = find_se(idstr, instance_id);
6277 if (!se) {
6278 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6279 instance_id, idstr);
6280 } else {
6281 if (version_id > se->version_id) { /* src version > dst version */
6282 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6283 idstr, version_id, se->version_id);
6284 ret = -1;
6285 goto the_end;
6287 ret = se->load_state(f, se->opaque, version_id);
6288 if (ret < 0) {
6289 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6290 instance_id, idstr);
6291 goto the_end;
6295 ret = 0;
6297 qemu_announce_self();
6299 the_end:
6300 return ret;
6303 /* device can contain snapshots */
6304 static int bdrv_can_snapshot(BlockDriverState *bs)
6306 return (bs &&
6307 !bdrv_is_removable(bs) &&
6308 !bdrv_is_read_only(bs));
6311 /* device must be snapshots in order to have a reliable snapshot */
6312 static int bdrv_has_snapshot(BlockDriverState *bs)
6314 return (bs &&
6315 !bdrv_is_removable(bs) &&
6316 !bdrv_is_read_only(bs));
6319 static BlockDriverState *get_bs_snapshots(void)
6321 BlockDriverState *bs;
6322 int i;
6324 if (bs_snapshots)
6325 return bs_snapshots;
6326 for(i = 0; i <= nb_drives; i++) {
6327 bs = drives_table[i].bdrv;
6328 if (bdrv_can_snapshot(bs))
6329 goto ok;
6331 return NULL;
6333 bs_snapshots = bs;
6334 return bs;
6337 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6338 const char *name)
6340 QEMUSnapshotInfo *sn_tab, *sn;
6341 int nb_sns, i, ret;
6343 ret = -ENOENT;
6344 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6345 if (nb_sns < 0)
6346 return ret;
6347 for(i = 0; i < nb_sns; i++) {
6348 sn = &sn_tab[i];
6349 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6350 *sn_info = *sn;
6351 ret = 0;
6352 break;
6355 qemu_free(sn_tab);
6356 return ret;
6359 void do_savevm(const char *name)
6361 BlockDriverState *bs, *bs1;
6362 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6363 int must_delete, ret, i;
6364 BlockDriverInfo bdi1, *bdi = &bdi1;
6365 QEMUFile *f;
6366 int saved_vm_running;
6367 #ifdef _WIN32
6368 struct _timeb tb;
6369 #else
6370 struct timeval tv;
6371 #endif
6373 bs = get_bs_snapshots();
6374 if (!bs) {
6375 term_printf("No block device can accept snapshots\n");
6376 return;
6379 /* ??? Should this occur after vm_stop? */
6380 qemu_aio_flush();
6382 saved_vm_running = vm_running;
6383 vm_stop(0);
6385 must_delete = 0;
6386 if (name) {
6387 ret = bdrv_snapshot_find(bs, old_sn, name);
6388 if (ret >= 0) {
6389 must_delete = 1;
6392 memset(sn, 0, sizeof(*sn));
6393 if (must_delete) {
6394 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6395 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6396 } else {
6397 if (name)
6398 pstrcpy(sn->name, sizeof(sn->name), name);
6401 /* fill auxiliary fields */
6402 #ifdef _WIN32
6403 _ftime(&tb);
6404 sn->date_sec = tb.time;
6405 sn->date_nsec = tb.millitm * 1000000;
6406 #else
6407 gettimeofday(&tv, NULL);
6408 sn->date_sec = tv.tv_sec;
6409 sn->date_nsec = tv.tv_usec * 1000;
6410 #endif
6411 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6413 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6414 term_printf("Device %s does not support VM state snapshots\n",
6415 bdrv_get_device_name(bs));
6416 goto the_end;
6419 /* save the VM state */
6420 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6421 if (!f) {
6422 term_printf("Could not open VM state file\n");
6423 goto the_end;
6425 ret = qemu_savevm_state(f);
6426 sn->vm_state_size = qemu_ftell(f);
6427 qemu_fclose(f);
6428 if (ret < 0) {
6429 term_printf("Error %d while writing VM\n", ret);
6430 goto the_end;
6433 /* create the snapshots */
6435 for(i = 0; i < nb_drives; i++) {
6436 bs1 = drives_table[i].bdrv;
6437 if (bdrv_has_snapshot(bs1)) {
6438 if (must_delete) {
6439 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6440 if (ret < 0) {
6441 term_printf("Error while deleting snapshot on '%s'\n",
6442 bdrv_get_device_name(bs1));
6445 ret = bdrv_snapshot_create(bs1, sn);
6446 if (ret < 0) {
6447 term_printf("Error while creating snapshot on '%s'\n",
6448 bdrv_get_device_name(bs1));
6453 the_end:
6454 if (saved_vm_running)
6455 vm_start();
6458 void do_loadvm(const char *name)
6460 BlockDriverState *bs, *bs1;
6461 BlockDriverInfo bdi1, *bdi = &bdi1;
6462 QEMUFile *f;
6463 int i, ret;
6464 int saved_vm_running;
6466 bs = get_bs_snapshots();
6467 if (!bs) {
6468 term_printf("No block device supports snapshots\n");
6469 return;
6472 /* Flush all IO requests so they don't interfere with the new state. */
6473 qemu_aio_flush();
6475 saved_vm_running = vm_running;
6476 vm_stop(0);
6478 for(i = 0; i <= nb_drives; i++) {
6479 bs1 = drives_table[i].bdrv;
6480 if (bdrv_has_snapshot(bs1)) {
6481 ret = bdrv_snapshot_goto(bs1, name);
6482 if (ret < 0) {
6483 if (bs != bs1)
6484 term_printf("Warning: ");
6485 switch(ret) {
6486 case -ENOTSUP:
6487 term_printf("Snapshots not supported on device '%s'\n",
6488 bdrv_get_device_name(bs1));
6489 break;
6490 case -ENOENT:
6491 term_printf("Could not find snapshot '%s' on device '%s'\n",
6492 name, bdrv_get_device_name(bs1));
6493 break;
6494 default:
6495 term_printf("Error %d while activating snapshot on '%s'\n",
6496 ret, bdrv_get_device_name(bs1));
6497 break;
6499 /* fatal on snapshot block device */
6500 if (bs == bs1)
6501 goto the_end;
6506 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6507 term_printf("Device %s does not support VM state snapshots\n",
6508 bdrv_get_device_name(bs));
6509 return;
6512 /* restore the VM state */
6513 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6514 if (!f) {
6515 term_printf("Could not open VM state file\n");
6516 goto the_end;
6518 ret = qemu_loadvm_state(f);
6519 qemu_fclose(f);
6520 if (ret < 0) {
6521 term_printf("Error %d while loading VM state\n", ret);
6523 the_end:
6524 if (saved_vm_running)
6525 vm_start();
6528 void do_delvm(const char *name)
6530 BlockDriverState *bs, *bs1;
6531 int i, ret;
6533 bs = get_bs_snapshots();
6534 if (!bs) {
6535 term_printf("No block device supports snapshots\n");
6536 return;
6539 for(i = 0; i <= nb_drives; i++) {
6540 bs1 = drives_table[i].bdrv;
6541 if (bdrv_has_snapshot(bs1)) {
6542 ret = bdrv_snapshot_delete(bs1, name);
6543 if (ret < 0) {
6544 if (ret == -ENOTSUP)
6545 term_printf("Snapshots not supported on device '%s'\n",
6546 bdrv_get_device_name(bs1));
6547 else
6548 term_printf("Error %d while deleting snapshot on '%s'\n",
6549 ret, bdrv_get_device_name(bs1));
6555 void do_info_snapshots(void)
6557 BlockDriverState *bs, *bs1;
6558 QEMUSnapshotInfo *sn_tab, *sn;
6559 int nb_sns, i;
6560 char buf[256];
6562 bs = get_bs_snapshots();
6563 if (!bs) {
6564 term_printf("No available block device supports snapshots\n");
6565 return;
6567 term_printf("Snapshot devices:");
6568 for(i = 0; i <= nb_drives; i++) {
6569 bs1 = drives_table[i].bdrv;
6570 if (bdrv_has_snapshot(bs1)) {
6571 if (bs == bs1)
6572 term_printf(" %s", bdrv_get_device_name(bs1));
6575 term_printf("\n");
6577 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6578 if (nb_sns < 0) {
6579 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6580 return;
6582 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6583 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6584 for(i = 0; i < nb_sns; i++) {
6585 sn = &sn_tab[i];
6586 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6588 qemu_free(sn_tab);
6591 /***********************************************************/
6592 /* cpu save/restore */
6594 #if defined(TARGET_I386)
6596 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6598 qemu_put_be32(f, dt->selector);
6599 qemu_put_betl(f, dt->base);
6600 qemu_put_be32(f, dt->limit);
6601 qemu_put_be32(f, dt->flags);
6604 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6606 dt->selector = qemu_get_be32(f);
6607 dt->base = qemu_get_betl(f);
6608 dt->limit = qemu_get_be32(f);
6609 dt->flags = qemu_get_be32(f);
6612 void cpu_save(QEMUFile *f, void *opaque)
6614 CPUState *env = opaque;
6615 uint16_t fptag, fpus, fpuc, fpregs_format;
6616 uint32_t hflags;
6617 int i;
6619 if (kvm_enabled())
6620 kvm_save_registers(env);
6622 for(i = 0; i < CPU_NB_REGS; i++)
6623 qemu_put_betls(f, &env->regs[i]);
6624 qemu_put_betls(f, &env->eip);
6625 qemu_put_betls(f, &env->eflags);
6626 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6627 qemu_put_be32s(f, &hflags);
6629 /* FPU */
6630 fpuc = env->fpuc;
6631 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6632 fptag = 0;
6633 for(i = 0; i < 8; i++) {
6634 fptag |= ((!env->fptags[i]) << i);
6637 qemu_put_be16s(f, &fpuc);
6638 qemu_put_be16s(f, &fpus);
6639 qemu_put_be16s(f, &fptag);
6641 #ifdef USE_X86LDOUBLE
6642 fpregs_format = 0;
6643 #else
6644 fpregs_format = 1;
6645 #endif
6646 qemu_put_be16s(f, &fpregs_format);
6648 for(i = 0; i < 8; i++) {
6649 #ifdef USE_X86LDOUBLE
6651 uint64_t mant;
6652 uint16_t exp;
6653 /* we save the real CPU data (in case of MMX usage only 'mant'
6654 contains the MMX register */
6655 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6656 qemu_put_be64(f, mant);
6657 qemu_put_be16(f, exp);
6659 #else
6660 /* if we use doubles for float emulation, we save the doubles to
6661 avoid losing information in case of MMX usage. It can give
6662 problems if the image is restored on a CPU where long
6663 doubles are used instead. */
6664 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6665 #endif
6668 for(i = 0; i < 6; i++)
6669 cpu_put_seg(f, &env->segs[i]);
6670 cpu_put_seg(f, &env->ldt);
6671 cpu_put_seg(f, &env->tr);
6672 cpu_put_seg(f, &env->gdt);
6673 cpu_put_seg(f, &env->idt);
6675 qemu_put_be32s(f, &env->sysenter_cs);
6676 qemu_put_be32s(f, &env->sysenter_esp);
6677 qemu_put_be32s(f, &env->sysenter_eip);
6679 qemu_put_betls(f, &env->cr[0]);
6680 qemu_put_betls(f, &env->cr[2]);
6681 qemu_put_betls(f, &env->cr[3]);
6682 qemu_put_betls(f, &env->cr[4]);
6684 for(i = 0; i < 8; i++)
6685 qemu_put_betls(f, &env->dr[i]);
6687 /* MMU */
6688 qemu_put_be32s(f, &env->a20_mask);
6690 /* XMM */
6691 qemu_put_be32s(f, &env->mxcsr);
6692 for(i = 0; i < CPU_NB_REGS; i++) {
6693 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6694 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6697 #ifdef TARGET_X86_64
6698 qemu_put_be64s(f, &env->efer);
6699 qemu_put_be64s(f, &env->star);
6700 qemu_put_be64s(f, &env->lstar);
6701 qemu_put_be64s(f, &env->cstar);
6702 qemu_put_be64s(f, &env->fmask);
6703 qemu_put_be64s(f, &env->kernelgsbase);
6704 #endif
6705 qemu_put_be32s(f, &env->smbase);
6707 if (kvm_enabled()) {
6708 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6709 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6711 qemu_put_be64s(f, &env->tsc);
6715 #ifdef USE_X86LDOUBLE
6716 /* XXX: add that in a FPU generic layer */
6717 union x86_longdouble {
6718 uint64_t mant;
6719 uint16_t exp;
6722 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6723 #define EXPBIAS1 1023
6724 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6725 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6727 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6729 int e;
6730 /* mantissa */
6731 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6732 /* exponent + sign */
6733 e = EXPD1(temp) - EXPBIAS1 + 16383;
6734 e |= SIGND1(temp) >> 16;
6735 p->exp = e;
6737 #endif
6739 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6741 CPUState *env = opaque;
6742 int i, guess_mmx;
6743 uint32_t hflags;
6744 uint16_t fpus, fpuc, fptag, fpregs_format;
6746 if (version_id != 3 && version_id != 4)
6747 return -EINVAL;
6748 for(i = 0; i < CPU_NB_REGS; i++)
6749 qemu_get_betls(f, &env->regs[i]);
6750 qemu_get_betls(f, &env->eip);
6751 qemu_get_betls(f, &env->eflags);
6752 qemu_get_be32s(f, &hflags);
6754 qemu_get_be16s(f, &fpuc);
6755 qemu_get_be16s(f, &fpus);
6756 qemu_get_be16s(f, &fptag);
6757 qemu_get_be16s(f, &fpregs_format);
6759 /* NOTE: we cannot always restore the FPU state if the image come
6760 from a host with a different 'USE_X86LDOUBLE' define. We guess
6761 if we are in an MMX state to restore correctly in that case. */
6762 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6763 for(i = 0; i < 8; i++) {
6764 uint64_t mant;
6765 uint16_t exp;
6767 switch(fpregs_format) {
6768 case 0:
6769 mant = qemu_get_be64(f);
6770 exp = qemu_get_be16(f);
6771 #ifdef USE_X86LDOUBLE
6772 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6773 #else
6774 /* difficult case */
6775 if (guess_mmx)
6776 env->fpregs[i].mmx.MMX_Q(0) = mant;
6777 else
6778 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6779 #endif
6780 break;
6781 case 1:
6782 mant = qemu_get_be64(f);
6783 #ifdef USE_X86LDOUBLE
6785 union x86_longdouble *p;
6786 /* difficult case */
6787 p = (void *)&env->fpregs[i];
6788 if (guess_mmx) {
6789 p->mant = mant;
6790 p->exp = 0xffff;
6791 } else {
6792 fp64_to_fp80(p, mant);
6795 #else
6796 env->fpregs[i].mmx.MMX_Q(0) = mant;
6797 #endif
6798 break;
6799 default:
6800 return -EINVAL;
6804 env->fpuc = fpuc;
6805 /* XXX: restore FPU round state */
6806 env->fpstt = (fpus >> 11) & 7;
6807 env->fpus = fpus & ~0x3800;
6808 fptag ^= 0xff;
6809 for(i = 0; i < 8; i++) {
6810 env->fptags[i] = (fptag >> i) & 1;
6813 for(i = 0; i < 6; i++)
6814 cpu_get_seg(f, &env->segs[i]);
6815 cpu_get_seg(f, &env->ldt);
6816 cpu_get_seg(f, &env->tr);
6817 cpu_get_seg(f, &env->gdt);
6818 cpu_get_seg(f, &env->idt);
6820 qemu_get_be32s(f, &env->sysenter_cs);
6821 qemu_get_be32s(f, &env->sysenter_esp);
6822 qemu_get_be32s(f, &env->sysenter_eip);
6824 qemu_get_betls(f, &env->cr[0]);
6825 qemu_get_betls(f, &env->cr[2]);
6826 qemu_get_betls(f, &env->cr[3]);
6827 qemu_get_betls(f, &env->cr[4]);
6829 for(i = 0; i < 8; i++)
6830 qemu_get_betls(f, &env->dr[i]);
6832 /* MMU */
6833 qemu_get_be32s(f, &env->a20_mask);
6835 qemu_get_be32s(f, &env->mxcsr);
6836 for(i = 0; i < CPU_NB_REGS; i++) {
6837 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6838 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6841 #ifdef TARGET_X86_64
6842 qemu_get_be64s(f, &env->efer);
6843 qemu_get_be64s(f, &env->star);
6844 qemu_get_be64s(f, &env->lstar);
6845 qemu_get_be64s(f, &env->cstar);
6846 qemu_get_be64s(f, &env->fmask);
6847 qemu_get_be64s(f, &env->kernelgsbase);
6848 #endif
6849 if (version_id >= 4)
6850 qemu_get_be32s(f, &env->smbase);
6852 /* XXX: compute hflags from scratch, except for CPL and IIF */
6853 env->hflags = hflags;
6854 tlb_flush(env, 1);
6855 if (kvm_enabled()) {
6856 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6857 because no userspace IRQs will ever clear this flag */
6858 env->hflags &= ~HF_HALTED_MASK;
6859 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6860 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6862 qemu_get_be64s(f, &env->tsc);
6863 kvm_load_registers(env);
6865 return 0;
6868 #elif defined(TARGET_PPC)
6869 void cpu_save(QEMUFile *f, void *opaque)
6873 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6875 return 0;
6878 #elif defined(TARGET_MIPS)
6879 void cpu_save(QEMUFile *f, void *opaque)
6883 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6885 return 0;
6888 #elif defined(TARGET_SPARC)
6889 void cpu_save(QEMUFile *f, void *opaque)
6891 CPUState *env = opaque;
6892 int i;
6893 uint32_t tmp;
6895 for(i = 0; i < 8; i++)
6896 qemu_put_betls(f, &env->gregs[i]);
6897 for(i = 0; i < NWINDOWS * 16; i++)
6898 qemu_put_betls(f, &env->regbase[i]);
6900 /* FPU */
6901 for(i = 0; i < TARGET_FPREGS; i++) {
6902 union {
6903 float32 f;
6904 uint32_t i;
6905 } u;
6906 u.f = env->fpr[i];
6907 qemu_put_be32(f, u.i);
6910 qemu_put_betls(f, &env->pc);
6911 qemu_put_betls(f, &env->npc);
6912 qemu_put_betls(f, &env->y);
6913 tmp = GET_PSR(env);
6914 qemu_put_be32(f, tmp);
6915 qemu_put_betls(f, &env->fsr);
6916 qemu_put_betls(f, &env->tbr);
6917 #ifndef TARGET_SPARC64
6918 qemu_put_be32s(f, &env->wim);
6919 /* MMU */
6920 for(i = 0; i < 16; i++)
6921 qemu_put_be32s(f, &env->mmuregs[i]);
6922 #endif
6925 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6927 CPUState *env = opaque;
6928 int i;
6929 uint32_t tmp;
6931 for(i = 0; i < 8; i++)
6932 qemu_get_betls(f, &env->gregs[i]);
6933 for(i = 0; i < NWINDOWS * 16; i++)
6934 qemu_get_betls(f, &env->regbase[i]);
6936 /* FPU */
6937 for(i = 0; i < TARGET_FPREGS; i++) {
6938 union {
6939 float32 f;
6940 uint32_t i;
6941 } u;
6942 u.i = qemu_get_be32(f);
6943 env->fpr[i] = u.f;
6946 qemu_get_betls(f, &env->pc);
6947 qemu_get_betls(f, &env->npc);
6948 qemu_get_betls(f, &env->y);
6949 tmp = qemu_get_be32(f);
6950 env->cwp = 0; /* needed to ensure that the wrapping registers are
6951 correctly updated */
6952 PUT_PSR(env, tmp);
6953 qemu_get_betls(f, &env->fsr);
6954 qemu_get_betls(f, &env->tbr);
6955 #ifndef TARGET_SPARC64
6956 qemu_get_be32s(f, &env->wim);
6957 /* MMU */
6958 for(i = 0; i < 16; i++)
6959 qemu_get_be32s(f, &env->mmuregs[i]);
6960 #endif
6961 tlb_flush(env, 1);
6962 return 0;
6965 #elif defined(TARGET_ARM)
6967 void cpu_save(QEMUFile *f, void *opaque)
6969 int i;
6970 CPUARMState *env = (CPUARMState *)opaque;
6972 for (i = 0; i < 16; i++) {
6973 qemu_put_be32(f, env->regs[i]);
6975 qemu_put_be32(f, cpsr_read(env));
6976 qemu_put_be32(f, env->spsr);
6977 for (i = 0; i < 6; i++) {
6978 qemu_put_be32(f, env->banked_spsr[i]);
6979 qemu_put_be32(f, env->banked_r13[i]);
6980 qemu_put_be32(f, env->banked_r14[i]);
6982 for (i = 0; i < 5; i++) {
6983 qemu_put_be32(f, env->usr_regs[i]);
6984 qemu_put_be32(f, env->fiq_regs[i]);
6986 qemu_put_be32(f, env->cp15.c0_cpuid);
6987 qemu_put_be32(f, env->cp15.c0_cachetype);
6988 qemu_put_be32(f, env->cp15.c1_sys);
6989 qemu_put_be32(f, env->cp15.c1_coproc);
6990 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6991 qemu_put_be32(f, env->cp15.c2_base0);
6992 qemu_put_be32(f, env->cp15.c2_base1);
6993 qemu_put_be32(f, env->cp15.c2_mask);
6994 qemu_put_be32(f, env->cp15.c2_data);
6995 qemu_put_be32(f, env->cp15.c2_insn);
6996 qemu_put_be32(f, env->cp15.c3);
6997 qemu_put_be32(f, env->cp15.c5_insn);
6998 qemu_put_be32(f, env->cp15.c5_data);
6999 for (i = 0; i < 8; i++) {
7000 qemu_put_be32(f, env->cp15.c6_region[i]);
7002 qemu_put_be32(f, env->cp15.c6_insn);
7003 qemu_put_be32(f, env->cp15.c6_data);
7004 qemu_put_be32(f, env->cp15.c9_insn);
7005 qemu_put_be32(f, env->cp15.c9_data);
7006 qemu_put_be32(f, env->cp15.c13_fcse);
7007 qemu_put_be32(f, env->cp15.c13_context);
7008 qemu_put_be32(f, env->cp15.c13_tls1);
7009 qemu_put_be32(f, env->cp15.c13_tls2);
7010 qemu_put_be32(f, env->cp15.c13_tls3);
7011 qemu_put_be32(f, env->cp15.c15_cpar);
7013 qemu_put_be32(f, env->features);
7015 if (arm_feature(env, ARM_FEATURE_VFP)) {
7016 for (i = 0; i < 16; i++) {
7017 CPU_DoubleU u;
7018 u.d = env->vfp.regs[i];
7019 qemu_put_be32(f, u.l.upper);
7020 qemu_put_be32(f, u.l.lower);
7022 for (i = 0; i < 16; i++) {
7023 qemu_put_be32(f, env->vfp.xregs[i]);
7026 /* TODO: Should use proper FPSCR access functions. */
7027 qemu_put_be32(f, env->vfp.vec_len);
7028 qemu_put_be32(f, env->vfp.vec_stride);
7030 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7031 for (i = 16; i < 32; i++) {
7032 CPU_DoubleU u;
7033 u.d = env->vfp.regs[i];
7034 qemu_put_be32(f, u.l.upper);
7035 qemu_put_be32(f, u.l.lower);
7040 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7041 for (i = 0; i < 16; i++) {
7042 qemu_put_be64(f, env->iwmmxt.regs[i]);
7044 for (i = 0; i < 16; i++) {
7045 qemu_put_be32(f, env->iwmmxt.cregs[i]);
7049 if (arm_feature(env, ARM_FEATURE_M)) {
7050 qemu_put_be32(f, env->v7m.other_sp);
7051 qemu_put_be32(f, env->v7m.vecbase);
7052 qemu_put_be32(f, env->v7m.basepri);
7053 qemu_put_be32(f, env->v7m.control);
7054 qemu_put_be32(f, env->v7m.current_sp);
7055 qemu_put_be32(f, env->v7m.exception);
7059 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7061 CPUARMState *env = (CPUARMState *)opaque;
7062 int i;
7064 if (version_id != ARM_CPU_SAVE_VERSION)
7065 return -EINVAL;
7067 for (i = 0; i < 16; i++) {
7068 env->regs[i] = qemu_get_be32(f);
7070 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7071 env->spsr = qemu_get_be32(f);
7072 for (i = 0; i < 6; i++) {
7073 env->banked_spsr[i] = qemu_get_be32(f);
7074 env->banked_r13[i] = qemu_get_be32(f);
7075 env->banked_r14[i] = qemu_get_be32(f);
7077 for (i = 0; i < 5; i++) {
7078 env->usr_regs[i] = qemu_get_be32(f);
7079 env->fiq_regs[i] = qemu_get_be32(f);
7081 env->cp15.c0_cpuid = qemu_get_be32(f);
7082 env->cp15.c0_cachetype = qemu_get_be32(f);
7083 env->cp15.c1_sys = qemu_get_be32(f);
7084 env->cp15.c1_coproc = qemu_get_be32(f);
7085 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7086 env->cp15.c2_base0 = qemu_get_be32(f);
7087 env->cp15.c2_base1 = qemu_get_be32(f);
7088 env->cp15.c2_mask = qemu_get_be32(f);
7089 env->cp15.c2_data = qemu_get_be32(f);
7090 env->cp15.c2_insn = qemu_get_be32(f);
7091 env->cp15.c3 = qemu_get_be32(f);
7092 env->cp15.c5_insn = qemu_get_be32(f);
7093 env->cp15.c5_data = qemu_get_be32(f);
7094 for (i = 0; i < 8; i++) {
7095 env->cp15.c6_region[i] = qemu_get_be32(f);
7097 env->cp15.c6_insn = qemu_get_be32(f);
7098 env->cp15.c6_data = qemu_get_be32(f);
7099 env->cp15.c9_insn = qemu_get_be32(f);
7100 env->cp15.c9_data = qemu_get_be32(f);
7101 env->cp15.c13_fcse = qemu_get_be32(f);
7102 env->cp15.c13_context = qemu_get_be32(f);
7103 env->cp15.c13_tls1 = qemu_get_be32(f);
7104 env->cp15.c13_tls2 = qemu_get_be32(f);
7105 env->cp15.c13_tls3 = qemu_get_be32(f);
7106 env->cp15.c15_cpar = qemu_get_be32(f);
7108 env->features = qemu_get_be32(f);
7110 if (arm_feature(env, ARM_FEATURE_VFP)) {
7111 for (i = 0; i < 16; i++) {
7112 CPU_DoubleU u;
7113 u.l.upper = qemu_get_be32(f);
7114 u.l.lower = qemu_get_be32(f);
7115 env->vfp.regs[i] = u.d;
7117 for (i = 0; i < 16; i++) {
7118 env->vfp.xregs[i] = qemu_get_be32(f);
7121 /* TODO: Should use proper FPSCR access functions. */
7122 env->vfp.vec_len = qemu_get_be32(f);
7123 env->vfp.vec_stride = qemu_get_be32(f);
7125 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7126 for (i = 0; i < 16; i++) {
7127 CPU_DoubleU u;
7128 u.l.upper = qemu_get_be32(f);
7129 u.l.lower = qemu_get_be32(f);
7130 env->vfp.regs[i] = u.d;
7135 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7136 for (i = 0; i < 16; i++) {
7137 env->iwmmxt.regs[i] = qemu_get_be64(f);
7139 for (i = 0; i < 16; i++) {
7140 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7144 if (arm_feature(env, ARM_FEATURE_M)) {
7145 env->v7m.other_sp = qemu_get_be32(f);
7146 env->v7m.vecbase = qemu_get_be32(f);
7147 env->v7m.basepri = qemu_get_be32(f);
7148 env->v7m.control = qemu_get_be32(f);
7149 env->v7m.current_sp = qemu_get_be32(f);
7150 env->v7m.exception = qemu_get_be32(f);
7153 return 0;
7156 #elif defined(TARGET_IA64)
7157 void cpu_save(QEMUFile *f, void *opaque)
7161 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7163 return 0;
7165 #else
7167 //#warning No CPU save/restore functions
7169 #endif
7171 /***********************************************************/
7172 /* ram save/restore */
7174 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7176 int v;
7178 v = qemu_get_byte(f);
7179 switch(v) {
7180 case 0:
7181 if (qemu_get_buffer(f, buf, len) != len)
7182 return -EIO;
7183 break;
7184 case 1:
7185 v = qemu_get_byte(f);
7186 memset(buf, v, len);
7187 break;
7188 default:
7189 return -EINVAL;
7191 return 0;
7194 static int ram_load_v1(QEMUFile *f, void *opaque)
7196 int i, ret;
7198 if (qemu_get_be32(f) != phys_ram_size)
7199 return -EINVAL;
7200 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7201 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7202 continue;
7203 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7204 if (ret)
7205 return ret;
7207 return 0;
7210 #define BDRV_HASH_BLOCK_SIZE 1024
7211 #define IOBUF_SIZE 4096
7212 #define RAM_CBLOCK_MAGIC 0xfabe
7214 typedef struct RamCompressState {
7215 z_stream zstream;
7216 QEMUFile *f;
7217 uint8_t buf[IOBUF_SIZE];
7218 } RamCompressState;
7220 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7222 int ret;
7223 memset(s, 0, sizeof(*s));
7224 s->f = f;
7225 ret = deflateInit2(&s->zstream, 1,
7226 Z_DEFLATED, 15,
7227 9, Z_DEFAULT_STRATEGY);
7228 if (ret != Z_OK)
7229 return -1;
7230 s->zstream.avail_out = IOBUF_SIZE;
7231 s->zstream.next_out = s->buf;
7232 return 0;
7235 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7237 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7238 qemu_put_be16(s->f, len);
7239 qemu_put_buffer(s->f, buf, len);
7242 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7244 int ret;
7246 s->zstream.avail_in = len;
7247 s->zstream.next_in = (uint8_t *)buf;
7248 while (s->zstream.avail_in > 0) {
7249 ret = deflate(&s->zstream, Z_NO_FLUSH);
7250 if (ret != Z_OK)
7251 return -1;
7252 if (s->zstream.avail_out == 0) {
7253 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7254 s->zstream.avail_out = IOBUF_SIZE;
7255 s->zstream.next_out = s->buf;
7258 return 0;
7261 static void ram_compress_close(RamCompressState *s)
7263 int len, ret;
7265 /* compress last bytes */
7266 for(;;) {
7267 ret = deflate(&s->zstream, Z_FINISH);
7268 if (ret == Z_OK || ret == Z_STREAM_END) {
7269 len = IOBUF_SIZE - s->zstream.avail_out;
7270 if (len > 0) {
7271 ram_put_cblock(s, s->buf, len);
7273 s->zstream.avail_out = IOBUF_SIZE;
7274 s->zstream.next_out = s->buf;
7275 if (ret == Z_STREAM_END)
7276 break;
7277 } else {
7278 goto fail;
7281 fail:
7282 deflateEnd(&s->zstream);
7285 typedef struct RamDecompressState {
7286 z_stream zstream;
7287 QEMUFile *f;
7288 uint8_t buf[IOBUF_SIZE];
7289 } RamDecompressState;
7291 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7293 int ret;
7294 memset(s, 0, sizeof(*s));
7295 s->f = f;
7296 ret = inflateInit(&s->zstream);
7297 if (ret != Z_OK)
7298 return -1;
7299 return 0;
7302 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7304 int ret, clen;
7306 s->zstream.avail_out = len;
7307 s->zstream.next_out = buf;
7308 while (s->zstream.avail_out > 0) {
7309 if (s->zstream.avail_in == 0) {
7310 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7311 return -1;
7312 clen = qemu_get_be16(s->f);
7313 if (clen > IOBUF_SIZE)
7314 return -1;
7315 qemu_get_buffer(s->f, s->buf, clen);
7316 s->zstream.avail_in = clen;
7317 s->zstream.next_in = s->buf;
7319 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7320 if (ret != Z_OK && ret != Z_STREAM_END) {
7321 return -1;
7324 return 0;
7327 static void ram_decompress_close(RamDecompressState *s)
7329 inflateEnd(&s->zstream);
7332 static void ram_save_live(QEMUFile *f, void *opaque)
7334 target_ulong addr;
7336 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7337 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7338 continue;
7339 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7340 qemu_put_be32(f, addr);
7341 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7344 qemu_put_be32(f, 1);
7347 static void ram_save_static(QEMUFile *f, void *opaque)
7349 int i;
7350 RamCompressState s1, *s = &s1;
7351 uint8_t buf[10];
7353 qemu_put_be32(f, phys_ram_size);
7354 if (ram_compress_open(s, f) < 0)
7355 return;
7356 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7357 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7358 continue;
7359 #if 0
7360 if (tight_savevm_enabled) {
7361 int64_t sector_num;
7362 int j;
7364 /* find if the memory block is available on a virtual
7365 block device */
7366 sector_num = -1;
7367 for(j = 0; j < nb_drives; j++) {
7368 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7369 phys_ram_base + i,
7370 BDRV_HASH_BLOCK_SIZE);
7371 if (sector_num >= 0)
7372 break;
7374 if (j == nb_drives)
7375 goto normal_compress;
7376 buf[0] = 1;
7377 buf[1] = j;
7378 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7379 ram_compress_buf(s, buf, 10);
7380 } else
7381 #endif
7383 // normal_compress:
7384 buf[0] = 0;
7385 ram_compress_buf(s, buf, 1);
7386 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7389 ram_compress_close(s);
7392 static void ram_save(QEMUFile *f, void *opaque)
7394 int in_migration = cpu_physical_memory_get_dirty_tracking();
7396 qemu_put_byte(f, in_migration);
7398 if (in_migration)
7399 ram_save_live(f, opaque);
7400 else
7401 ram_save_static(f, opaque);
7404 static int ram_load_live(QEMUFile *f, void *opaque)
7406 target_ulong addr;
7408 do {
7409 addr = qemu_get_be32(f);
7410 if (addr == 1)
7411 break;
7413 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7414 } while (1);
7416 return 0;
7419 static int ram_load_static(QEMUFile *f, void *opaque)
7421 RamDecompressState s1, *s = &s1;
7422 uint8_t buf[10];
7423 int i;
7425 if (qemu_get_be32(f) != phys_ram_size)
7426 return -EINVAL;
7427 if (ram_decompress_open(s, f) < 0)
7428 return -EINVAL;
7429 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7430 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7431 continue;
7432 if (ram_decompress_buf(s, buf, 1) < 0) {
7433 fprintf(stderr, "Error while reading ram block header\n");
7434 goto error;
7436 if (buf[0] == 0) {
7437 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7438 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7439 goto error;
7441 } else
7442 #if 0
7443 if (buf[0] == 1) {
7444 int bs_index;
7445 int64_t sector_num;
7447 ram_decompress_buf(s, buf + 1, 9);
7448 bs_index = buf[1];
7449 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7450 if (bs_index >= nb_drives) {
7451 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7452 goto error;
7454 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7455 phys_ram_base + i,
7456 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7457 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7458 bs_index, sector_num);
7459 goto error;
7461 } else
7462 #endif
7464 error:
7465 printf("Error block header\n");
7466 return -EINVAL;
7469 ram_decompress_close(s);
7470 return 0;
7473 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7475 int ret;
7477 switch (version_id) {
7478 case 1:
7479 ret = ram_load_v1(f, opaque);
7480 break;
7481 case 3:
7482 if (qemu_get_byte(f)) {
7483 ret = ram_load_live(f, opaque);
7484 break;
7486 case 2:
7487 ret = ram_load_static(f, opaque);
7488 break;
7489 default:
7490 ret = -EINVAL;
7491 break;
7494 return ret;
7497 /***********************************************************/
7498 /* bottom halves (can be seen as timers which expire ASAP) */
7500 struct QEMUBH {
7501 QEMUBHFunc *cb;
7502 void *opaque;
7503 int scheduled;
7504 QEMUBH *next;
7507 static QEMUBH *first_bh = NULL;
7509 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7511 QEMUBH *bh;
7512 bh = qemu_mallocz(sizeof(QEMUBH));
7513 if (!bh)
7514 return NULL;
7515 bh->cb = cb;
7516 bh->opaque = opaque;
7517 return bh;
7520 int qemu_bh_poll(void)
7522 QEMUBH *bh, **pbh;
7523 int ret;
7525 ret = 0;
7526 for(;;) {
7527 pbh = &first_bh;
7528 bh = *pbh;
7529 if (!bh)
7530 break;
7531 ret = 1;
7532 *pbh = bh->next;
7533 bh->scheduled = 0;
7534 bh->cb(bh->opaque);
7536 return ret;
7539 void qemu_bh_schedule(QEMUBH *bh)
7541 CPUState *env = cpu_single_env;
7542 if (bh->scheduled)
7543 return;
7544 bh->scheduled = 1;
7545 bh->next = first_bh;
7546 first_bh = bh;
7548 /* stop the currently executing CPU to execute the BH ASAP */
7549 if (env) {
7550 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7554 void qemu_bh_cancel(QEMUBH *bh)
7556 QEMUBH **pbh;
7557 if (bh->scheduled) {
7558 pbh = &first_bh;
7559 while (*pbh != bh)
7560 pbh = &(*pbh)->next;
7561 *pbh = bh->next;
7562 bh->scheduled = 0;
7566 void qemu_bh_delete(QEMUBH *bh)
7568 qemu_bh_cancel(bh);
7569 qemu_free(bh);
7572 /***********************************************************/
7573 /* machine registration */
7575 QEMUMachine *first_machine = NULL;
7577 int qemu_register_machine(QEMUMachine *m)
7579 QEMUMachine **pm;
7580 pm = &first_machine;
7581 while (*pm != NULL)
7582 pm = &(*pm)->next;
7583 m->next = NULL;
7584 *pm = m;
7585 return 0;
7588 static QEMUMachine *find_machine(const char *name)
7590 QEMUMachine *m;
7592 for(m = first_machine; m != NULL; m = m->next) {
7593 if (!strcmp(m->name, name))
7594 return m;
7596 return NULL;
7599 /***********************************************************/
7600 /* main execution loop */
7602 static void gui_update(void *opaque)
7604 DisplayState *ds = opaque;
7605 ds->dpy_refresh(ds);
7606 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7609 struct vm_change_state_entry {
7610 VMChangeStateHandler *cb;
7611 void *opaque;
7612 LIST_ENTRY (vm_change_state_entry) entries;
7615 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7617 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7618 void *opaque)
7620 VMChangeStateEntry *e;
7622 e = qemu_mallocz(sizeof (*e));
7623 if (!e)
7624 return NULL;
7626 e->cb = cb;
7627 e->opaque = opaque;
7628 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7629 return e;
7632 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7634 LIST_REMOVE (e, entries);
7635 qemu_free (e);
7638 static void vm_state_notify(int running)
7640 VMChangeStateEntry *e;
7642 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7643 e->cb(e->opaque, running);
7647 /* XXX: support several handlers */
7648 static VMStopHandler *vm_stop_cb;
7649 static void *vm_stop_opaque;
7651 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7653 vm_stop_cb = cb;
7654 vm_stop_opaque = opaque;
7655 return 0;
7658 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7660 vm_stop_cb = NULL;
7663 void vm_start(void)
7665 if (!vm_running) {
7666 cpu_enable_ticks();
7667 vm_running = 1;
7668 vm_state_notify(1);
7669 qemu_rearm_alarm_timer(alarm_timer);
7673 void vm_stop(int reason)
7675 if (vm_running) {
7676 cpu_disable_ticks();
7677 vm_running = 0;
7678 if (reason != 0) {
7679 if (vm_stop_cb) {
7680 vm_stop_cb(vm_stop_opaque, reason);
7683 vm_state_notify(0);
7687 /* reset/shutdown handler */
7689 typedef struct QEMUResetEntry {
7690 QEMUResetHandler *func;
7691 void *opaque;
7692 struct QEMUResetEntry *next;
7693 } QEMUResetEntry;
7695 static QEMUResetEntry *first_reset_entry;
7696 static int reset_requested;
7697 static int shutdown_requested;
7698 static int powerdown_requested;
7700 int qemu_shutdown_requested(void)
7702 int r = shutdown_requested;
7703 shutdown_requested = 0;
7704 return r;
7707 int qemu_reset_requested(void)
7709 int r = reset_requested;
7710 reset_requested = 0;
7711 return r;
7714 int qemu_powerdown_requested(void)
7716 int r = powerdown_requested;
7717 powerdown_requested = 0;
7718 return r;
7721 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7723 QEMUResetEntry **pre, *re;
7725 pre = &first_reset_entry;
7726 while (*pre != NULL)
7727 pre = &(*pre)->next;
7728 re = qemu_mallocz(sizeof(QEMUResetEntry));
7729 re->func = func;
7730 re->opaque = opaque;
7731 re->next = NULL;
7732 *pre = re;
7735 void qemu_system_reset(void)
7737 QEMUResetEntry *re;
7739 /* reset all devices */
7740 for(re = first_reset_entry; re != NULL; re = re->next) {
7741 re->func(re->opaque);
7745 void qemu_system_reset_request(void)
7747 if (no_reboot) {
7748 shutdown_requested = 1;
7749 } else {
7750 reset_requested = 1;
7752 if (cpu_single_env)
7753 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7756 void qemu_system_shutdown_request(void)
7758 shutdown_requested = 1;
7759 if (cpu_single_env)
7760 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7763 void qemu_system_powerdown_request(void)
7765 powerdown_requested = 1;
7766 if (cpu_single_env)
7767 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7770 void main_loop_wait(int timeout)
7772 IOHandlerRecord *ioh;
7773 fd_set rfds, wfds, xfds;
7774 int ret, nfds;
7775 #ifdef _WIN32
7776 int ret2, i;
7777 #endif
7778 struct timeval tv;
7779 PollingEntry *pe;
7782 /* XXX: need to suppress polling by better using win32 events */
7783 ret = 0;
7784 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7785 ret |= pe->func(pe->opaque);
7787 #ifdef _WIN32
7788 if (ret == 0) {
7789 int err;
7790 WaitObjects *w = &wait_objects;
7792 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7793 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7794 if (w->func[ret - WAIT_OBJECT_0])
7795 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7797 /* Check for additional signaled events */
7798 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7800 /* Check if event is signaled */
7801 ret2 = WaitForSingleObject(w->events[i], 0);
7802 if(ret2 == WAIT_OBJECT_0) {
7803 if (w->func[i])
7804 w->func[i](w->opaque[i]);
7805 } else if (ret2 == WAIT_TIMEOUT) {
7806 } else {
7807 err = GetLastError();
7808 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7811 } else if (ret == WAIT_TIMEOUT) {
7812 } else {
7813 err = GetLastError();
7814 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7817 #endif
7818 /* poll any events */
7819 /* XXX: separate device handlers from system ones */
7820 nfds = -1;
7821 FD_ZERO(&rfds);
7822 FD_ZERO(&wfds);
7823 FD_ZERO(&xfds);
7824 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7825 if (ioh->deleted)
7826 continue;
7827 if (ioh->fd_read &&
7828 (!ioh->fd_read_poll ||
7829 ioh->fd_read_poll(ioh->opaque) != 0)) {
7830 FD_SET(ioh->fd, &rfds);
7831 if (ioh->fd > nfds)
7832 nfds = ioh->fd;
7834 if (ioh->fd_write) {
7835 FD_SET(ioh->fd, &wfds);
7836 if (ioh->fd > nfds)
7837 nfds = ioh->fd;
7841 tv.tv_sec = 0;
7842 #ifdef _WIN32
7843 tv.tv_usec = 0;
7844 #else
7845 tv.tv_usec = timeout * 1000;
7846 #endif
7847 #if defined(CONFIG_SLIRP)
7848 if (slirp_inited) {
7849 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7851 #endif
7852 moreio:
7853 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7854 if (ret > 0) {
7855 IOHandlerRecord **pioh;
7856 int more = 0;
7858 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7859 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7860 ioh->fd_read(ioh->opaque);
7861 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7862 more = 1;
7863 else
7864 FD_CLR(ioh->fd, &rfds);
7866 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7867 ioh->fd_write(ioh->opaque);
7868 more = 1;
7872 /* remove deleted IO handlers */
7873 pioh = &first_io_handler;
7874 while (*pioh) {
7875 ioh = *pioh;
7876 if (ioh->deleted) {
7877 *pioh = ioh->next;
7878 qemu_free(ioh);
7879 } else
7880 pioh = &ioh->next;
7882 if (more)
7883 goto moreio;
7885 #if defined(CONFIG_SLIRP)
7886 if (slirp_inited) {
7887 if (ret < 0) {
7888 FD_ZERO(&rfds);
7889 FD_ZERO(&wfds);
7890 FD_ZERO(&xfds);
7892 slirp_select_poll(&rfds, &wfds, &xfds);
7894 #endif
7895 virtio_net_poll();
7897 qemu_aio_poll();
7899 if (vm_running) {
7900 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7901 qemu_get_clock(vm_clock));
7902 /* run dma transfers, if any */
7903 DMA_run();
7906 /* real time timers */
7907 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7908 qemu_get_clock(rt_clock));
7910 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7911 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7912 qemu_rearm_alarm_timer(alarm_timer);
7915 /* Check bottom-halves last in case any of the earlier events triggered
7916 them. */
7917 qemu_bh_poll();
7921 static int main_loop(void)
7923 int ret, timeout;
7924 #ifdef CONFIG_PROFILER
7925 int64_t ti;
7926 #endif
7927 CPUState *env;
7930 if (kvm_enabled()) {
7931 kvm_main_loop();
7932 cpu_disable_ticks();
7933 return 0;
7936 cur_cpu = first_cpu;
7937 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7938 for(;;) {
7939 if (vm_running) {
7941 for(;;) {
7942 /* get next cpu */
7943 env = next_cpu;
7944 #ifdef CONFIG_PROFILER
7945 ti = profile_getclock();
7946 #endif
7947 ret = cpu_exec(env);
7948 #ifdef CONFIG_PROFILER
7949 qemu_time += profile_getclock() - ti;
7950 #endif
7951 next_cpu = env->next_cpu ?: first_cpu;
7952 if (event_pending) {
7953 ret = EXCP_INTERRUPT;
7954 event_pending = 0;
7955 break;
7957 if (ret == EXCP_HLT) {
7958 /* Give the next CPU a chance to run. */
7959 cur_cpu = env;
7960 continue;
7962 if (ret != EXCP_HALTED)
7963 break;
7964 /* all CPUs are halted ? */
7965 if (env == cur_cpu)
7966 break;
7968 cur_cpu = env;
7970 if (shutdown_requested) {
7971 ret = EXCP_INTERRUPT;
7972 break;
7974 if (reset_requested) {
7975 reset_requested = 0;
7976 qemu_system_reset();
7977 if (kvm_enabled())
7978 kvm_load_registers(env);
7979 ret = EXCP_INTERRUPT;
7981 if (powerdown_requested) {
7982 powerdown_requested = 0;
7983 qemu_system_powerdown();
7984 ret = EXCP_INTERRUPT;
7986 if (ret == EXCP_DEBUG) {
7987 vm_stop(EXCP_DEBUG);
7989 /* If all cpus are halted then wait until the next IRQ */
7990 /* XXX: use timeout computed from timers */
7991 if (ret == EXCP_HALTED)
7992 timeout = 10;
7993 else
7994 timeout = 0;
7995 } else {
7996 timeout = 10;
7998 #ifdef CONFIG_PROFILER
7999 ti = profile_getclock();
8000 #endif
8001 main_loop_wait(timeout);
8002 #ifdef CONFIG_PROFILER
8003 dev_time += profile_getclock() - ti;
8004 #endif
8006 cpu_disable_ticks();
8007 return ret;
8010 static void help(int exitcode)
8012 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8013 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8014 "usage: %s [options] [disk_image]\n"
8015 "\n"
8016 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8017 "\n"
8018 "Standard options:\n"
8019 "-M machine select emulated machine (-M ? for list)\n"
8020 "-cpu cpu select CPU (-cpu ? for list)\n"
8021 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8022 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8023 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8024 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8025 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
8026 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
8027 " [,cache=on|off][,boot=on|off]\n"
8028 " use 'file' as a drive image\n"
8029 "-mtdblock file use 'file' as on-board Flash memory image\n"
8030 "-sd file use 'file' as SecureDigital card image\n"
8031 "-pflash file use 'file' as a parallel flash image\n"
8032 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8033 "-snapshot write to temporary files instead of disk image files\n"
8034 #ifdef CONFIG_SDL
8035 "-no-frame open SDL window without a frame and window decorations\n"
8036 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8037 "-no-quit disable SDL window close capability\n"
8038 #endif
8039 #ifdef TARGET_I386
8040 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8041 #endif
8042 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8043 "-smp n set the number of CPUs to 'n' [default=1]\n"
8044 "-nographic disable graphical output and redirect serial I/Os to console\n"
8045 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8046 #ifndef _WIN32
8047 "-k language use keyboard layout (for example \"fr\" for French)\n"
8048 #endif
8049 #ifdef HAS_AUDIO
8050 "-audio-help print list of audio drivers and their options\n"
8051 "-soundhw c1,... enable audio support\n"
8052 " and only specified sound cards (comma separated list)\n"
8053 " use -soundhw ? to get the list of supported cards\n"
8054 " use -soundhw all to enable all of them\n"
8055 #endif
8056 "-localtime set the real time clock to local time [default=utc]\n"
8057 "-full-screen start in full screen\n"
8058 #ifdef TARGET_I386
8059 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8060 #endif
8061 "-usb enable the USB driver (will be the default soon)\n"
8062 "-usbdevice name add the host or guest USB device 'name'\n"
8063 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8064 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8065 #endif
8066 "-name string set the name of the guest\n"
8067 "\n"
8068 "Network options:\n"
8069 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8070 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8071 #ifdef CONFIG_SLIRP
8072 "-net user[,vlan=n][,hostname=host]\n"
8073 " connect the user mode network stack to VLAN 'n' and send\n"
8074 " hostname 'host' to DHCP clients\n"
8075 #endif
8076 #ifdef _WIN32
8077 "-net tap[,vlan=n],ifname=name\n"
8078 " connect the host TAP network interface to VLAN 'n'\n"
8079 #else
8080 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8081 " connect the host TAP network interface to VLAN 'n' and use the\n"
8082 " network scripts 'file' (default=%s)\n"
8083 " and 'dfile' (default=%s);\n"
8084 " use '[down]script=no' to disable script execution;\n"
8085 " use 'fd=h' to connect to an already opened TAP interface\n"
8086 #endif
8087 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8088 " connect the vlan 'n' to another VLAN using a socket connection\n"
8089 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8090 " connect the vlan 'n' to multicast maddr and port\n"
8091 "-net none use it alone to have zero network devices; if no -net option\n"
8092 " is provided, the default is '-net nic -net user'\n"
8093 "\n"
8094 #ifdef CONFIG_SLIRP
8095 "-tftp dir allow tftp access to files in dir [-net user]\n"
8096 "-bootp file advertise file in BOOTP replies\n"
8097 #ifndef _WIN32
8098 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8099 #endif
8100 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8101 " redirect TCP or UDP connections from host to guest [-net user]\n"
8102 #endif
8103 "\n"
8104 "Linux boot specific:\n"
8105 "-kernel bzImage use 'bzImage' as kernel image\n"
8106 "-append cmdline use 'cmdline' as kernel command line\n"
8107 "-initrd file use 'file' as initial ram disk\n"
8108 "\n"
8109 "Debug/Expert options:\n"
8110 "-monitor dev redirect the monitor to char device 'dev'\n"
8111 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8112 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8113 "-serial dev redirect the serial port to char device 'dev'\n"
8114 "-parallel dev redirect the parallel port to char device 'dev'\n"
8115 "-pidfile file Write PID to 'file'\n"
8116 "-S freeze CPU at startup (use 'c' to start execution)\n"
8117 "-s wait gdb connection to port\n"
8118 "-p port set gdb connection port [default=%s]\n"
8119 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8120 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8121 " translation (t=none or lba) (usually qemu can guess them)\n"
8122 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8123 #ifdef USE_KQEMU
8124 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8125 "-no-kqemu disable KQEMU kernel module usage\n"
8126 #endif
8127 #ifdef USE_KVM
8128 #ifndef NO_CPU_EMULATION
8129 "-no-kvm disable KVM hardware virtualization\n"
8130 #endif
8131 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8132 "-no-kvm-pit disable KVM kernel mode PIT\n"
8133 #endif
8134 #ifdef TARGET_I386
8135 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8136 " (default is CL-GD5446 PCI VGA)\n"
8137 "-no-acpi disable ACPI\n"
8138 #endif
8139 #ifdef CONFIG_CURSES
8140 "-curses use a curses/ncurses interface instead of SDL\n"
8141 #endif
8142 "-no-reboot exit instead of rebooting\n"
8143 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8144 "-vnc display start a VNC server on display\n"
8145 #ifndef _WIN32
8146 "-daemonize daemonize QEMU after initializing\n"
8147 #endif
8148 "-tdf inject timer interrupts that got lost\n"
8149 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8150 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8151 "-option-rom rom load a file, rom, into the option ROM space\n"
8152 #ifdef TARGET_SPARC
8153 "-prom-env variable=value set OpenBIOS nvram variables\n"
8154 #endif
8155 "-clock force the use of the given methods for timer alarm.\n"
8156 " To see what timers are available use -clock help\n"
8157 "-startdate select initial date of the clock\n"
8158 "\n"
8159 "During emulation, the following keys are useful:\n"
8160 "ctrl-alt-f toggle full screen\n"
8161 "ctrl-alt-n switch to virtual console 'n'\n"
8162 "ctrl-alt toggle mouse and keyboard grab\n"
8163 "\n"
8164 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8166 "qemu",
8167 DEFAULT_RAM_SIZE,
8168 #ifndef _WIN32
8169 DEFAULT_NETWORK_SCRIPT,
8170 DEFAULT_NETWORK_DOWN_SCRIPT,
8171 #endif
8172 DEFAULT_GDBSTUB_PORT,
8173 "/tmp/qemu.log");
8174 exit(exitcode);
8177 #define HAS_ARG 0x0001
8179 enum {
8180 QEMU_OPTION_h,
8182 QEMU_OPTION_M,
8183 QEMU_OPTION_cpu,
8184 QEMU_OPTION_fda,
8185 QEMU_OPTION_fdb,
8186 QEMU_OPTION_hda,
8187 QEMU_OPTION_hdb,
8188 QEMU_OPTION_hdc,
8189 QEMU_OPTION_hdd,
8190 QEMU_OPTION_drive,
8191 QEMU_OPTION_cdrom,
8192 QEMU_OPTION_mtdblock,
8193 QEMU_OPTION_sd,
8194 QEMU_OPTION_pflash,
8195 QEMU_OPTION_boot,
8196 QEMU_OPTION_snapshot,
8197 #ifdef TARGET_I386
8198 QEMU_OPTION_no_fd_bootchk,
8199 #endif
8200 QEMU_OPTION_m,
8201 QEMU_OPTION_nographic,
8202 QEMU_OPTION_portrait,
8203 #ifdef HAS_AUDIO
8204 QEMU_OPTION_audio_help,
8205 QEMU_OPTION_soundhw,
8206 #endif
8208 QEMU_OPTION_net,
8209 QEMU_OPTION_tftp,
8210 QEMU_OPTION_bootp,
8211 QEMU_OPTION_smb,
8212 QEMU_OPTION_redir,
8214 QEMU_OPTION_kernel,
8215 QEMU_OPTION_append,
8216 QEMU_OPTION_initrd,
8218 QEMU_OPTION_S,
8219 QEMU_OPTION_s,
8220 QEMU_OPTION_p,
8221 QEMU_OPTION_d,
8222 QEMU_OPTION_hdachs,
8223 QEMU_OPTION_L,
8224 QEMU_OPTION_bios,
8225 QEMU_OPTION_no_code_copy,
8226 QEMU_OPTION_k,
8227 QEMU_OPTION_localtime,
8228 QEMU_OPTION_cirrusvga,
8229 QEMU_OPTION_vmsvga,
8230 QEMU_OPTION_g,
8231 QEMU_OPTION_std_vga,
8232 QEMU_OPTION_echr,
8233 QEMU_OPTION_monitor,
8234 QEMU_OPTION_balloon,
8235 QEMU_OPTION_vmchannel,
8236 QEMU_OPTION_serial,
8237 QEMU_OPTION_parallel,
8238 QEMU_OPTION_loadvm,
8239 QEMU_OPTION_full_screen,
8240 QEMU_OPTION_no_frame,
8241 QEMU_OPTION_alt_grab,
8242 QEMU_OPTION_no_quit,
8243 QEMU_OPTION_pidfile,
8244 QEMU_OPTION_no_kqemu,
8245 QEMU_OPTION_kernel_kqemu,
8246 QEMU_OPTION_win2k_hack,
8247 QEMU_OPTION_usb,
8248 QEMU_OPTION_usbdevice,
8249 QEMU_OPTION_smp,
8250 QEMU_OPTION_vnc,
8251 QEMU_OPTION_no_acpi,
8252 QEMU_OPTION_curses,
8253 QEMU_OPTION_no_kvm,
8254 QEMU_OPTION_no_kvm_irqchip,
8255 QEMU_OPTION_no_kvm_pit,
8256 QEMU_OPTION_no_reboot,
8257 QEMU_OPTION_show_cursor,
8258 QEMU_OPTION_daemonize,
8259 QEMU_OPTION_option_rom,
8260 QEMU_OPTION_semihosting,
8261 QEMU_OPTION_cpu_vendor,
8262 QEMU_OPTION_name,
8263 QEMU_OPTION_prom_env,
8264 QEMU_OPTION_old_param,
8265 QEMU_OPTION_clock,
8266 QEMU_OPTION_startdate,
8267 QEMU_OPTION_translation,
8268 QEMU_OPTION_incoming,
8269 QEMU_OPTION_tdf,
8270 QEMU_OPTION_kvm_shadow_memory,
8271 QEMU_OPTION_mempath,
8274 typedef struct QEMUOption {
8275 const char *name;
8276 int flags;
8277 int index;
8278 } QEMUOption;
8280 const QEMUOption qemu_options[] = {
8281 { "h", 0, QEMU_OPTION_h },
8282 { "help", 0, QEMU_OPTION_h },
8284 { "M", HAS_ARG, QEMU_OPTION_M },
8285 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8286 { "fda", HAS_ARG, QEMU_OPTION_fda },
8287 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8288 { "hda", HAS_ARG, QEMU_OPTION_hda },
8289 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8290 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8291 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8292 { "drive", HAS_ARG, QEMU_OPTION_drive },
8293 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8294 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8295 { "sd", HAS_ARG, QEMU_OPTION_sd },
8296 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8297 { "boot", HAS_ARG, QEMU_OPTION_boot },
8298 { "snapshot", 0, QEMU_OPTION_snapshot },
8299 #ifdef TARGET_I386
8300 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8301 #endif
8302 { "m", HAS_ARG, QEMU_OPTION_m },
8303 { "nographic", 0, QEMU_OPTION_nographic },
8304 { "portrait", 0, QEMU_OPTION_portrait },
8305 { "k", HAS_ARG, QEMU_OPTION_k },
8306 #ifdef HAS_AUDIO
8307 { "audio-help", 0, QEMU_OPTION_audio_help },
8308 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8309 #endif
8311 { "net", HAS_ARG, QEMU_OPTION_net},
8312 #ifdef CONFIG_SLIRP
8313 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8314 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8315 #ifndef _WIN32
8316 { "smb", HAS_ARG, QEMU_OPTION_smb },
8317 #endif
8318 { "redir", HAS_ARG, QEMU_OPTION_redir },
8319 #endif
8321 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8322 { "append", HAS_ARG, QEMU_OPTION_append },
8323 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8325 { "S", 0, QEMU_OPTION_S },
8326 { "s", 0, QEMU_OPTION_s },
8327 { "p", HAS_ARG, QEMU_OPTION_p },
8328 { "d", HAS_ARG, QEMU_OPTION_d },
8329 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8330 { "L", HAS_ARG, QEMU_OPTION_L },
8331 { "bios", HAS_ARG, QEMU_OPTION_bios },
8332 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8333 #ifdef USE_KQEMU
8334 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8335 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8336 #endif
8337 #ifdef USE_KVM
8338 #ifndef NO_CPU_EMULATION
8339 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8340 #endif
8341 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8342 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8343 #endif
8344 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8345 { "g", 1, QEMU_OPTION_g },
8346 #endif
8347 { "localtime", 0, QEMU_OPTION_localtime },
8348 { "std-vga", 0, QEMU_OPTION_std_vga },
8349 { "monitor", 1, QEMU_OPTION_monitor },
8350 { "balloon", 1, QEMU_OPTION_balloon },
8351 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8352 { "echr", HAS_ARG, QEMU_OPTION_echr },
8353 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8354 { "serial", HAS_ARG, QEMU_OPTION_serial },
8355 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8356 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8357 { "incoming", 1, QEMU_OPTION_incoming },
8358 { "full-screen", 0, QEMU_OPTION_full_screen },
8359 #ifdef CONFIG_SDL
8360 { "no-frame", 0, QEMU_OPTION_no_frame },
8361 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8362 { "no-quit", 0, QEMU_OPTION_no_quit },
8363 #endif
8364 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8365 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8366 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8367 { "smp", HAS_ARG, QEMU_OPTION_smp },
8368 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8369 #ifdef CONFIG_CURSES
8370 { "curses", 0, QEMU_OPTION_curses },
8371 #endif
8373 /* temporary options */
8374 { "usb", 0, QEMU_OPTION_usb },
8375 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8376 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8377 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8378 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8379 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8380 { "daemonize", 0, QEMU_OPTION_daemonize },
8381 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8382 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8383 { "semihosting", 0, QEMU_OPTION_semihosting },
8384 #endif
8385 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8386 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8387 { "name", HAS_ARG, QEMU_OPTION_name },
8388 #if defined(TARGET_SPARC)
8389 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8390 #endif
8391 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8392 #if defined(TARGET_ARM)
8393 { "old-param", 0, QEMU_OPTION_old_param },
8394 #endif
8395 { "clock", HAS_ARG, QEMU_OPTION_clock },
8396 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8397 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8398 { NULL },
8401 /* password input */
8403 int qemu_key_check(BlockDriverState *bs, const char *name)
8405 char password[256];
8406 int i;
8408 if (!bdrv_is_encrypted(bs))
8409 return 0;
8411 term_printf("%s is encrypted.\n", name);
8412 for(i = 0; i < 3; i++) {
8413 monitor_readline("Password: ", 1, password, sizeof(password));
8414 if (bdrv_set_key(bs, password) == 0)
8415 return 0;
8416 term_printf("invalid password\n");
8418 return -EPERM;
8421 static BlockDriverState *get_bdrv(int index)
8423 if (index > nb_drives)
8424 return NULL;
8425 return drives_table[index].bdrv;
8428 static void read_passwords(void)
8430 BlockDriverState *bs;
8431 int i;
8433 for(i = 0; i < 6; i++) {
8434 bs = get_bdrv(i);
8435 if (bs)
8436 qemu_key_check(bs, bdrv_get_device_name(bs));
8440 /* XXX: currently we cannot use simultaneously different CPUs */
8441 static void register_machines(void)
8443 #if defined(TARGET_I386)
8444 qemu_register_machine(&pc_machine);
8445 qemu_register_machine(&isapc_machine);
8446 #elif defined(TARGET_PPC)
8447 qemu_register_machine(&heathrow_machine);
8448 qemu_register_machine(&core99_machine);
8449 qemu_register_machine(&prep_machine);
8450 qemu_register_machine(&ref405ep_machine);
8451 qemu_register_machine(&taihu_machine);
8452 qemu_register_machine(&bamboo_machine);
8453 #elif defined(TARGET_MIPS)
8454 qemu_register_machine(&mips_machine);
8455 qemu_register_machine(&mips_malta_machine);
8456 qemu_register_machine(&mips_pica61_machine);
8457 qemu_register_machine(&mips_mipssim_machine);
8458 #elif defined(TARGET_SPARC)
8459 #ifdef TARGET_SPARC64
8460 qemu_register_machine(&sun4u_machine);
8461 #else
8462 qemu_register_machine(&ss5_machine);
8463 qemu_register_machine(&ss10_machine);
8464 qemu_register_machine(&ss600mp_machine);
8465 qemu_register_machine(&ss20_machine);
8466 qemu_register_machine(&ss2_machine);
8467 qemu_register_machine(&ss1000_machine);
8468 qemu_register_machine(&ss2000_machine);
8469 #endif
8470 #elif defined(TARGET_ARM)
8471 qemu_register_machine(&integratorcp_machine);
8472 qemu_register_machine(&versatilepb_machine);
8473 qemu_register_machine(&versatileab_machine);
8474 qemu_register_machine(&realview_machine);
8475 qemu_register_machine(&akitapda_machine);
8476 qemu_register_machine(&spitzpda_machine);
8477 qemu_register_machine(&borzoipda_machine);
8478 qemu_register_machine(&terrierpda_machine);
8479 qemu_register_machine(&palmte_machine);
8480 qemu_register_machine(&lm3s811evb_machine);
8481 qemu_register_machine(&lm3s6965evb_machine);
8482 qemu_register_machine(&connex_machine);
8483 qemu_register_machine(&verdex_machine);
8484 qemu_register_machine(&mainstone2_machine);
8485 #elif defined(TARGET_SH4)
8486 qemu_register_machine(&shix_machine);
8487 qemu_register_machine(&r2d_machine);
8488 #elif defined(TARGET_ALPHA)
8489 /* XXX: TODO */
8490 #elif defined(TARGET_M68K)
8491 qemu_register_machine(&mcf5208evb_machine);
8492 qemu_register_machine(&an5206_machine);
8493 qemu_register_machine(&dummy_m68k_machine);
8494 #elif defined(TARGET_CRIS)
8495 qemu_register_machine(&bareetraxfs_machine);
8496 #elif defined(TARGET_IA64)
8497 qemu_register_machine(&ipf_machine);
8498 #else
8499 #error unsupported CPU
8500 #endif
8503 #ifdef HAS_AUDIO
8504 struct soundhw soundhw[] = {
8505 #ifdef HAS_AUDIO_CHOICE
8506 #ifdef TARGET_I386
8508 "pcspk",
8509 "PC speaker",
8512 { .init_isa = pcspk_audio_init }
8514 #endif
8516 "sb16",
8517 "Creative Sound Blaster 16",
8520 { .init_isa = SB16_init }
8523 #ifdef CONFIG_ADLIB
8525 "adlib",
8526 #ifdef HAS_YMF262
8527 "Yamaha YMF262 (OPL3)",
8528 #else
8529 "Yamaha YM3812 (OPL2)",
8530 #endif
8533 { .init_isa = Adlib_init }
8535 #endif
8537 #ifdef CONFIG_GUS
8539 "gus",
8540 "Gravis Ultrasound GF1",
8543 { .init_isa = GUS_init }
8545 #endif
8547 #ifdef CONFIG_AC97
8549 "ac97",
8550 "Intel 82801AA AC97 Audio",
8553 { .init_pci = ac97_init }
8555 #endif
8558 "es1370",
8559 "ENSONIQ AudioPCI ES1370",
8562 { .init_pci = es1370_init }
8564 #endif
8566 { NULL, NULL, 0, 0, { NULL } }
8569 static void select_soundhw (const char *optarg)
8571 struct soundhw *c;
8573 if (*optarg == '?') {
8574 show_valid_cards:
8576 printf ("Valid sound card names (comma separated):\n");
8577 for (c = soundhw; c->name; ++c) {
8578 printf ("%-11s %s\n", c->name, c->descr);
8580 printf ("\n-soundhw all will enable all of the above\n");
8581 exit (*optarg != '?');
8583 else {
8584 size_t l;
8585 const char *p;
8586 char *e;
8587 int bad_card = 0;
8589 if (!strcmp (optarg, "all")) {
8590 for (c = soundhw; c->name; ++c) {
8591 c->enabled = 1;
8593 return;
8596 p = optarg;
8597 while (*p) {
8598 e = strchr (p, ',');
8599 l = !e ? strlen (p) : (size_t) (e - p);
8601 for (c = soundhw; c->name; ++c) {
8602 if (!strncmp (c->name, p, l)) {
8603 c->enabled = 1;
8604 break;
8608 if (!c->name) {
8609 if (l > 80) {
8610 fprintf (stderr,
8611 "Unknown sound card name (too big to show)\n");
8613 else {
8614 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8615 (int) l, p);
8617 bad_card = 1;
8619 p += l + (e != NULL);
8622 if (bad_card)
8623 goto show_valid_cards;
8626 #endif
8628 #ifdef _WIN32
8629 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8631 exit(STATUS_CONTROL_C_EXIT);
8632 return TRUE;
8634 #endif
8636 #define MAX_NET_CLIENTS 32
8638 static int saved_argc;
8639 static char **saved_argv;
8641 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8643 *argc = saved_argc;
8644 *argv = saved_argv;
8645 *opt_daemonize = daemonize;
8646 *opt_incoming = incoming;
8650 static int gethugepagesize(void)
8652 int ret, fd;
8653 char buf[4096];
8654 char *needle = "Hugepagesize:";
8655 char *size;
8656 unsigned long hugepagesize;
8658 fd = open("/proc/meminfo", O_RDONLY);
8659 if (fd < 0) {
8660 perror("open");
8661 exit(0);
8664 ret = read(fd, buf, sizeof(buf));
8665 if (ret < 0) {
8666 perror("read");
8667 exit(0);
8670 size = strstr(buf, needle);
8671 if (!size)
8672 return 0;
8673 size += strlen(needle);
8674 hugepagesize = strtol(size, NULL, 0);
8675 return hugepagesize;
8678 void *alloc_mem_area(unsigned long memory, const char *path)
8680 char *filename;
8681 void *area;
8682 int fd;
8684 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8685 return NULL;
8687 hpagesize = gethugepagesize() * 1024;
8688 if (!hpagesize)
8689 return NULL;
8691 fd = mkstemp(filename);
8692 if (fd < 0) {
8693 perror("mkstemp");
8694 free(filename);
8695 return NULL;
8697 unlink(filename);
8698 free(filename);
8700 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8702 if (ftruncate(fd, memory) == -1) {
8703 perror("ftruncate");
8704 close(fd);
8705 return NULL;
8708 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8709 if (area == MAP_FAILED) {
8710 perror("mmap");
8711 close(fd);
8712 return NULL;
8715 return area;
8718 void *qemu_alloc_physram(unsigned long memory)
8720 void *area = NULL;
8722 if (mem_path)
8723 area = alloc_mem_area(memory, mem_path);
8724 if (!area)
8725 area = qemu_vmalloc(memory);
8727 return area;
8730 int main(int argc, char **argv)
8732 #ifdef CONFIG_GDBSTUB
8733 int use_gdbstub;
8734 const char *gdbstub_port;
8735 #endif
8736 uint32_t boot_devices_bitmap = 0;
8737 int i;
8738 int snapshot, linux_boot, net_boot;
8739 const char *initrd_filename;
8740 const char *kernel_filename, *kernel_cmdline;
8741 const char *boot_devices = "";
8742 DisplayState *ds = &display_state;
8743 int cyls, heads, secs, translation;
8744 char net_clients[MAX_NET_CLIENTS][256];
8745 int nb_net_clients;
8746 int hda_index;
8747 int optind;
8748 const char *r, *optarg;
8749 CharDriverState *monitor_hd;
8750 char monitor_device[128];
8751 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8752 int vmchannel_device_index;
8753 char serial_devices[MAX_SERIAL_PORTS][128];
8754 int serial_device_index;
8755 char parallel_devices[MAX_PARALLEL_PORTS][128];
8756 int parallel_device_index;
8757 const char *loadvm = NULL;
8758 QEMUMachine *machine;
8759 const char *cpu_model;
8760 char usb_devices[MAX_USB_CMDLINE][128];
8761 int usb_devices_index;
8762 int fds[2];
8763 const char *pid_file = NULL;
8764 VLANState *vlan;
8766 saved_argc = argc;
8767 saved_argv = argv;
8769 LIST_INIT (&vm_change_state_head);
8770 #ifndef _WIN32
8772 struct sigaction act;
8773 sigfillset(&act.sa_mask);
8774 act.sa_flags = 0;
8775 act.sa_handler = SIG_IGN;
8776 sigaction(SIGPIPE, &act, NULL);
8778 #else
8779 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8780 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8781 QEMU to run on a single CPU */
8783 HANDLE h;
8784 DWORD mask, smask;
8785 int i;
8786 h = GetCurrentProcess();
8787 if (GetProcessAffinityMask(h, &mask, &smask)) {
8788 for(i = 0; i < 32; i++) {
8789 if (mask & (1 << i))
8790 break;
8792 if (i != 32) {
8793 mask = 1 << i;
8794 SetProcessAffinityMask(h, mask);
8798 #endif
8800 register_machines();
8801 machine = first_machine;
8802 cpu_model = NULL;
8803 initrd_filename = NULL;
8804 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8805 vga_ram_size = VGA_RAM_SIZE;
8806 #ifdef CONFIG_GDBSTUB
8807 use_gdbstub = 0;
8808 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8809 #endif
8810 snapshot = 0;
8811 nographic = 0;
8812 curses = 0;
8813 kernel_filename = NULL;
8814 kernel_cmdline = "";
8815 cyls = heads = secs = 0;
8816 translation = BIOS_ATA_TRANSLATION_AUTO;
8817 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8819 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8820 vmchannel_devices[i][0] = '\0';
8821 vmchannel_device_index = 0;
8823 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8824 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8825 serial_devices[i][0] = '\0';
8826 serial_device_index = 0;
8828 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8829 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8830 parallel_devices[i][0] = '\0';
8831 parallel_device_index = 0;
8833 usb_devices_index = 0;
8835 nb_net_clients = 0;
8836 nb_drives = 0;
8837 nb_drives_opt = 0;
8838 hda_index = -1;
8840 nb_nics = 0;
8841 /* default mac address of the first network interface */
8843 optind = 1;
8844 for(;;) {
8845 if (optind >= argc)
8846 break;
8847 r = argv[optind];
8848 if (r[0] != '-') {
8849 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8850 } else {
8851 const QEMUOption *popt;
8853 optind++;
8854 /* Treat --foo the same as -foo. */
8855 if (r[1] == '-')
8856 r++;
8857 popt = qemu_options;
8858 for(;;) {
8859 if (!popt->name) {
8860 fprintf(stderr, "%s: invalid option -- '%s'\n",
8861 argv[0], r);
8862 exit(1);
8864 if (!strcmp(popt->name, r + 1))
8865 break;
8866 popt++;
8868 if (popt->flags & HAS_ARG) {
8869 if (optind >= argc) {
8870 fprintf(stderr, "%s: option '%s' requires an argument\n",
8871 argv[0], r);
8872 exit(1);
8874 optarg = argv[optind++];
8875 } else {
8876 optarg = NULL;
8879 switch(popt->index) {
8880 case QEMU_OPTION_M:
8881 machine = find_machine(optarg);
8882 if (!machine) {
8883 QEMUMachine *m;
8884 printf("Supported machines are:\n");
8885 for(m = first_machine; m != NULL; m = m->next) {
8886 printf("%-10s %s%s\n",
8887 m->name, m->desc,
8888 m == first_machine ? " (default)" : "");
8890 exit(*optarg != '?');
8892 break;
8893 case QEMU_OPTION_cpu:
8894 /* hw initialization will check this */
8895 if (*optarg == '?') {
8896 /* XXX: implement xxx_cpu_list for targets that still miss it */
8897 #if defined(cpu_list)
8898 cpu_list(stdout, &fprintf);
8899 #endif
8900 exit(0);
8901 } else {
8902 cpu_model = optarg;
8904 break;
8905 case QEMU_OPTION_initrd:
8906 initrd_filename = optarg;
8907 break;
8908 case QEMU_OPTION_hda:
8909 if (cyls == 0)
8910 hda_index = drive_add(optarg, HD_ALIAS, 0);
8911 else
8912 hda_index = drive_add(optarg, HD_ALIAS
8913 ",cyls=%d,heads=%d,secs=%d%s",
8914 0, cyls, heads, secs,
8915 translation == BIOS_ATA_TRANSLATION_LBA ?
8916 ",trans=lba" :
8917 translation == BIOS_ATA_TRANSLATION_NONE ?
8918 ",trans=none" : "");
8919 break;
8920 case QEMU_OPTION_hdb:
8921 case QEMU_OPTION_hdc:
8922 case QEMU_OPTION_hdd:
8923 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8924 break;
8925 case QEMU_OPTION_drive:
8926 drive_add(NULL, "%s", optarg);
8927 break;
8928 case QEMU_OPTION_mtdblock:
8929 drive_add(optarg, MTD_ALIAS);
8930 break;
8931 case QEMU_OPTION_sd:
8932 drive_add(optarg, SD_ALIAS);
8933 break;
8934 case QEMU_OPTION_pflash:
8935 drive_add(optarg, PFLASH_ALIAS);
8936 break;
8937 case QEMU_OPTION_snapshot:
8938 snapshot = 1;
8939 break;
8940 case QEMU_OPTION_hdachs:
8942 const char *p;
8943 p = optarg;
8944 cyls = strtol(p, (char **)&p, 0);
8945 if (cyls < 1 || cyls > 16383)
8946 goto chs_fail;
8947 if (*p != ',')
8948 goto chs_fail;
8949 p++;
8950 heads = strtol(p, (char **)&p, 0);
8951 if (heads < 1 || heads > 16)
8952 goto chs_fail;
8953 if (*p != ',')
8954 goto chs_fail;
8955 p++;
8956 secs = strtol(p, (char **)&p, 0);
8957 if (secs < 1 || secs > 63)
8958 goto chs_fail;
8959 if (*p == ',') {
8960 p++;
8961 if (!strcmp(p, "none"))
8962 translation = BIOS_ATA_TRANSLATION_NONE;
8963 else if (!strcmp(p, "lba"))
8964 translation = BIOS_ATA_TRANSLATION_LBA;
8965 else if (!strcmp(p, "auto"))
8966 translation = BIOS_ATA_TRANSLATION_AUTO;
8967 else
8968 goto chs_fail;
8969 } else if (*p != '\0') {
8970 chs_fail:
8971 fprintf(stderr, "qemu: invalid physical CHS format\n");
8972 exit(1);
8974 if (hda_index != -1)
8975 snprintf(drives_opt[hda_index].opt,
8976 sizeof(drives_opt[hda_index].opt),
8977 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8978 0, cyls, heads, secs,
8979 translation == BIOS_ATA_TRANSLATION_LBA ?
8980 ",trans=lba" :
8981 translation == BIOS_ATA_TRANSLATION_NONE ?
8982 ",trans=none" : "");
8984 break;
8985 case QEMU_OPTION_nographic:
8986 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8987 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8988 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8989 nographic = 1;
8990 break;
8991 #ifdef CONFIG_CURSES
8992 case QEMU_OPTION_curses:
8993 curses = 1;
8994 break;
8995 #endif
8996 case QEMU_OPTION_portrait:
8997 graphic_rotate = 1;
8998 break;
8999 case QEMU_OPTION_kernel:
9000 kernel_filename = optarg;
9001 break;
9002 case QEMU_OPTION_append:
9003 kernel_cmdline = optarg;
9004 break;
9005 case QEMU_OPTION_cdrom:
9006 drive_add(optarg, CDROM_ALIAS);
9007 break;
9008 case QEMU_OPTION_boot:
9009 boot_devices = optarg;
9010 /* We just do some generic consistency checks */
9012 /* Could easily be extended to 64 devices if needed */
9013 const char *p;
9015 boot_devices_bitmap = 0;
9016 for (p = boot_devices; *p != '\0'; p++) {
9017 /* Allowed boot devices are:
9018 * a b : floppy disk drives
9019 * c ... f : IDE disk drives
9020 * g ... m : machine implementation dependant drives
9021 * n ... p : network devices
9022 * It's up to each machine implementation to check
9023 * if the given boot devices match the actual hardware
9024 * implementation and firmware features.
9026 if (*p < 'a' || *p > 'q') {
9027 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9028 exit(1);
9030 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9031 fprintf(stderr,
9032 "Boot device '%c' was given twice\n",*p);
9033 exit(1);
9035 boot_devices_bitmap |= 1 << (*p - 'a');
9038 break;
9039 case QEMU_OPTION_fda:
9040 case QEMU_OPTION_fdb:
9041 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9042 break;
9043 #ifdef TARGET_I386
9044 case QEMU_OPTION_no_fd_bootchk:
9045 fd_bootchk = 0;
9046 break;
9047 #endif
9048 case QEMU_OPTION_no_code_copy:
9049 code_copy_enabled = 0;
9050 break;
9051 case QEMU_OPTION_net:
9052 if (nb_net_clients >= MAX_NET_CLIENTS) {
9053 fprintf(stderr, "qemu: too many network clients\n");
9054 exit(1);
9056 pstrcpy(net_clients[nb_net_clients],
9057 sizeof(net_clients[0]),
9058 optarg);
9059 nb_net_clients++;
9060 break;
9061 #ifdef CONFIG_SLIRP
9062 case QEMU_OPTION_tftp:
9063 tftp_prefix = optarg;
9064 break;
9065 case QEMU_OPTION_bootp:
9066 bootp_filename = optarg;
9067 break;
9068 #ifndef _WIN32
9069 case QEMU_OPTION_smb:
9070 net_slirp_smb(optarg);
9071 break;
9072 #endif
9073 case QEMU_OPTION_redir:
9074 net_slirp_redir(optarg);
9075 break;
9076 #endif
9077 #ifdef HAS_AUDIO
9078 case QEMU_OPTION_audio_help:
9079 AUD_help ();
9080 exit (0);
9081 break;
9082 case QEMU_OPTION_soundhw:
9083 select_soundhw (optarg);
9084 break;
9085 #endif
9086 case QEMU_OPTION_h:
9087 help(0);
9088 break;
9089 case QEMU_OPTION_m:
9090 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9091 if (ram_size <= 0)
9092 help(1);
9093 if (ram_size > PHYS_RAM_MAX_SIZE) {
9094 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9095 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9096 exit(1);
9098 break;
9099 case QEMU_OPTION_d:
9101 int mask;
9102 CPULogItem *item;
9104 mask = cpu_str_to_log_mask(optarg);
9105 if (!mask) {
9106 printf("Log items (comma separated):\n");
9107 for(item = cpu_log_items; item->mask != 0; item++) {
9108 printf("%-10s %s\n", item->name, item->help);
9110 exit(1);
9112 cpu_set_log(mask);
9114 break;
9115 #ifdef CONFIG_GDBSTUB
9116 case QEMU_OPTION_s:
9117 use_gdbstub = 1;
9118 break;
9119 case QEMU_OPTION_p:
9120 gdbstub_port = optarg;
9121 break;
9122 #endif
9123 case QEMU_OPTION_L:
9124 bios_dir = optarg;
9125 break;
9126 case QEMU_OPTION_bios:
9127 bios_name = optarg;
9128 break;
9129 case QEMU_OPTION_S:
9130 autostart = 0;
9131 break;
9132 case QEMU_OPTION_k:
9133 keyboard_layout = optarg;
9134 break;
9135 case QEMU_OPTION_localtime:
9136 rtc_utc = 0;
9137 break;
9138 case QEMU_OPTION_cirrusvga:
9139 cirrus_vga_enabled = 1;
9140 vmsvga_enabled = 0;
9141 break;
9142 case QEMU_OPTION_vmsvga:
9143 cirrus_vga_enabled = 0;
9144 vmsvga_enabled = 1;
9145 break;
9146 case QEMU_OPTION_std_vga:
9147 cirrus_vga_enabled = 0;
9148 vmsvga_enabled = 0;
9149 break;
9150 case QEMU_OPTION_g:
9152 const char *p;
9153 int w, h, depth;
9154 p = optarg;
9155 w = strtol(p, (char **)&p, 10);
9156 if (w <= 0) {
9157 graphic_error:
9158 fprintf(stderr, "qemu: invalid resolution or depth\n");
9159 exit(1);
9161 if (*p != 'x')
9162 goto graphic_error;
9163 p++;
9164 h = strtol(p, (char **)&p, 10);
9165 if (h <= 0)
9166 goto graphic_error;
9167 if (*p == 'x') {
9168 p++;
9169 depth = strtol(p, (char **)&p, 10);
9170 if (depth != 8 && depth != 15 && depth != 16 &&
9171 depth != 24 && depth != 32)
9172 goto graphic_error;
9173 } else if (*p == '\0') {
9174 depth = graphic_depth;
9175 } else {
9176 goto graphic_error;
9179 graphic_width = w;
9180 graphic_height = h;
9181 graphic_depth = depth;
9183 break;
9184 case QEMU_OPTION_echr:
9186 char *r;
9187 term_escape_char = strtol(optarg, &r, 0);
9188 if (r == optarg)
9189 printf("Bad argument to echr\n");
9190 break;
9192 case QEMU_OPTION_monitor:
9193 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9194 break;
9195 case QEMU_OPTION_balloon:
9196 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9197 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9198 exit(1);
9200 if (balloon_used) {
9201 fprintf(stderr, "qemu: only one balloon device can be used\n");
9202 exit(1);
9204 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9205 vmchannel_device_index++;
9206 balloon_used = 1;
9207 break;
9208 case QEMU_OPTION_vmchannel:
9209 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9210 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9211 exit(1);
9213 pstrcpy(vmchannel_devices[vmchannel_device_index],
9214 sizeof(vmchannel_devices[0]), optarg);
9215 vmchannel_device_index++;
9216 break;
9217 case QEMU_OPTION_serial:
9218 if (serial_device_index >= MAX_SERIAL_PORTS) {
9219 fprintf(stderr, "qemu: too many serial ports\n");
9220 exit(1);
9222 pstrcpy(serial_devices[serial_device_index],
9223 sizeof(serial_devices[0]), optarg);
9224 serial_device_index++;
9225 break;
9226 case QEMU_OPTION_parallel:
9227 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9228 fprintf(stderr, "qemu: too many parallel ports\n");
9229 exit(1);
9231 pstrcpy(parallel_devices[parallel_device_index],
9232 sizeof(parallel_devices[0]), optarg);
9233 parallel_device_index++;
9234 break;
9235 case QEMU_OPTION_loadvm:
9236 loadvm = optarg;
9237 break;
9238 case QEMU_OPTION_incoming:
9239 incoming = optarg;
9240 break;
9241 case QEMU_OPTION_full_screen:
9242 full_screen = 1;
9243 break;
9244 #ifdef CONFIG_SDL
9245 case QEMU_OPTION_no_frame:
9246 no_frame = 1;
9247 break;
9248 case QEMU_OPTION_alt_grab:
9249 alt_grab = 1;
9250 break;
9251 case QEMU_OPTION_no_quit:
9252 no_quit = 1;
9253 break;
9254 #endif
9255 case QEMU_OPTION_pidfile:
9256 pid_file = optarg;
9257 break;
9258 #ifdef TARGET_I386
9259 case QEMU_OPTION_win2k_hack:
9260 win2k_install_hack = 1;
9261 break;
9262 #endif
9263 #ifdef USE_KQEMU
9264 case QEMU_OPTION_no_kqemu:
9265 kqemu_allowed = 0;
9266 break;
9267 case QEMU_OPTION_kernel_kqemu:
9268 kqemu_allowed = 2;
9269 break;
9270 #endif
9271 #ifdef USE_KVM
9272 case QEMU_OPTION_no_kvm:
9273 kvm_allowed = 0;
9274 break;
9275 case QEMU_OPTION_no_kvm_irqchip: {
9276 extern int kvm_irqchip, kvm_pit;
9277 kvm_irqchip = 0;
9278 kvm_pit = 0;
9279 break;
9281 case QEMU_OPTION_no_kvm_pit: {
9282 extern int kvm_pit;
9283 kvm_pit = 0;
9284 break;
9286 #endif
9287 case QEMU_OPTION_usb:
9288 usb_enabled = 1;
9289 break;
9290 case QEMU_OPTION_usbdevice:
9291 usb_enabled = 1;
9292 if (usb_devices_index >= MAX_USB_CMDLINE) {
9293 fprintf(stderr, "Too many USB devices\n");
9294 exit(1);
9296 pstrcpy(usb_devices[usb_devices_index],
9297 sizeof(usb_devices[usb_devices_index]),
9298 optarg);
9299 usb_devices_index++;
9300 break;
9301 case QEMU_OPTION_smp:
9302 smp_cpus = atoi(optarg);
9303 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9304 fprintf(stderr, "Invalid number of CPUs\n");
9305 exit(1);
9307 break;
9308 case QEMU_OPTION_vnc:
9309 vnc_display = optarg;
9310 break;
9311 case QEMU_OPTION_no_acpi:
9312 acpi_enabled = 0;
9313 break;
9314 case QEMU_OPTION_no_reboot:
9315 no_reboot = 1;
9316 break;
9317 case QEMU_OPTION_show_cursor:
9318 cursor_hide = 0;
9319 break;
9320 case QEMU_OPTION_daemonize:
9321 daemonize = 1;
9322 break;
9323 case QEMU_OPTION_option_rom:
9324 if (nb_option_roms >= MAX_OPTION_ROMS) {
9325 fprintf(stderr, "Too many option ROMs\n");
9326 exit(1);
9328 option_rom[nb_option_roms] = optarg;
9329 nb_option_roms++;
9330 break;
9331 case QEMU_OPTION_semihosting:
9332 semihosting_enabled = 1;
9333 break;
9334 case QEMU_OPTION_tdf:
9335 time_drift_fix = 1;
9336 break;
9337 case QEMU_OPTION_kvm_shadow_memory:
9338 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9339 break;
9340 case QEMU_OPTION_mempath:
9341 mem_path = optarg;
9342 break;
9343 case QEMU_OPTION_name:
9344 qemu_name = optarg;
9345 break;
9346 #ifdef TARGET_SPARC
9347 case QEMU_OPTION_prom_env:
9348 if (nb_prom_envs >= MAX_PROM_ENVS) {
9349 fprintf(stderr, "Too many prom variables\n");
9350 exit(1);
9352 prom_envs[nb_prom_envs] = optarg;
9353 nb_prom_envs++;
9354 break;
9355 #endif
9356 case QEMU_OPTION_cpu_vendor:
9357 cpu_vendor_string = optarg;
9358 break;
9359 #ifdef TARGET_ARM
9360 case QEMU_OPTION_old_param:
9361 old_param = 1;
9362 break;
9363 #endif
9364 case QEMU_OPTION_clock:
9365 configure_alarms(optarg);
9366 break;
9367 case QEMU_OPTION_startdate:
9369 struct tm tm;
9370 time_t rtc_start_date;
9371 if (!strcmp(optarg, "now")) {
9372 rtc_date_offset = -1;
9373 } else {
9374 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9375 &tm.tm_year,
9376 &tm.tm_mon,
9377 &tm.tm_mday,
9378 &tm.tm_hour,
9379 &tm.tm_min,
9380 &tm.tm_sec) == 6) {
9381 /* OK */
9382 } else if (sscanf(optarg, "%d-%d-%d",
9383 &tm.tm_year,
9384 &tm.tm_mon,
9385 &tm.tm_mday) == 3) {
9386 tm.tm_hour = 0;
9387 tm.tm_min = 0;
9388 tm.tm_sec = 0;
9389 } else {
9390 goto date_fail;
9392 tm.tm_year -= 1900;
9393 tm.tm_mon--;
9394 rtc_start_date = mktimegm(&tm);
9395 if (rtc_start_date == -1) {
9396 date_fail:
9397 fprintf(stderr, "Invalid date format. Valid format are:\n"
9398 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9399 exit(1);
9401 rtc_date_offset = time(NULL) - rtc_start_date;
9404 break;
9409 #ifndef _WIN32
9410 if (daemonize) {
9411 pid_t pid;
9413 if (pipe(fds) == -1)
9414 exit(1);
9416 pid = fork();
9417 if (pid > 0) {
9418 uint8_t status;
9419 ssize_t len;
9421 close(fds[1]);
9423 again:
9424 len = read(fds[0], &status, 1);
9425 if (len == -1 && (errno == EINTR))
9426 goto again;
9428 if (len != 1)
9429 exit(1);
9430 else if (status == 1) {
9431 fprintf(stderr, "Could not acquire pidfile\n");
9432 exit(1);
9433 } else
9434 exit(0);
9435 } else if (pid < 0)
9436 exit(1);
9438 setsid();
9440 pid = fork();
9441 if (pid > 0)
9442 exit(0);
9443 else if (pid < 0)
9444 exit(1);
9446 umask(027);
9448 signal(SIGTSTP, SIG_IGN);
9449 signal(SIGTTOU, SIG_IGN);
9450 signal(SIGTTIN, SIG_IGN);
9452 #endif
9454 #if USE_KVM
9455 if (kvm_enabled()) {
9456 if (kvm_qemu_init() < 0) {
9457 extern int kvm_allowed;
9458 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9459 #ifdef NO_CPU_EMULATION
9460 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9461 exit(1);
9462 #endif
9463 kvm_allowed = 0;
9466 #endif
9468 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9469 if (daemonize) {
9470 uint8_t status = 1;
9471 write(fds[1], &status, 1);
9472 } else
9473 fprintf(stderr, "Could not acquire pid file\n");
9474 exit(1);
9477 #ifdef USE_KQEMU
9478 if (smp_cpus > 1)
9479 kqemu_allowed = 0;
9480 #endif
9481 linux_boot = (kernel_filename != NULL);
9482 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9484 /* XXX: this should not be: some embedded targets just have flash */
9485 if (!linux_boot && net_boot == 0 &&
9486 nb_drives_opt == 0)
9487 help(1);
9489 /* boot to floppy or the default cd if no hard disk defined yet */
9490 if (!boot_devices[0]) {
9491 boot_devices = "cad";
9493 setvbuf(stdout, NULL, _IOLBF, 0);
9495 init_timers();
9496 init_timer_alarm();
9497 qemu_aio_init();
9499 #ifdef _WIN32
9500 socket_init();
9501 #endif
9503 /* init network clients */
9504 if (nb_net_clients == 0) {
9505 /* if no clients, we use a default config */
9506 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9507 "nic");
9508 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9509 "user");
9510 nb_net_clients = 2;
9513 for(i = 0;i < nb_net_clients; i++) {
9514 if (net_client_init(net_clients[i]) < 0)
9515 exit(1);
9517 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9518 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9519 continue;
9520 if (vlan->nb_guest_devs == 0) {
9521 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9522 exit(1);
9524 if (vlan->nb_host_devs == 0)
9525 fprintf(stderr,
9526 "Warning: vlan %d is not connected to host network\n",
9527 vlan->id);
9530 #ifdef TARGET_I386
9531 /* XXX: this should be moved in the PC machine instantiation code */
9532 if (net_boot != 0) {
9533 int netroms = 0;
9534 for (i = 0; i < nb_nics && i < 4; i++) {
9535 const char *model = nd_table[i].model;
9536 char buf[1024];
9537 if (net_boot & (1 << i)) {
9538 if (model == NULL)
9539 model = "rtl8139";
9540 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9541 if (get_image_size(buf) > 0) {
9542 if (nb_option_roms >= MAX_OPTION_ROMS) {
9543 fprintf(stderr, "Too many option ROMs\n");
9544 exit(1);
9546 option_rom[nb_option_roms] = strdup(buf);
9547 nb_option_roms++;
9548 netroms++;
9552 if (netroms == 0) {
9553 fprintf(stderr, "No valid PXE rom found for network device\n");
9554 exit(1);
9557 #endif
9559 /* init the memory */
9560 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9562 /* Initialize kvm */
9563 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9564 #define KVM_EXTRA_PAGES 3
9565 #else
9566 #define KVM_EXTRA_PAGES 0
9567 #endif
9568 if (kvm_enabled()) {
9569 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9570 if (kvm_qemu_create_context() < 0) {
9571 fprintf(stderr, "Could not create KVM context\n");
9572 exit(1);
9574 #ifdef KVM_CAP_USER_MEMORY
9576 int ret;
9578 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9579 if (ret) {
9580 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9581 if (!phys_ram_base) {
9582 fprintf(stderr, "Could not allocate physical memory\n");
9583 exit(1);
9587 #endif
9588 } else {
9589 phys_ram_base = qemu_vmalloc(phys_ram_size);
9590 if (!phys_ram_base) {
9591 fprintf(stderr, "Could not allocate physical memory\n");
9592 exit(1);
9596 bdrv_init();
9598 /* we always create the cdrom drive, even if no disk is there */
9600 if (nb_drives_opt < MAX_DRIVES)
9601 drive_add(NULL, CDROM_ALIAS);
9603 /* we always create at least one floppy */
9605 if (nb_drives_opt < MAX_DRIVES)
9606 drive_add(NULL, FD_ALIAS, 0);
9608 /* we always create one sd slot, even if no card is in it */
9610 if (nb_drives_opt < MAX_DRIVES)
9611 drive_add(NULL, SD_ALIAS);
9613 /* open the virtual block devices
9614 * note that migration with device
9615 * hot add/remove is broken.
9617 for(i = 0; i < nb_drives_opt; i++)
9618 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9619 exit(1);
9621 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9622 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9624 init_ioports();
9626 /* terminal init */
9627 memset(&display_state, 0, sizeof(display_state));
9628 if (nographic) {
9629 if (curses) {
9630 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9631 exit(1);
9633 /* nearly nothing to do */
9634 dumb_display_init(ds);
9635 } else if (vnc_display != NULL) {
9636 vnc_display_init(ds);
9637 if (vnc_display_open(ds, vnc_display) < 0)
9638 exit(1);
9639 } else
9640 #if defined(CONFIG_CURSES)
9641 if (curses) {
9642 curses_display_init(ds, full_screen);
9643 } else
9644 #endif
9646 #if defined(CONFIG_SDL)
9647 sdl_display_init(ds, full_screen, no_frame);
9648 #elif defined(CONFIG_COCOA)
9649 cocoa_display_init(ds, full_screen);
9650 #else
9651 dumb_display_init(ds);
9652 #endif
9655 /* Maintain compatibility with multiple stdio monitors */
9656 if (!strcmp(monitor_device,"stdio")) {
9657 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9658 if (!strcmp(serial_devices[i],"mon:stdio")) {
9659 monitor_device[0] = '\0';
9660 break;
9661 } else if (!strcmp(serial_devices[i],"stdio")) {
9662 monitor_device[0] = '\0';
9663 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9664 break;
9668 if (monitor_device[0] != '\0') {
9669 monitor_hd = qemu_chr_open(monitor_device);
9670 if (!monitor_hd) {
9671 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9672 exit(1);
9674 monitor_init(monitor_hd, !nographic);
9677 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9678 const char *devname = vmchannel_devices[i];
9679 if (devname[0] != '\0' && strcmp(devname, "none")) {
9680 int devid;
9681 char *termn;
9683 if (strstart(devname, "di:", &devname)) {
9684 devid = strtol(devname, &termn, 16);
9685 devname = termn + 1;
9687 else {
9688 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9689 devname);
9690 exit(1);
9692 vmchannel_hds[i] = qemu_chr_open(devname);
9693 if (!vmchannel_hds[i]) {
9694 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9695 devname);
9696 exit(1);
9698 vmchannel_init(vmchannel_hds[i], devid, i);
9702 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9703 const char *devname = serial_devices[i];
9704 if (devname[0] != '\0' && strcmp(devname, "none")) {
9705 serial_hds[i] = qemu_chr_open(devname);
9706 if (!serial_hds[i]) {
9707 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9708 devname);
9709 exit(1);
9711 if (strstart(devname, "vc", 0))
9712 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9716 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9717 const char *devname = parallel_devices[i];
9718 if (devname[0] != '\0' && strcmp(devname, "none")) {
9719 parallel_hds[i] = qemu_chr_open(devname);
9720 if (!parallel_hds[i]) {
9721 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9722 devname);
9723 exit(1);
9725 if (strstart(devname, "vc", 0))
9726 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9730 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9731 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9733 /* init USB devices */
9734 if (usb_enabled) {
9735 for(i = 0; i < usb_devices_index; i++) {
9736 if (usb_device_add(usb_devices[i]) < 0) {
9737 fprintf(stderr, "Warning: could not add USB device %s\n",
9738 usb_devices[i]);
9743 if (display_state.dpy_refresh) {
9744 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9745 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9748 if (kvm_enabled())
9749 kvm_init_ap();
9751 #ifdef CONFIG_GDBSTUB
9752 if (use_gdbstub) {
9753 /* XXX: use standard host:port notation and modify options
9754 accordingly. */
9755 if (gdbserver_start(gdbstub_port) < 0) {
9756 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9757 gdbstub_port);
9758 exit(1);
9761 #endif
9762 if (loadvm)
9763 do_loadvm(loadvm);
9765 if (incoming) {
9766 int rc;
9768 rc = migrate_incoming(incoming);
9769 if (rc != 0) {
9770 fprintf(stderr, "Migration failed rc=%d\n", rc);
9771 exit(rc);
9776 /* XXX: simplify init */
9777 read_passwords();
9778 if (autostart) {
9779 vm_start();
9783 if (daemonize) {
9784 uint8_t status = 0;
9785 ssize_t len;
9786 int fd;
9788 again1:
9789 len = write(fds[1], &status, 1);
9790 if (len == -1 && (errno == EINTR))
9791 goto again1;
9793 if (len != 1)
9794 exit(1);
9796 chdir("/");
9797 TFR(fd = open("/dev/null", O_RDWR));
9798 if (fd == -1)
9799 exit(1);
9801 dup2(fd, 0);
9802 dup2(fd, 1);
9803 dup2(fd, 2);
9805 close(fd);
9808 main_loop();
9809 quit_timers();
9811 #if !defined(_WIN32)
9812 /* close network clients */
9813 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9814 VLANClientState *vc;
9816 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9817 if (vc->fd_read == tap_receive) {
9818 char ifname[64];
9819 TAPState *s = vc->opaque;
9821 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9822 s->down_script[0])
9823 launch_script(s->down_script, ifname, s->fd);
9827 #endif
9828 return 0;