libkvm: accept EAGAIN to restart kvm_run
[qemu-kvm/fedora.git] / vl.c
blob0a55aae0e6c173f681da1324fca33abab7e06c30
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 Fabrice Bellard
5 *
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 "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #endif
59 #endif
60 #endif
62 #if defined(CONFIG_SLIRP)
63 #include "libslirp.h"
64 #endif
66 #ifdef _WIN32
67 #include <malloc.h>
68 #include <sys/timeb.h>
69 #include <windows.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
72 #endif
74 #include "qemu_socket.h"
76 #ifdef CONFIG_SDL
77 #ifdef __APPLE__
78 #include <SDL/SDL.h>
79 #endif
80 #endif /* CONFIG_SDL */
82 #ifdef CONFIG_COCOA
83 #undef main
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
87 #include "disas.h"
89 #include "exec-all.h"
91 #if USE_KVM
92 #include "qemu-kvm.h"
93 #endif
95 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
96 #ifdef __sun__
97 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
98 #else
99 #define SMBD_COMMAND "/usr/sbin/smbd"
100 #endif
102 //#define DEBUG_UNUSED_IOPORT
103 //#define DEBUG_IOPORT
105 #if HOST_LONG_BITS < 64
106 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
107 #else
108 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
109 #endif
111 #ifdef TARGET_PPC
112 #define DEFAULT_RAM_SIZE 144
113 #else
114 #define DEFAULT_RAM_SIZE 128
115 #endif
116 /* in ms */
117 #define GUI_REFRESH_INTERVAL 30
119 /* Max number of USB devices that can be specified on the commandline. */
120 #define MAX_USB_CMDLINE 8
122 /* XXX: use a two level table to limit memory usage */
123 #define MAX_IOPORTS 65536
125 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
126 char phys_ram_file[1024];
127 void *ioport_opaque[MAX_IOPORTS];
128 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
129 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
130 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
131 to store the VM snapshots */
132 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
133 /* point to the block driver where the snapshots are managed */
134 BlockDriverState *bs_snapshots;
135 int vga_ram_size;
136 int bios_size;
137 static DisplayState display_state;
138 int nographic;
139 const char* keyboard_layout = NULL;
140 int64_t ticks_per_sec;
141 int boot_device = 'c';
142 int64_t ram_size;
143 int pit_min_timer_count = 0;
144 int nb_nics;
145 NICInfo nd_table[MAX_NICS];
146 QEMUTimer *gui_timer;
147 int vm_running;
148 int rtc_utc = 1;
149 int cirrus_vga_enabled = 1;
150 #ifdef TARGET_SPARC
151 int graphic_width = 1024;
152 int graphic_height = 768;
153 #else
154 int graphic_width = 800;
155 int graphic_height = 600;
156 #endif
157 int graphic_depth = 15;
158 int full_screen = 0;
159 int no_quit = 0;
160 int balloon_used = 0;
161 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
162 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
163 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
164 #ifdef TARGET_I386
165 int win2k_install_hack = 0;
166 #endif
167 int usb_enabled = 0;
168 static VLANState *first_vlan;
169 int smp_cpus = 1;
170 const char *vnc_display;
171 #if defined(TARGET_SPARC)
172 #define MAX_CPUS 16
173 #elif defined(TARGET_I386)
174 #define MAX_CPUS 255
175 #else
176 #define MAX_CPUS 1
177 #endif
178 int acpi_enabled = 1;
179 int fd_bootchk = 1;
180 int no_reboot = 0;
181 int daemonize = 0;
182 const char *incoming;
183 const char *option_rom[MAX_OPTION_ROMS];
184 int nb_option_roms;
185 int semihosting_enabled = 0;
186 int autostart = 1;
187 int time_drift_fix = 0;
188 const char *cpu_vendor_string;
190 /***********************************************************/
191 /* x86 ISA bus support */
193 target_phys_addr_t isa_mem_base = 0;
194 PicState2 *isa_pic;
196 uint32_t default_ioport_readb(void *opaque, uint32_t address)
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr, "inb: port=0x%04x\n", address);
200 #endif
201 return 0xff;
204 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
208 #endif
211 /* default is to make two byte accesses */
212 uint32_t default_ioport_readw(void *opaque, uint32_t address)
214 uint32_t data;
215 data = ioport_read_table[0][address](ioport_opaque[address], address);
216 address = (address + 1) & (MAX_IOPORTS - 1);
217 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
218 return data;
221 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
223 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
224 address = (address + 1) & (MAX_IOPORTS - 1);
225 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
228 uint32_t default_ioport_readl(void *opaque, uint32_t address)
230 #ifdef DEBUG_UNUSED_IOPORT
231 fprintf(stderr, "inl: port=0x%04x\n", address);
232 #endif
233 return 0xffffffff;
236 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
238 #ifdef DEBUG_UNUSED_IOPORT
239 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
240 #endif
243 void init_ioports(void)
245 int i;
247 for(i = 0; i < MAX_IOPORTS; i++) {
248 ioport_read_table[0][i] = default_ioport_readb;
249 ioport_write_table[0][i] = default_ioport_writeb;
250 ioport_read_table[1][i] = default_ioport_readw;
251 ioport_write_table[1][i] = default_ioport_writew;
252 ioport_read_table[2][i] = default_ioport_readl;
253 ioport_write_table[2][i] = default_ioport_writel;
257 /* size is the word size in byte */
258 int register_ioport_read(int start, int length, int size,
259 IOPortReadFunc *func, void *opaque)
261 int i, bsize;
263 if (size == 1) {
264 bsize = 0;
265 } else if (size == 2) {
266 bsize = 1;
267 } else if (size == 4) {
268 bsize = 2;
269 } else {
270 hw_error("register_ioport_read: invalid size");
271 return -1;
273 for(i = start; i < start + length; i += size) {
274 ioport_read_table[bsize][i] = func;
275 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
276 hw_error("register_ioport_read: invalid opaque");
277 ioport_opaque[i] = opaque;
279 return 0;
282 /* size is the word size in byte */
283 int register_ioport_write(int start, int length, int size,
284 IOPortWriteFunc *func, void *opaque)
286 int i, bsize;
288 if (size == 1) {
289 bsize = 0;
290 } else if (size == 2) {
291 bsize = 1;
292 } else if (size == 4) {
293 bsize = 2;
294 } else {
295 hw_error("register_ioport_write: invalid size");
296 return -1;
298 for(i = start; i < start + length; i += size) {
299 ioport_write_table[bsize][i] = func;
300 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
301 hw_error("register_ioport_write: invalid opaque");
302 ioport_opaque[i] = opaque;
304 return 0;
307 void isa_unassign_ioport(int start, int length)
309 int i;
311 for(i = start; i < start + length; i++) {
312 ioport_read_table[0][i] = default_ioport_readb;
313 ioport_read_table[1][i] = default_ioport_readw;
314 ioport_read_table[2][i] = default_ioport_readl;
316 ioport_write_table[0][i] = default_ioport_writeb;
317 ioport_write_table[1][i] = default_ioport_writew;
318 ioport_write_table[2][i] = default_ioport_writel;
322 /***********************************************************/
324 void cpu_outb(CPUState *env, int addr, int val)
326 #ifdef DEBUG_IOPORT
327 if (loglevel & CPU_LOG_IOPORT)
328 fprintf(logfile, "outb: %04x %02x\n", addr, val);
329 #endif
330 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
331 #ifdef USE_KQEMU
332 if (env)
333 env->last_io_time = cpu_get_time_fast();
334 #endif
337 void cpu_outw(CPUState *env, int addr, int val)
339 #ifdef DEBUG_IOPORT
340 if (loglevel & CPU_LOG_IOPORT)
341 fprintf(logfile, "outw: %04x %04x\n", addr, val);
342 #endif
343 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
344 #ifdef USE_KQEMU
345 if (env)
346 env->last_io_time = cpu_get_time_fast();
347 #endif
350 void cpu_outl(CPUState *env, int addr, int val)
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outl: %04x %08x\n", addr, val);
355 #endif
356 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
363 int cpu_inb(CPUState *env, int addr)
365 int val;
366 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "inb : %04x %02x\n", addr, val);
370 #endif
371 #ifdef USE_KQEMU
372 if (env)
373 env->last_io_time = cpu_get_time_fast();
374 #endif
375 return val;
378 int cpu_inw(CPUState *env, int addr)
380 int val;
381 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inw : %04x %04x\n", addr, val);
385 #endif
386 #ifdef USE_KQEMU
387 if (env)
388 env->last_io_time = cpu_get_time_fast();
389 #endif
390 return val;
393 int cpu_inl(CPUState *env, int addr)
395 int val;
396 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
397 #ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inl : %04x %08x\n", addr, val);
400 #endif
401 #ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
404 #endif
405 return val;
408 /***********************************************************/
409 void hw_error(const char *fmt, ...)
411 va_list ap;
412 CPUState *env;
414 va_start(ap, fmt);
415 fprintf(stderr, "qemu: hardware error: ");
416 vfprintf(stderr, fmt, ap);
417 fprintf(stderr, "\n");
418 for(env = first_cpu; env != NULL; env = env->next_cpu) {
419 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
420 #ifdef TARGET_I386
421 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
422 #else
423 cpu_dump_state(env, stderr, fprintf, 0);
424 #endif
426 va_end(ap);
427 abort();
430 /***********************************************************/
431 /* keyboard/mouse */
433 static QEMUPutKBDEvent *qemu_put_kbd_event;
434 static void *qemu_put_kbd_event_opaque;
435 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
436 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
438 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
440 qemu_put_kbd_event_opaque = opaque;
441 qemu_put_kbd_event = func;
444 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
445 void *opaque, int absolute,
446 const char *name)
448 QEMUPutMouseEntry *s, *cursor;
450 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
451 if (!s)
452 return NULL;
454 s->qemu_put_mouse_event = func;
455 s->qemu_put_mouse_event_opaque = opaque;
456 s->qemu_put_mouse_event_absolute = absolute;
457 s->qemu_put_mouse_event_name = qemu_strdup(name);
458 s->next = NULL;
460 if (!qemu_put_mouse_event_head) {
461 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
462 return s;
465 cursor = qemu_put_mouse_event_head;
466 while (cursor->next != NULL)
467 cursor = cursor->next;
469 cursor->next = s;
470 qemu_put_mouse_event_current = s;
472 return s;
475 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
477 QEMUPutMouseEntry *prev = NULL, *cursor;
479 if (!qemu_put_mouse_event_head || entry == NULL)
480 return;
482 cursor = qemu_put_mouse_event_head;
483 while (cursor != NULL && cursor != entry) {
484 prev = cursor;
485 cursor = cursor->next;
488 if (cursor == NULL) // does not exist or list empty
489 return;
490 else if (prev == NULL) { // entry is head
491 qemu_put_mouse_event_head = cursor->next;
492 if (qemu_put_mouse_event_current == entry)
493 qemu_put_mouse_event_current = cursor->next;
494 qemu_free(entry->qemu_put_mouse_event_name);
495 qemu_free(entry);
496 return;
499 prev->next = entry->next;
501 if (qemu_put_mouse_event_current == entry)
502 qemu_put_mouse_event_current = prev;
504 qemu_free(entry->qemu_put_mouse_event_name);
505 qemu_free(entry);
508 void kbd_put_keycode(int keycode)
510 if (qemu_put_kbd_event) {
511 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
515 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
517 QEMUPutMouseEvent *mouse_event;
518 void *mouse_event_opaque;
520 if (!qemu_put_mouse_event_current) {
521 return;
524 mouse_event =
525 qemu_put_mouse_event_current->qemu_put_mouse_event;
526 mouse_event_opaque =
527 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
529 if (mouse_event) {
530 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
534 int kbd_mouse_is_absolute(void)
536 if (!qemu_put_mouse_event_current)
537 return 0;
539 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
542 void do_info_mice(void)
544 QEMUPutMouseEntry *cursor;
545 int index = 0;
547 if (!qemu_put_mouse_event_head) {
548 term_printf("No mouse devices connected\n");
549 return;
552 term_printf("Mouse devices available:\n");
553 cursor = qemu_put_mouse_event_head;
554 while (cursor != NULL) {
555 term_printf("%c Mouse #%d: %s\n",
556 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
557 index, cursor->qemu_put_mouse_event_name);
558 index++;
559 cursor = cursor->next;
563 void do_mouse_set(int index)
565 QEMUPutMouseEntry *cursor;
566 int i = 0;
568 if (!qemu_put_mouse_event_head) {
569 term_printf("No mouse devices connected\n");
570 return;
573 cursor = qemu_put_mouse_event_head;
574 while (cursor != NULL && index != i) {
575 i++;
576 cursor = cursor->next;
579 if (cursor != NULL)
580 qemu_put_mouse_event_current = cursor;
581 else
582 term_printf("Mouse at given index not found\n");
585 /* compute with 96 bit intermediate result: (a*b)/c */
586 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
588 union {
589 uint64_t ll;
590 struct {
591 #ifdef WORDS_BIGENDIAN
592 uint32_t high, low;
593 #else
594 uint32_t low, high;
595 #endif
596 } l;
597 } u, res;
598 uint64_t rl, rh;
600 u.ll = a;
601 rl = (uint64_t)u.l.low * (uint64_t)b;
602 rh = (uint64_t)u.l.high * (uint64_t)b;
603 rh += (rl >> 32);
604 res.l.high = rh / c;
605 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
606 return res.ll;
609 /***********************************************************/
610 /* real time host monotonic timer */
612 #define QEMU_TIMER_BASE 1000000000LL
614 #ifdef WIN32
616 static int64_t clock_freq;
618 static void init_get_clock(void)
620 LARGE_INTEGER freq;
621 int ret;
622 ret = QueryPerformanceFrequency(&freq);
623 if (ret == 0) {
624 fprintf(stderr, "Could not calibrate ticks\n");
625 exit(1);
627 clock_freq = freq.QuadPart;
630 static int64_t get_clock(void)
632 LARGE_INTEGER ti;
633 QueryPerformanceCounter(&ti);
634 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
637 #else
639 static int use_rt_clock;
641 static void init_get_clock(void)
643 use_rt_clock = 0;
644 #if defined(__linux__)
646 struct timespec ts;
647 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
648 use_rt_clock = 1;
651 #endif
654 static int64_t get_clock(void)
656 #if defined(__linux__)
657 if (use_rt_clock) {
658 struct timespec ts;
659 clock_gettime(CLOCK_MONOTONIC, &ts);
660 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
661 } else
662 #endif
664 /* XXX: using gettimeofday leads to problems if the date
665 changes, so it should be avoided. */
666 struct timeval tv;
667 gettimeofday(&tv, NULL);
668 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
672 #endif
674 /***********************************************************/
675 /* guest cycle counter */
677 static int64_t cpu_ticks_prev;
678 static int64_t cpu_ticks_offset;
679 static int64_t cpu_clock_offset;
680 static int cpu_ticks_enabled;
682 /* return the host CPU cycle counter and handle stop/restart */
683 int64_t cpu_get_ticks(void)
685 if (!cpu_ticks_enabled) {
686 return cpu_ticks_offset;
687 } else {
688 int64_t ticks;
689 ticks = cpu_get_real_ticks();
690 if (cpu_ticks_prev > ticks) {
691 /* Note: non increasing ticks may happen if the host uses
692 software suspend */
693 cpu_ticks_offset += cpu_ticks_prev - ticks;
695 cpu_ticks_prev = ticks;
696 return ticks + cpu_ticks_offset;
700 /* return the host CPU monotonic timer and handle stop/restart */
701 static int64_t cpu_get_clock(void)
703 int64_t ti;
704 if (!cpu_ticks_enabled) {
705 return cpu_clock_offset;
706 } else {
707 ti = get_clock();
708 return ti + cpu_clock_offset;
712 /* enable cpu_get_ticks() */
713 void cpu_enable_ticks(void)
715 if (!cpu_ticks_enabled) {
716 cpu_ticks_offset -= cpu_get_real_ticks();
717 cpu_clock_offset -= get_clock();
718 cpu_ticks_enabled = 1;
722 /* disable cpu_get_ticks() : the clock is stopped. You must not call
723 cpu_get_ticks() after that. */
724 void cpu_disable_ticks(void)
726 if (cpu_ticks_enabled) {
727 cpu_ticks_offset = cpu_get_ticks();
728 cpu_clock_offset = cpu_get_clock();
729 cpu_ticks_enabled = 0;
733 /***********************************************************/
734 /* timers */
736 #define QEMU_TIMER_REALTIME 0
737 #define QEMU_TIMER_VIRTUAL 1
739 struct QEMUClock {
740 int type;
741 /* XXX: add frequency */
744 struct QEMUTimer {
745 QEMUClock *clock;
746 int64_t expire_time;
747 QEMUTimerCB *cb;
748 void *opaque;
749 struct QEMUTimer *next;
752 QEMUClock *rt_clock;
753 QEMUClock *vm_clock;
755 static QEMUTimer *active_timers[2];
756 #ifdef _WIN32
757 static MMRESULT timerID;
758 static HANDLE host_alarm = NULL;
759 static unsigned int period = 1;
760 #else
761 /* frequency of the times() clock tick */
762 static int timer_freq;
763 #endif
765 QEMUClock *qemu_new_clock(int type)
767 QEMUClock *clock;
768 clock = qemu_mallocz(sizeof(QEMUClock));
769 if (!clock)
770 return NULL;
771 clock->type = type;
772 return clock;
775 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
777 QEMUTimer *ts;
779 ts = qemu_mallocz(sizeof(QEMUTimer));
780 ts->clock = clock;
781 ts->cb = cb;
782 ts->opaque = opaque;
783 return ts;
786 void qemu_free_timer(QEMUTimer *ts)
788 qemu_free(ts);
791 /* stop a timer, but do not dealloc it */
792 void qemu_del_timer(QEMUTimer *ts)
794 QEMUTimer **pt, *t;
796 /* NOTE: this code must be signal safe because
797 qemu_timer_expired() can be called from a signal. */
798 pt = &active_timers[ts->clock->type];
799 for(;;) {
800 t = *pt;
801 if (!t)
802 break;
803 if (t == ts) {
804 *pt = t->next;
805 break;
807 pt = &t->next;
811 /* modify the current timer so that it will be fired when current_time
812 >= expire_time. The corresponding callback will be called. */
813 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
815 QEMUTimer **pt, *t;
817 qemu_del_timer(ts);
819 /* add the timer in the sorted list */
820 /* NOTE: this code must be signal safe because
821 qemu_timer_expired() can be called from a signal. */
822 pt = &active_timers[ts->clock->type];
823 for(;;) {
824 t = *pt;
825 if (!t)
826 break;
827 if (t->expire_time > expire_time)
828 break;
829 pt = &t->next;
831 ts->expire_time = expire_time;
832 ts->next = *pt;
833 *pt = ts;
836 int qemu_timer_pending(QEMUTimer *ts)
838 QEMUTimer *t;
839 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
840 if (t == ts)
841 return 1;
843 return 0;
846 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
848 if (!timer_head)
849 return 0;
850 return (timer_head->expire_time <= current_time);
853 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
855 QEMUTimer *ts;
857 for(;;) {
858 ts = *ptimer_head;
859 if (!ts || ts->expire_time > current_time)
860 break;
861 /* remove timer from the list before calling the callback */
862 *ptimer_head = ts->next;
863 ts->next = NULL;
865 /* run the callback (the timer list can be modified) */
866 ts->cb(ts->opaque);
870 int64_t qemu_get_clock(QEMUClock *clock)
872 switch(clock->type) {
873 case QEMU_TIMER_REALTIME:
874 return get_clock() / 1000000;
875 default:
876 case QEMU_TIMER_VIRTUAL:
877 return cpu_get_clock();
881 static void init_timers(void)
883 init_get_clock();
884 ticks_per_sec = QEMU_TIMER_BASE;
885 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
886 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
889 /* save a timer */
890 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
892 uint64_t expire_time;
894 if (qemu_timer_pending(ts)) {
895 expire_time = ts->expire_time;
896 } else {
897 expire_time = -1;
899 qemu_put_be64(f, expire_time);
902 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
904 uint64_t expire_time;
906 expire_time = qemu_get_be64(f);
907 if (expire_time != -1) {
908 qemu_mod_timer(ts, expire_time);
909 } else {
910 qemu_del_timer(ts);
914 static void timer_save(QEMUFile *f, void *opaque)
916 if (cpu_ticks_enabled) {
917 hw_error("cannot save state if virtual timers are running");
919 qemu_put_be64s(f, &cpu_ticks_offset);
920 qemu_put_be64s(f, &ticks_per_sec);
921 qemu_put_be64s(f, &cpu_clock_offset);
924 static int timer_load(QEMUFile *f, void *opaque, int version_id)
926 if (version_id != 1 && version_id != 2)
927 return -EINVAL;
928 if (cpu_ticks_enabled) {
929 return -EINVAL;
931 qemu_get_be64s(f, &cpu_ticks_offset);
932 qemu_get_be64s(f, &ticks_per_sec);
933 if (version_id == 2) {
934 qemu_get_be64s(f, &cpu_clock_offset);
936 return 0;
939 #ifdef _WIN32
940 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
941 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
942 #else
943 static void host_alarm_handler(int host_signum)
944 #endif
946 #if 0
947 #define DISP_FREQ 1000
949 static int64_t delta_min = INT64_MAX;
950 static int64_t delta_max, delta_cum, last_clock, delta, ti;
951 static int count;
952 ti = qemu_get_clock(vm_clock);
953 if (last_clock != 0) {
954 delta = ti - last_clock;
955 if (delta < delta_min)
956 delta_min = delta;
957 if (delta > delta_max)
958 delta_max = delta;
959 delta_cum += delta;
960 if (++count == DISP_FREQ) {
961 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
962 muldiv64(delta_min, 1000000, ticks_per_sec),
963 muldiv64(delta_max, 1000000, ticks_per_sec),
964 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
965 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
966 count = 0;
967 delta_min = INT64_MAX;
968 delta_max = 0;
969 delta_cum = 0;
972 last_clock = ti;
974 #endif
975 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
976 qemu_get_clock(vm_clock)) ||
977 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
978 qemu_get_clock(rt_clock))) {
979 #ifdef _WIN32
980 SetEvent(host_alarm);
981 #endif
982 CPUState *env = cpu_single_env;
983 if (env) {
984 /* stop the currently executing cpu because a timer occured */
985 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
986 #ifdef USE_KQEMU
987 if (env->kqemu_enabled) {
988 kqemu_cpu_interrupt(env);
990 #endif
995 #ifndef _WIN32
997 #if defined(__linux__)
999 #define RTC_FREQ 1024
1001 static int use_rtc = 1;
1002 static int rtc_fd;
1004 static int start_rtc_timer(void)
1006 rtc_fd = open("/dev/rtc", O_RDONLY);
1007 if (rtc_fd < 0)
1008 return -1;
1009 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1010 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1011 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1012 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1013 goto fail;
1015 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1016 fail:
1017 close(rtc_fd);
1018 return -1;
1020 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1021 return 0;
1024 #else
1026 static int start_rtc_timer(void)
1028 return -1;
1031 #endif /* !defined(__linux__) */
1033 #endif /* !defined(_WIN32) */
1035 static void init_timer_alarm(void)
1037 #ifdef _WIN32
1039 int count=0;
1040 TIMECAPS tc;
1042 ZeroMemory(&tc, sizeof(TIMECAPS));
1043 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1044 if (period < tc.wPeriodMin)
1045 period = tc.wPeriodMin;
1046 timeBeginPeriod(period);
1047 timerID = timeSetEvent(1, // interval (ms)
1048 period, // resolution
1049 host_alarm_handler, // function
1050 (DWORD)&count, // user parameter
1051 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1052 if( !timerID ) {
1053 perror("failed timer alarm");
1054 exit(1);
1056 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1057 if (!host_alarm) {
1058 perror("failed CreateEvent");
1059 exit(1);
1061 qemu_add_wait_object(host_alarm, NULL, NULL);
1063 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1064 #else
1066 struct sigaction act;
1067 struct itimerval itv;
1069 /* get times() syscall frequency */
1070 timer_freq = sysconf(_SC_CLK_TCK);
1072 /* timer signal */
1073 sigfillset(&act.sa_mask);
1074 act.sa_flags = 0;
1075 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1076 act.sa_flags |= SA_ONSTACK;
1077 #endif
1078 act.sa_handler = host_alarm_handler;
1079 sigaction(SIGALRM, &act, NULL);
1081 itv.it_interval.tv_sec = 0;
1082 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1083 itv.it_value.tv_sec = 0;
1084 itv.it_value.tv_usec = 10 * 1000;
1085 setitimer(ITIMER_REAL, &itv, NULL);
1086 /* we probe the tick duration of the kernel to inform the user if
1087 the emulated kernel requested a too high timer frequency */
1088 getitimer(ITIMER_REAL, &itv);
1090 #if defined(__linux__)
1091 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1092 have timers with 1 ms resolution. The correct solution will
1093 be to use the POSIX real time timers available in recent
1094 2.6 kernels */
1095 if (itv.it_interval.tv_usec > 1000 || 1) {
1096 /* try to use /dev/rtc to have a faster timer */
1097 if (!use_rtc || (start_rtc_timer() < 0))
1098 goto use_itimer;
1099 /* disable itimer */
1100 itv.it_interval.tv_sec = 0;
1101 itv.it_interval.tv_usec = 0;
1102 itv.it_value.tv_sec = 0;
1103 itv.it_value.tv_usec = 0;
1104 setitimer(ITIMER_REAL, &itv, NULL);
1106 /* use the RTC */
1107 sigaction(SIGIO, &act, NULL);
1108 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1109 fcntl(rtc_fd, F_SETOWN, getpid());
1110 } else
1111 #endif /* defined(__linux__) */
1113 use_itimer:
1114 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1115 PIT_FREQ) / 1000000;
1118 #endif
1121 void quit_timers(void)
1123 #ifdef _WIN32
1124 timeKillEvent(timerID);
1125 timeEndPeriod(period);
1126 if (host_alarm) {
1127 CloseHandle(host_alarm);
1128 host_alarm = NULL;
1130 #endif
1133 /***********************************************************/
1134 /* character device */
1136 static void qemu_chr_event(CharDriverState *s, int event)
1138 if (!s->chr_event)
1139 return;
1140 s->chr_event(s->handler_opaque, event);
1143 static void qemu_chr_reset_bh(void *opaque)
1145 CharDriverState *s = opaque;
1146 qemu_chr_event(s, CHR_EVENT_RESET);
1147 qemu_bh_delete(s->bh);
1148 s->bh = NULL;
1151 void qemu_chr_reset(CharDriverState *s)
1153 if (s->bh == NULL) {
1154 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1155 qemu_bh_schedule(s->bh);
1159 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1161 return s->chr_write(s, buf, len);
1164 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1166 if (!s->chr_ioctl)
1167 return -ENOTSUP;
1168 return s->chr_ioctl(s, cmd, arg);
1171 int qemu_chr_can_read(CharDriverState *s)
1173 if (!s->chr_can_read)
1174 return 0;
1175 return s->chr_can_read(s->handler_opaque);
1178 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1180 s->chr_read(s->handler_opaque, buf, len);
1184 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1186 char buf[4096];
1187 va_list ap;
1188 va_start(ap, fmt);
1189 vsnprintf(buf, sizeof(buf), fmt, ap);
1190 qemu_chr_write(s, buf, strlen(buf));
1191 va_end(ap);
1194 void qemu_chr_send_event(CharDriverState *s, int event)
1196 if (s->chr_send_event)
1197 s->chr_send_event(s, event);
1200 void qemu_chr_add_handlers(CharDriverState *s,
1201 IOCanRWHandler *fd_can_read,
1202 IOReadHandler *fd_read,
1203 IOEventHandler *fd_event,
1204 void *opaque)
1206 s->chr_can_read = fd_can_read;
1207 s->chr_read = fd_read;
1208 s->chr_event = fd_event;
1209 s->handler_opaque = opaque;
1210 if (s->chr_update_read_handler)
1211 s->chr_update_read_handler(s);
1214 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1216 return len;
1219 static CharDriverState *qemu_chr_open_null(void)
1221 CharDriverState *chr;
1223 chr = qemu_mallocz(sizeof(CharDriverState));
1224 if (!chr)
1225 return NULL;
1226 chr->chr_write = null_chr_write;
1227 return chr;
1230 #ifdef _WIN32
1232 static void socket_cleanup(void)
1234 WSACleanup();
1237 static int socket_init(void)
1239 WSADATA Data;
1240 int ret, err;
1242 ret = WSAStartup(MAKEWORD(2,2), &Data);
1243 if (ret != 0) {
1244 err = WSAGetLastError();
1245 fprintf(stderr, "WSAStartup: %d\n", err);
1246 return -1;
1248 atexit(socket_cleanup);
1249 return 0;
1252 static int send_all(int fd, const uint8_t *buf, int len1)
1254 int ret, len;
1256 len = len1;
1257 while (len > 0) {
1258 ret = send(fd, buf, len, 0);
1259 if (ret < 0) {
1260 int errno;
1261 errno = WSAGetLastError();
1262 if (errno != WSAEWOULDBLOCK) {
1263 return -1;
1265 } else if (ret == 0) {
1266 break;
1267 } else {
1268 buf += ret;
1269 len -= ret;
1272 return len1 - len;
1275 void socket_set_nonblock(int fd)
1277 unsigned long opt = 1;
1278 ioctlsocket(fd, FIONBIO, &opt);
1281 #else
1283 static int unix_write(int fd, const uint8_t *buf, int len1)
1285 int ret, len;
1287 len = len1;
1288 while (len > 0) {
1289 ret = write(fd, buf, len);
1290 if (ret < 0) {
1291 if (errno != EINTR && errno != EAGAIN)
1292 return -1;
1293 } else if (ret == 0) {
1294 break;
1295 } else {
1296 buf += ret;
1297 len -= ret;
1300 return len1 - len;
1303 static inline int send_all(int fd, const uint8_t *buf, int len1)
1305 return unix_write(fd, buf, len1);
1308 void socket_set_nonblock(int fd)
1310 fcntl(fd, F_SETFL, O_NONBLOCK);
1312 #endif /* !_WIN32 */
1314 #ifndef _WIN32
1316 typedef struct {
1317 int fd_in, fd_out;
1318 int max_size;
1319 } FDCharDriver;
1321 #define STDIO_MAX_CLIENTS 2
1323 static int stdio_nb_clients;
1324 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1326 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1328 FDCharDriver *s = chr->opaque;
1329 return unix_write(s->fd_out, buf, len);
1332 static int fd_chr_read_poll(void *opaque)
1334 CharDriverState *chr = opaque;
1335 FDCharDriver *s = chr->opaque;
1337 s->max_size = qemu_chr_can_read(chr);
1338 return s->max_size;
1341 static void fd_chr_read(void *opaque)
1343 CharDriverState *chr = opaque;
1344 FDCharDriver *s = chr->opaque;
1345 int size, len;
1346 uint8_t buf[1024];
1348 len = sizeof(buf);
1349 if (len > s->max_size)
1350 len = s->max_size;
1351 if (len == 0)
1352 return;
1353 size = read(s->fd_in, buf, len);
1354 if (size == 0) {
1355 /* FD has been closed. Remove it from the active list. */
1356 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1357 return;
1359 if (size > 0) {
1360 qemu_chr_read(chr, buf, size);
1364 static void fd_chr_update_read_handler(CharDriverState *chr)
1366 FDCharDriver *s = chr->opaque;
1368 if (s->fd_in >= 0) {
1369 if (nographic && s->fd_in == 0) {
1370 } else {
1371 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1372 fd_chr_read, NULL, chr);
1377 /* open a character device to a unix fd */
1378 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1380 CharDriverState *chr;
1381 FDCharDriver *s;
1383 chr = qemu_mallocz(sizeof(CharDriverState));
1384 if (!chr)
1385 return NULL;
1386 s = qemu_mallocz(sizeof(FDCharDriver));
1387 if (!s) {
1388 free(chr);
1389 return NULL;
1391 s->fd_in = fd_in;
1392 s->fd_out = fd_out;
1393 chr->opaque = s;
1394 chr->chr_write = fd_chr_write;
1395 chr->chr_update_read_handler = fd_chr_update_read_handler;
1397 qemu_chr_reset(chr);
1399 return chr;
1402 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1404 int fd_out;
1406 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1407 if (fd_out < 0)
1408 return NULL;
1409 return qemu_chr_open_fd(-1, fd_out);
1412 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1414 int fd_in, fd_out;
1415 char filename_in[256], filename_out[256];
1417 snprintf(filename_in, 256, "%s.in", filename);
1418 snprintf(filename_out, 256, "%s.out", filename);
1419 fd_in = open(filename_in, O_RDWR | O_BINARY);
1420 fd_out = open(filename_out, O_RDWR | O_BINARY);
1421 if (fd_in < 0 || fd_out < 0) {
1422 if (fd_in >= 0)
1423 close(fd_in);
1424 if (fd_out >= 0)
1425 close(fd_out);
1426 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1427 if (fd_in < 0)
1428 return NULL;
1430 return qemu_chr_open_fd(fd_in, fd_out);
1434 /* for STDIO, we handle the case where several clients use it
1435 (nographic mode) */
1437 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1439 #define TERM_FIFO_MAX_SIZE 1
1441 static int term_got_escape, client_index;
1442 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1443 static int term_fifo_size;
1444 static int term_timestamps;
1445 static int64_t term_timestamps_start;
1447 void term_print_help(void)
1449 printf("\n"
1450 "C-a h print this help\n"
1451 "C-a x exit emulator\n"
1452 "C-a s save disk data back to file (if -snapshot)\n"
1453 "C-a b send break (magic sysrq)\n"
1454 "C-a t toggle console timestamps\n"
1455 "C-a c switch between console and monitor\n"
1456 "C-a C-a send C-a\n"
1460 /* called when a char is received */
1461 static void stdio_received_byte(int ch)
1463 if (term_got_escape) {
1464 term_got_escape = 0;
1465 switch(ch) {
1466 case 'h':
1467 term_print_help();
1468 break;
1469 case 'x':
1470 exit(0);
1471 break;
1472 case 's':
1474 int i;
1475 for (i = 0; i < MAX_DISKS; i++) {
1476 if (bs_table[i])
1477 bdrv_commit(bs_table[i]);
1480 break;
1481 case 'b':
1482 if (client_index < stdio_nb_clients) {
1483 CharDriverState *chr;
1484 FDCharDriver *s;
1486 chr = stdio_clients[client_index];
1487 s = chr->opaque;
1488 qemu_chr_event(chr, CHR_EVENT_BREAK);
1490 break;
1491 case 'c':
1492 client_index++;
1493 if (client_index >= stdio_nb_clients)
1494 client_index = 0;
1495 if (client_index == 0) {
1496 /* send a new line in the monitor to get the prompt */
1497 ch = '\r';
1498 goto send_char;
1500 break;
1501 case 't':
1502 term_timestamps = !term_timestamps;
1503 term_timestamps_start = -1;
1504 break;
1505 case TERM_ESCAPE:
1506 goto send_char;
1508 } else if (ch == TERM_ESCAPE) {
1509 term_got_escape = 1;
1510 } else {
1511 send_char:
1512 if (client_index < stdio_nb_clients) {
1513 uint8_t buf[1];
1514 CharDriverState *chr;
1516 chr = stdio_clients[client_index];
1517 if (qemu_chr_can_read(chr) > 0) {
1518 buf[0] = ch;
1519 qemu_chr_read(chr, buf, 1);
1520 } else if (term_fifo_size == 0) {
1521 term_fifo[term_fifo_size++] = ch;
1527 static int stdio_read_poll(void *opaque)
1529 CharDriverState *chr;
1531 if (client_index < stdio_nb_clients) {
1532 chr = stdio_clients[client_index];
1533 /* try to flush the queue if needed */
1534 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1535 qemu_chr_read(chr, term_fifo, 1);
1536 term_fifo_size = 0;
1538 /* see if we can absorb more chars */
1539 if (term_fifo_size == 0)
1540 return 1;
1541 else
1542 return 0;
1543 } else {
1544 return 1;
1548 static void stdio_read(void *opaque)
1550 int size;
1551 uint8_t buf[1];
1553 size = read(0, buf, 1);
1554 if (size == 0) {
1555 /* stdin has been closed. Remove it from the active list. */
1556 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1557 return;
1559 if (size > 0)
1560 stdio_received_byte(buf[0]);
1563 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1565 FDCharDriver *s = chr->opaque;
1566 if (!term_timestamps) {
1567 return unix_write(s->fd_out, buf, len);
1568 } else {
1569 int i;
1570 char buf1[64];
1572 for(i = 0; i < len; i++) {
1573 unix_write(s->fd_out, buf + i, 1);
1574 if (buf[i] == '\n') {
1575 int64_t ti;
1576 int secs;
1578 ti = get_clock();
1579 if (term_timestamps_start == -1)
1580 term_timestamps_start = ti;
1581 ti -= term_timestamps_start;
1582 secs = ti / 1000000000;
1583 snprintf(buf1, sizeof(buf1),
1584 "[%02d:%02d:%02d.%03d] ",
1585 secs / 3600,
1586 (secs / 60) % 60,
1587 secs % 60,
1588 (int)((ti / 1000000) % 1000));
1589 unix_write(s->fd_out, buf1, strlen(buf1));
1592 return len;
1596 /* init terminal so that we can grab keys */
1597 static struct termios oldtty;
1598 static int old_fd0_flags;
1600 static void term_exit(void)
1602 tcsetattr (0, TCSANOW, &oldtty);
1603 fcntl(0, F_SETFL, old_fd0_flags);
1606 static void term_init(void)
1608 struct termios tty;
1610 tcgetattr (0, &tty);
1611 oldtty = tty;
1612 old_fd0_flags = fcntl(0, F_GETFL);
1614 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1615 |INLCR|IGNCR|ICRNL|IXON);
1616 tty.c_oflag |= OPOST;
1617 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1618 /* if graphical mode, we allow Ctrl-C handling */
1619 if (nographic)
1620 tty.c_lflag &= ~ISIG;
1621 tty.c_cflag &= ~(CSIZE|PARENB);
1622 tty.c_cflag |= CS8;
1623 tty.c_cc[VMIN] = 1;
1624 tty.c_cc[VTIME] = 0;
1626 tcsetattr (0, TCSANOW, &tty);
1628 atexit(term_exit);
1630 fcntl(0, F_SETFL, O_NONBLOCK);
1633 static CharDriverState *qemu_chr_open_stdio(void)
1635 CharDriverState *chr;
1637 if (nographic) {
1638 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1639 return NULL;
1640 chr = qemu_chr_open_fd(0, 1);
1641 chr->chr_write = stdio_write;
1642 if (stdio_nb_clients == 0)
1643 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1644 client_index = stdio_nb_clients;
1645 } else {
1646 if (stdio_nb_clients != 0)
1647 return NULL;
1648 chr = qemu_chr_open_fd(0, 1);
1650 stdio_clients[stdio_nb_clients++] = chr;
1651 if (stdio_nb_clients == 1) {
1652 /* set the terminal in raw mode */
1653 term_init();
1655 return chr;
1658 #if defined(__linux__)
1659 static CharDriverState *qemu_chr_open_pty(void)
1661 struct termios tty;
1662 char slave_name[1024];
1663 int master_fd, slave_fd;
1665 /* Not satisfying */
1666 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1667 return NULL;
1670 /* Disabling local echo and line-buffered output */
1671 tcgetattr (master_fd, &tty);
1672 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1673 tty.c_cc[VMIN] = 1;
1674 tty.c_cc[VTIME] = 0;
1675 tcsetattr (master_fd, TCSAFLUSH, &tty);
1677 fprintf(stderr, "char device redirected to %s\n", slave_name);
1678 return qemu_chr_open_fd(master_fd, master_fd);
1681 static void tty_serial_init(int fd, int speed,
1682 int parity, int data_bits, int stop_bits)
1684 struct termios tty;
1685 speed_t spd;
1687 #if 0
1688 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1689 speed, parity, data_bits, stop_bits);
1690 #endif
1691 tcgetattr (fd, &tty);
1693 switch(speed) {
1694 case 50:
1695 spd = B50;
1696 break;
1697 case 75:
1698 spd = B75;
1699 break;
1700 case 300:
1701 spd = B300;
1702 break;
1703 case 600:
1704 spd = B600;
1705 break;
1706 case 1200:
1707 spd = B1200;
1708 break;
1709 case 2400:
1710 spd = B2400;
1711 break;
1712 case 4800:
1713 spd = B4800;
1714 break;
1715 case 9600:
1716 spd = B9600;
1717 break;
1718 case 19200:
1719 spd = B19200;
1720 break;
1721 case 38400:
1722 spd = B38400;
1723 break;
1724 case 57600:
1725 spd = B57600;
1726 break;
1727 default:
1728 case 115200:
1729 spd = B115200;
1730 break;
1733 cfsetispeed(&tty, spd);
1734 cfsetospeed(&tty, spd);
1736 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1737 |INLCR|IGNCR|ICRNL|IXON);
1738 tty.c_oflag |= OPOST;
1739 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1740 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1741 switch(data_bits) {
1742 default:
1743 case 8:
1744 tty.c_cflag |= CS8;
1745 break;
1746 case 7:
1747 tty.c_cflag |= CS7;
1748 break;
1749 case 6:
1750 tty.c_cflag |= CS6;
1751 break;
1752 case 5:
1753 tty.c_cflag |= CS5;
1754 break;
1756 switch(parity) {
1757 default:
1758 case 'N':
1759 break;
1760 case 'E':
1761 tty.c_cflag |= PARENB;
1762 break;
1763 case 'O':
1764 tty.c_cflag |= PARENB | PARODD;
1765 break;
1767 if (stop_bits == 2)
1768 tty.c_cflag |= CSTOPB;
1770 tcsetattr (fd, TCSANOW, &tty);
1773 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1775 FDCharDriver *s = chr->opaque;
1777 switch(cmd) {
1778 case CHR_IOCTL_SERIAL_SET_PARAMS:
1780 QEMUSerialSetParams *ssp = arg;
1781 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1782 ssp->data_bits, ssp->stop_bits);
1784 break;
1785 case CHR_IOCTL_SERIAL_SET_BREAK:
1787 int enable = *(int *)arg;
1788 if (enable)
1789 tcsendbreak(s->fd_in, 1);
1791 break;
1792 default:
1793 return -ENOTSUP;
1795 return 0;
1798 static CharDriverState *qemu_chr_open_tty(const char *filename)
1800 CharDriverState *chr;
1801 int fd;
1803 fd = open(filename, O_RDWR | O_NONBLOCK);
1804 if (fd < 0)
1805 return NULL;
1806 fcntl(fd, F_SETFL, O_NONBLOCK);
1807 tty_serial_init(fd, 115200, 'N', 8, 1);
1808 chr = qemu_chr_open_fd(fd, fd);
1809 if (!chr)
1810 return NULL;
1811 chr->chr_ioctl = tty_serial_ioctl;
1812 qemu_chr_reset(chr);
1813 return chr;
1816 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1818 int fd = (int)chr->opaque;
1819 uint8_t b;
1821 switch(cmd) {
1822 case CHR_IOCTL_PP_READ_DATA:
1823 if (ioctl(fd, PPRDATA, &b) < 0)
1824 return -ENOTSUP;
1825 *(uint8_t *)arg = b;
1826 break;
1827 case CHR_IOCTL_PP_WRITE_DATA:
1828 b = *(uint8_t *)arg;
1829 if (ioctl(fd, PPWDATA, &b) < 0)
1830 return -ENOTSUP;
1831 break;
1832 case CHR_IOCTL_PP_READ_CONTROL:
1833 if (ioctl(fd, PPRCONTROL, &b) < 0)
1834 return -ENOTSUP;
1835 *(uint8_t *)arg = b;
1836 break;
1837 case CHR_IOCTL_PP_WRITE_CONTROL:
1838 b = *(uint8_t *)arg;
1839 if (ioctl(fd, PPWCONTROL, &b) < 0)
1840 return -ENOTSUP;
1841 break;
1842 case CHR_IOCTL_PP_READ_STATUS:
1843 if (ioctl(fd, PPRSTATUS, &b) < 0)
1844 return -ENOTSUP;
1845 *(uint8_t *)arg = b;
1846 break;
1847 default:
1848 return -ENOTSUP;
1850 return 0;
1853 static CharDriverState *qemu_chr_open_pp(const char *filename)
1855 CharDriverState *chr;
1856 int fd;
1858 fd = open(filename, O_RDWR);
1859 if (fd < 0)
1860 return NULL;
1862 if (ioctl(fd, PPCLAIM) < 0) {
1863 close(fd);
1864 return NULL;
1867 chr = qemu_mallocz(sizeof(CharDriverState));
1868 if (!chr) {
1869 close(fd);
1870 return NULL;
1872 chr->opaque = (void *)fd;
1873 chr->chr_write = null_chr_write;
1874 chr->chr_ioctl = pp_ioctl;
1876 qemu_chr_reset(chr);
1878 return chr;
1881 #else
1882 static CharDriverState *qemu_chr_open_pty(void)
1884 return NULL;
1886 #endif
1888 #endif /* !defined(_WIN32) */
1890 #ifdef _WIN32
1891 typedef struct {
1892 CharDriverState *chr;
1893 int max_size;
1894 HANDLE hcom, hrecv, hsend;
1895 OVERLAPPED orecv, osend;
1896 BOOL fpipe;
1897 DWORD len;
1898 } WinCharState;
1900 #define NSENDBUF 2048
1901 #define NRECVBUF 2048
1902 #define MAXCONNECT 1
1903 #define NTIMEOUT 5000
1905 static int win_chr_poll(void *opaque);
1906 static int win_chr_pipe_poll(void *opaque);
1908 static void win_chr_close2(WinCharState *s)
1910 if (s->hsend) {
1911 CloseHandle(s->hsend);
1912 s->hsend = NULL;
1914 if (s->hrecv) {
1915 CloseHandle(s->hrecv);
1916 s->hrecv = NULL;
1918 if (s->hcom) {
1919 CloseHandle(s->hcom);
1920 s->hcom = NULL;
1922 if (s->fpipe)
1923 qemu_del_polling_cb(win_chr_pipe_poll, s);
1924 else
1925 qemu_del_polling_cb(win_chr_poll, s);
1928 static void win_chr_close(CharDriverState *chr)
1930 WinCharState *s = chr->opaque;
1931 win_chr_close2(s);
1934 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
1936 COMMCONFIG comcfg;
1937 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1938 COMSTAT comstat;
1939 DWORD size;
1940 DWORD err;
1942 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1943 if (!s->hsend) {
1944 fprintf(stderr, "Failed CreateEvent\n");
1945 goto fail;
1947 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1948 if (!s->hrecv) {
1949 fprintf(stderr, "Failed CreateEvent\n");
1950 goto fail;
1953 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1954 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1955 if (s->hcom == INVALID_HANDLE_VALUE) {
1956 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1957 s->hcom = NULL;
1958 goto fail;
1961 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1962 fprintf(stderr, "Failed SetupComm\n");
1963 goto fail;
1966 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1967 size = sizeof(COMMCONFIG);
1968 GetDefaultCommConfig(filename, &comcfg, &size);
1969 comcfg.dcb.DCBlength = sizeof(DCB);
1970 CommConfigDialog(filename, NULL, &comcfg);
1972 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1973 fprintf(stderr, "Failed SetCommState\n");
1974 goto fail;
1977 if (!SetCommMask(s->hcom, EV_ERR)) {
1978 fprintf(stderr, "Failed SetCommMask\n");
1979 goto fail;
1982 cto.ReadIntervalTimeout = MAXDWORD;
1983 if (!SetCommTimeouts(s->hcom, &cto)) {
1984 fprintf(stderr, "Failed SetCommTimeouts\n");
1985 goto fail;
1988 if (!ClearCommError(s->hcom, &err, &comstat)) {
1989 fprintf(stderr, "Failed ClearCommError\n");
1990 goto fail;
1992 s->chr = chr;
1993 qemu_add_polling_cb(win_chr_poll, s);
1994 return 0;
1996 fail:
1997 win_chr_close2(s);
1998 return -1;
2001 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2003 WinCharState *s = chr->opaque;
2004 DWORD len, ret, size, err;
2006 len = len1;
2007 ZeroMemory(&s->osend, sizeof(s->osend));
2008 s->osend.hEvent = s->hsend;
2009 while (len > 0) {
2010 if (s->hsend)
2011 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2012 else
2013 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2014 if (!ret) {
2015 err = GetLastError();
2016 if (err == ERROR_IO_PENDING) {
2017 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2018 if (ret) {
2019 buf += size;
2020 len -= size;
2021 } else {
2022 break;
2024 } else {
2025 break;
2027 } else {
2028 buf += size;
2029 len -= size;
2032 return len1 - len;
2035 static int win_chr_read_poll(WinCharState *s)
2037 s->max_size = qemu_chr_can_read(s->chr);
2038 return s->max_size;
2041 static void win_chr_readfile(WinCharState *s)
2043 int ret, err;
2044 uint8_t buf[1024];
2045 DWORD size;
2047 ZeroMemory(&s->orecv, sizeof(s->orecv));
2048 s->orecv.hEvent = s->hrecv;
2049 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2050 if (!ret) {
2051 err = GetLastError();
2052 if (err == ERROR_IO_PENDING) {
2053 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2057 if (size > 0) {
2058 qemu_chr_read(s->chr, buf, size);
2062 static void win_chr_read(WinCharState *s)
2064 if (s->len > s->max_size)
2065 s->len = s->max_size;
2066 if (s->len == 0)
2067 return;
2069 win_chr_readfile(s);
2072 static int win_chr_poll(void *opaque)
2074 WinCharState *s = opaque;
2075 COMSTAT status;
2076 DWORD comerr;
2078 ClearCommError(s->hcom, &comerr, &status);
2079 if (status.cbInQue > 0) {
2080 s->len = status.cbInQue;
2081 win_chr_read_poll(s);
2082 win_chr_read(s);
2083 return 1;
2085 return 0;
2088 static CharDriverState *qemu_chr_open_win(const char *filename)
2090 CharDriverState *chr;
2091 WinCharState *s;
2093 chr = qemu_mallocz(sizeof(CharDriverState));
2094 if (!chr)
2095 return NULL;
2096 s = qemu_mallocz(sizeof(WinCharState));
2097 if (!s) {
2098 free(chr);
2099 return NULL;
2101 chr->opaque = s;
2102 chr->chr_write = win_chr_write;
2103 chr->chr_close = win_chr_close;
2105 if (win_chr_init(s, chr, filename) < 0) {
2106 free(s);
2107 free(chr);
2108 return NULL;
2110 qemu_chr_reset(chr);
2111 return chr;
2114 static int win_chr_pipe_poll(void *opaque)
2116 WinCharState *s = opaque;
2117 DWORD size;
2119 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2120 if (size > 0) {
2121 s->len = size;
2122 win_chr_read_poll(s);
2123 win_chr_read(s);
2124 return 1;
2126 return 0;
2129 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2131 OVERLAPPED ov;
2132 int ret;
2133 DWORD size;
2134 char openname[256];
2136 s->fpipe = TRUE;
2138 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2139 if (!s->hsend) {
2140 fprintf(stderr, "Failed CreateEvent\n");
2141 goto fail;
2143 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2144 if (!s->hrecv) {
2145 fprintf(stderr, "Failed CreateEvent\n");
2146 goto fail;
2149 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2150 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2151 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2152 PIPE_WAIT,
2153 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2154 if (s->hcom == INVALID_HANDLE_VALUE) {
2155 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2156 s->hcom = NULL;
2157 goto fail;
2160 ZeroMemory(&ov, sizeof(ov));
2161 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2162 ret = ConnectNamedPipe(s->hcom, &ov);
2163 if (ret) {
2164 fprintf(stderr, "Failed ConnectNamedPipe\n");
2165 goto fail;
2168 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2169 if (!ret) {
2170 fprintf(stderr, "Failed GetOverlappedResult\n");
2171 if (ov.hEvent) {
2172 CloseHandle(ov.hEvent);
2173 ov.hEvent = NULL;
2175 goto fail;
2178 if (ov.hEvent) {
2179 CloseHandle(ov.hEvent);
2180 ov.hEvent = NULL;
2182 qemu_add_polling_cb(win_chr_pipe_poll, s);
2183 return 0;
2185 fail:
2186 win_chr_close2(s);
2187 return -1;
2191 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2193 CharDriverState *chr;
2194 WinCharState *s;
2196 chr = qemu_mallocz(sizeof(CharDriverState));
2197 if (!chr)
2198 return NULL;
2199 s = qemu_mallocz(sizeof(WinCharState));
2200 if (!s) {
2201 free(chr);
2202 return NULL;
2204 chr->opaque = s;
2205 chr->chr_write = win_chr_write;
2206 chr->chr_close = win_chr_close;
2208 if (win_chr_pipe_init(s, filename) < 0) {
2209 free(s);
2210 free(chr);
2211 return NULL;
2213 qemu_chr_reset(chr);
2214 return chr;
2217 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2219 CharDriverState *chr;
2220 WinCharState *s;
2222 chr = qemu_mallocz(sizeof(CharDriverState));
2223 if (!chr)
2224 return NULL;
2225 s = qemu_mallocz(sizeof(WinCharState));
2226 if (!s) {
2227 free(chr);
2228 return NULL;
2230 s->hcom = fd_out;
2231 chr->opaque = s;
2232 chr->chr_write = win_chr_write;
2233 qemu_chr_reset(chr);
2234 return chr;
2237 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2239 HANDLE fd_out;
2241 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2242 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2243 if (fd_out == INVALID_HANDLE_VALUE)
2244 return NULL;
2246 return qemu_chr_open_win_file(fd_out);
2248 #endif
2250 /***********************************************************/
2251 /* UDP Net console */
2253 typedef struct {
2254 int fd;
2255 struct sockaddr_in daddr;
2256 char buf[1024];
2257 int bufcnt;
2258 int bufptr;
2259 int max_size;
2260 } NetCharDriver;
2262 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2264 NetCharDriver *s = chr->opaque;
2266 return sendto(s->fd, buf, len, 0,
2267 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2270 static int udp_chr_read_poll(void *opaque)
2272 CharDriverState *chr = opaque;
2273 NetCharDriver *s = chr->opaque;
2275 s->max_size = qemu_chr_can_read(chr);
2277 /* If there were any stray characters in the queue process them
2278 * first
2280 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2281 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2282 s->bufptr++;
2283 s->max_size = qemu_chr_can_read(chr);
2285 return s->max_size;
2288 static void udp_chr_read(void *opaque)
2290 CharDriverState *chr = opaque;
2291 NetCharDriver *s = chr->opaque;
2293 if (s->max_size == 0)
2294 return;
2295 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2296 s->bufptr = s->bufcnt;
2297 if (s->bufcnt <= 0)
2298 return;
2300 s->bufptr = 0;
2301 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2302 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2303 s->bufptr++;
2304 s->max_size = qemu_chr_can_read(chr);
2308 static void udp_chr_update_read_handler(CharDriverState *chr)
2310 NetCharDriver *s = chr->opaque;
2312 if (s->fd >= 0) {
2313 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2314 udp_chr_read, NULL, chr);
2318 #ifndef _WIN32
2319 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2320 #endif
2321 int parse_host_src_port(struct sockaddr_in *haddr,
2322 struct sockaddr_in *saddr,
2323 const char *str);
2325 static CharDriverState *qemu_chr_open_udp(const char *def)
2327 CharDriverState *chr = NULL;
2328 NetCharDriver *s = NULL;
2329 int fd = -1;
2330 struct sockaddr_in saddr;
2332 chr = qemu_mallocz(sizeof(CharDriverState));
2333 if (!chr)
2334 goto return_err;
2335 s = qemu_mallocz(sizeof(NetCharDriver));
2336 if (!s)
2337 goto return_err;
2339 fd = socket(PF_INET, SOCK_DGRAM, 0);
2340 if (fd < 0) {
2341 perror("socket(PF_INET, SOCK_DGRAM)");
2342 goto return_err;
2345 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2346 printf("Could not parse: %s\n", def);
2347 goto return_err;
2350 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2352 perror("bind");
2353 goto return_err;
2356 s->fd = fd;
2357 s->bufcnt = 0;
2358 s->bufptr = 0;
2359 chr->opaque = s;
2360 chr->chr_write = udp_chr_write;
2361 chr->chr_update_read_handler = udp_chr_update_read_handler;
2362 return chr;
2364 return_err:
2365 if (chr)
2366 free(chr);
2367 if (s)
2368 free(s);
2369 if (fd >= 0)
2370 closesocket(fd);
2371 return NULL;
2374 /***********************************************************/
2375 /* TCP Net console */
2377 typedef struct {
2378 int fd, listen_fd;
2379 int connected;
2380 int max_size;
2381 int do_telnetopt;
2382 int do_nodelay;
2383 int is_unix;
2384 } TCPCharDriver;
2386 static void tcp_chr_accept(void *opaque);
2388 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2390 TCPCharDriver *s = chr->opaque;
2391 if (s->connected) {
2392 return send_all(s->fd, buf, len);
2393 } else {
2394 /* XXX: indicate an error ? */
2395 return len;
2399 static int tcp_chr_read_poll(void *opaque)
2401 CharDriverState *chr = opaque;
2402 TCPCharDriver *s = chr->opaque;
2403 if (!s->connected)
2404 return 0;
2405 s->max_size = qemu_chr_can_read(chr);
2406 return s->max_size;
2409 #define IAC 255
2410 #define IAC_BREAK 243
2411 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2412 TCPCharDriver *s,
2413 char *buf, int *size)
2415 /* Handle any telnet client's basic IAC options to satisfy char by
2416 * char mode with no echo. All IAC options will be removed from
2417 * the buf and the do_telnetopt variable will be used to track the
2418 * state of the width of the IAC information.
2420 * IAC commands come in sets of 3 bytes with the exception of the
2421 * "IAC BREAK" command and the double IAC.
2424 int i;
2425 int j = 0;
2427 for (i = 0; i < *size; i++) {
2428 if (s->do_telnetopt > 1) {
2429 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2430 /* Double IAC means send an IAC */
2431 if (j != i)
2432 buf[j] = buf[i];
2433 j++;
2434 s->do_telnetopt = 1;
2435 } else {
2436 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2437 /* Handle IAC break commands by sending a serial break */
2438 qemu_chr_event(chr, CHR_EVENT_BREAK);
2439 s->do_telnetopt++;
2441 s->do_telnetopt++;
2443 if (s->do_telnetopt >= 4) {
2444 s->do_telnetopt = 1;
2446 } else {
2447 if ((unsigned char)buf[i] == IAC) {
2448 s->do_telnetopt = 2;
2449 } else {
2450 if (j != i)
2451 buf[j] = buf[i];
2452 j++;
2456 *size = j;
2459 static void tcp_chr_read(void *opaque)
2461 CharDriverState *chr = opaque;
2462 TCPCharDriver *s = chr->opaque;
2463 uint8_t buf[1024];
2464 int len, size;
2466 if (!s->connected || s->max_size <= 0)
2467 return;
2468 len = sizeof(buf);
2469 if (len > s->max_size)
2470 len = s->max_size;
2471 size = recv(s->fd, buf, len, 0);
2472 if (size == 0) {
2473 /* connection closed */
2474 s->connected = 0;
2475 if (s->listen_fd >= 0) {
2476 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2478 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2479 closesocket(s->fd);
2480 s->fd = -1;
2481 } else if (size > 0) {
2482 if (s->do_telnetopt)
2483 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2484 if (size > 0)
2485 qemu_chr_read(chr, buf, size);
2489 static void tcp_chr_connect(void *opaque)
2491 CharDriverState *chr = opaque;
2492 TCPCharDriver *s = chr->opaque;
2494 s->connected = 1;
2495 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2496 tcp_chr_read, NULL, chr);
2497 qemu_chr_reset(chr);
2500 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2501 static void tcp_chr_telnet_init(int fd)
2503 char buf[3];
2504 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2505 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2506 send(fd, (char *)buf, 3, 0);
2507 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2508 send(fd, (char *)buf, 3, 0);
2509 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2510 send(fd, (char *)buf, 3, 0);
2511 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2512 send(fd, (char *)buf, 3, 0);
2515 static void socket_set_nodelay(int fd)
2517 int val = 1;
2518 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2521 static void tcp_chr_accept(void *opaque)
2523 CharDriverState *chr = opaque;
2524 TCPCharDriver *s = chr->opaque;
2525 struct sockaddr_in saddr;
2526 #ifndef _WIN32
2527 struct sockaddr_un uaddr;
2528 #endif
2529 struct sockaddr *addr;
2530 socklen_t len;
2531 int fd;
2533 for(;;) {
2534 #ifndef _WIN32
2535 if (s->is_unix) {
2536 len = sizeof(uaddr);
2537 addr = (struct sockaddr *)&uaddr;
2538 } else
2539 #endif
2541 len = sizeof(saddr);
2542 addr = (struct sockaddr *)&saddr;
2544 fd = accept(s->listen_fd, addr, &len);
2545 if (fd < 0 && errno != EINTR) {
2546 return;
2547 } else if (fd >= 0) {
2548 if (s->do_telnetopt)
2549 tcp_chr_telnet_init(fd);
2550 break;
2553 socket_set_nonblock(fd);
2554 if (s->do_nodelay)
2555 socket_set_nodelay(fd);
2556 s->fd = fd;
2557 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2558 tcp_chr_connect(chr);
2561 static void tcp_chr_close(CharDriverState *chr)
2563 TCPCharDriver *s = chr->opaque;
2564 if (s->fd >= 0)
2565 closesocket(s->fd);
2566 if (s->listen_fd >= 0)
2567 closesocket(s->listen_fd);
2568 qemu_free(s);
2571 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2572 int is_telnet,
2573 int is_unix)
2575 CharDriverState *chr = NULL;
2576 TCPCharDriver *s = NULL;
2577 int fd = -1, ret, err, val;
2578 int is_listen = 0;
2579 int is_waitconnect = 1;
2580 int do_nodelay = 0;
2581 const char *ptr;
2582 struct sockaddr_in saddr;
2583 #ifndef _WIN32
2584 struct sockaddr_un uaddr;
2585 #endif
2586 struct sockaddr *addr;
2587 socklen_t addrlen;
2589 #ifndef _WIN32
2590 if (is_unix) {
2591 addr = (struct sockaddr *)&uaddr;
2592 addrlen = sizeof(uaddr);
2593 if (parse_unix_path(&uaddr, host_str) < 0)
2594 goto fail;
2595 } else
2596 #endif
2598 addr = (struct sockaddr *)&saddr;
2599 addrlen = sizeof(saddr);
2600 if (parse_host_port(&saddr, host_str) < 0)
2601 goto fail;
2604 ptr = host_str;
2605 while((ptr = strchr(ptr,','))) {
2606 ptr++;
2607 if (!strncmp(ptr,"server",6)) {
2608 is_listen = 1;
2609 } else if (!strncmp(ptr,"nowait",6)) {
2610 is_waitconnect = 0;
2611 } else if (!strncmp(ptr,"nodelay",6)) {
2612 do_nodelay = 1;
2613 } else {
2614 printf("Unknown option: %s\n", ptr);
2615 goto fail;
2618 if (!is_listen)
2619 is_waitconnect = 0;
2621 chr = qemu_mallocz(sizeof(CharDriverState));
2622 if (!chr)
2623 goto fail;
2624 s = qemu_mallocz(sizeof(TCPCharDriver));
2625 if (!s)
2626 goto fail;
2628 #ifndef _WIN32
2629 if (is_unix)
2630 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2631 else
2632 #endif
2633 fd = socket(PF_INET, SOCK_STREAM, 0);
2635 if (fd < 0)
2636 goto fail;
2638 if (!is_waitconnect)
2639 socket_set_nonblock(fd);
2641 s->connected = 0;
2642 s->fd = -1;
2643 s->listen_fd = -1;
2644 s->is_unix = is_unix;
2645 s->do_nodelay = do_nodelay && !is_unix;
2647 chr->opaque = s;
2648 chr->chr_write = tcp_chr_write;
2649 chr->chr_close = tcp_chr_close;
2651 if (is_listen) {
2652 /* allow fast reuse */
2653 #ifndef _WIN32
2654 if (is_unix) {
2655 char path[109];
2656 strncpy(path, uaddr.sun_path, 108);
2657 path[108] = 0;
2658 unlink(path);
2659 } else
2660 #endif
2662 val = 1;
2663 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2666 ret = bind(fd, addr, addrlen);
2667 if (ret < 0)
2668 goto fail;
2670 ret = listen(fd, 0);
2671 if (ret < 0)
2672 goto fail;
2674 s->listen_fd = fd;
2675 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2676 if (is_telnet)
2677 s->do_telnetopt = 1;
2678 } else {
2679 for(;;) {
2680 ret = connect(fd, addr, addrlen);
2681 if (ret < 0) {
2682 err = socket_error();
2683 if (err == EINTR || err == EWOULDBLOCK) {
2684 } else if (err == EINPROGRESS) {
2685 break;
2686 } else {
2687 goto fail;
2689 } else {
2690 s->connected = 1;
2691 break;
2694 s->fd = fd;
2695 socket_set_nodelay(fd);
2696 if (s->connected)
2697 tcp_chr_connect(chr);
2698 else
2699 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2702 if (is_listen && is_waitconnect) {
2703 printf("QEMU waiting for connection on: %s\n", host_str);
2704 tcp_chr_accept(chr);
2705 socket_set_nonblock(s->listen_fd);
2708 return chr;
2709 fail:
2710 if (fd >= 0)
2711 closesocket(fd);
2712 qemu_free(s);
2713 qemu_free(chr);
2714 return NULL;
2717 CharDriverState *qemu_chr_open(const char *filename)
2719 const char *p;
2721 if (!strcmp(filename, "vc")) {
2722 return text_console_init(&display_state);
2723 } else if (!strcmp(filename, "null")) {
2724 return qemu_chr_open_null();
2725 } else
2726 if (strstart(filename, "tcp:", &p)) {
2727 return qemu_chr_open_tcp(p, 0, 0);
2728 } else
2729 if (strstart(filename, "telnet:", &p)) {
2730 return qemu_chr_open_tcp(p, 1, 0);
2731 } else
2732 if (strstart(filename, "udp:", &p)) {
2733 return qemu_chr_open_udp(p);
2734 } else
2735 #ifndef _WIN32
2736 if (strstart(filename, "unix:", &p)) {
2737 return qemu_chr_open_tcp(p, 0, 1);
2738 } else if (strstart(filename, "file:", &p)) {
2739 return qemu_chr_open_file_out(p);
2740 } else if (strstart(filename, "pipe:", &p)) {
2741 return qemu_chr_open_pipe(p);
2742 } else if (!strcmp(filename, "pty")) {
2743 return qemu_chr_open_pty();
2744 } else if (!strcmp(filename, "stdio")) {
2745 return qemu_chr_open_stdio();
2746 } else
2747 #endif
2748 #if defined(__linux__)
2749 if (strstart(filename, "/dev/parport", NULL)) {
2750 return qemu_chr_open_pp(filename);
2751 } else
2752 if (strstart(filename, "/dev/", NULL)) {
2753 return qemu_chr_open_tty(filename);
2754 } else
2755 #endif
2756 #ifdef _WIN32
2757 if (strstart(filename, "COM", NULL)) {
2758 return qemu_chr_open_win(filename);
2759 } else
2760 if (strstart(filename, "pipe:", &p)) {
2761 return qemu_chr_open_win_pipe(p);
2762 } else
2763 if (strstart(filename, "file:", &p)) {
2764 return qemu_chr_open_win_file_out(p);
2766 #endif
2768 return NULL;
2772 void qemu_chr_close(CharDriverState *chr)
2774 if (chr->chr_close)
2775 chr->chr_close(chr);
2778 /***********************************************************/
2779 /* network device redirectors */
2781 void hex_dump(FILE *f, const uint8_t *buf, int size)
2783 int len, i, j, c;
2785 for(i=0;i<size;i+=16) {
2786 len = size - i;
2787 if (len > 16)
2788 len = 16;
2789 fprintf(f, "%08x ", i);
2790 for(j=0;j<16;j++) {
2791 if (j < len)
2792 fprintf(f, " %02x", buf[i+j]);
2793 else
2794 fprintf(f, " ");
2796 fprintf(f, " ");
2797 for(j=0;j<len;j++) {
2798 c = buf[i+j];
2799 if (c < ' ' || c > '~')
2800 c = '.';
2801 fprintf(f, "%c", c);
2803 fprintf(f, "\n");
2807 static int parse_macaddr(uint8_t *macaddr, const char *p)
2809 int i;
2810 for(i = 0; i < 6; i++) {
2811 macaddr[i] = strtol(p, (char **)&p, 16);
2812 if (i == 5) {
2813 if (*p != '\0')
2814 return -1;
2815 } else {
2816 if (*p != ':')
2817 return -1;
2818 p++;
2821 return 0;
2824 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2826 const char *p, *p1;
2827 int len;
2828 p = *pp;
2829 p1 = strchr(p, sep);
2830 if (!p1)
2831 return -1;
2832 len = p1 - p;
2833 p1++;
2834 if (buf_size > 0) {
2835 if (len > buf_size - 1)
2836 len = buf_size - 1;
2837 memcpy(buf, p, len);
2838 buf[len] = '\0';
2840 *pp = p1;
2841 return 0;
2844 int parse_host_src_port(struct sockaddr_in *haddr,
2845 struct sockaddr_in *saddr,
2846 const char *input_str)
2848 char *str = strdup(input_str);
2849 char *host_str = str;
2850 char *src_str;
2851 char *ptr;
2854 * Chop off any extra arguments at the end of the string which
2855 * would start with a comma, then fill in the src port information
2856 * if it was provided else use the "any address" and "any port".
2858 if ((ptr = strchr(str,',')))
2859 *ptr = '\0';
2861 if ((src_str = strchr(input_str,'@'))) {
2862 *src_str = '\0';
2863 src_str++;
2866 if (parse_host_port(haddr, host_str) < 0)
2867 goto fail;
2869 if (!src_str || *src_str == '\0')
2870 src_str = ":0";
2872 if (parse_host_port(saddr, src_str) < 0)
2873 goto fail;
2875 free(str);
2876 return(0);
2878 fail:
2879 free(str);
2880 return -1;
2883 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2885 char buf[512];
2886 struct hostent *he;
2887 const char *p, *r;
2888 int port;
2890 p = str;
2891 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2892 return -1;
2893 saddr->sin_family = AF_INET;
2894 if (buf[0] == '\0') {
2895 saddr->sin_addr.s_addr = 0;
2896 } else {
2897 if (isdigit(buf[0])) {
2898 if (!inet_aton(buf, &saddr->sin_addr))
2899 return -1;
2900 } else {
2901 if ((he = gethostbyname(buf)) == NULL)
2902 return - 1;
2903 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2906 port = strtol(p, (char **)&r, 0);
2907 if (r == p)
2908 return -1;
2909 saddr->sin_port = htons(port);
2910 return 0;
2913 #ifndef _WIN32
2914 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2916 const char *p;
2917 int len;
2919 len = MIN(108, strlen(str));
2920 p = strchr(str, ',');
2921 if (p)
2922 len = MIN(len, p - str);
2924 memset(uaddr, 0, sizeof(*uaddr));
2926 uaddr->sun_family = AF_UNIX;
2927 memcpy(uaddr->sun_path, str, len);
2929 return 0;
2931 #endif
2933 /* find or alloc a new VLAN */
2934 VLANState *qemu_find_vlan(int id)
2936 VLANState **pvlan, *vlan;
2937 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2938 if (vlan->id == id)
2939 return vlan;
2941 vlan = qemu_mallocz(sizeof(VLANState));
2942 if (!vlan)
2943 return NULL;
2944 vlan->id = id;
2945 vlan->next = NULL;
2946 pvlan = &first_vlan;
2947 while (*pvlan != NULL)
2948 pvlan = &(*pvlan)->next;
2949 *pvlan = vlan;
2950 return vlan;
2953 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2954 IOReadHandler *fd_read,
2955 IOCanRWHandler *fd_can_read,
2956 void *opaque)
2958 VLANClientState *vc, **pvc;
2959 vc = qemu_mallocz(sizeof(VLANClientState));
2960 if (!vc)
2961 return NULL;
2962 vc->fd_read = fd_read;
2963 vc->fd_can_read = fd_can_read;
2964 vc->opaque = opaque;
2965 vc->vlan = vlan;
2967 vc->next = NULL;
2968 pvc = &vlan->first_client;
2969 while (*pvc != NULL)
2970 pvc = &(*pvc)->next;
2971 *pvc = vc;
2972 return vc;
2975 int qemu_can_send_packet(VLANClientState *vc1)
2977 VLANState *vlan = vc1->vlan;
2978 VLANClientState *vc;
2980 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2981 if (vc != vc1) {
2982 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2983 return 0;
2986 return 1;
2989 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2991 VLANState *vlan = vc1->vlan;
2992 VLANClientState *vc;
2994 #if 0
2995 printf("vlan %d send:\n", vlan->id);
2996 hex_dump(stdout, buf, size);
2997 #endif
2998 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2999 if (vc != vc1) {
3000 vc->fd_read(vc->opaque, buf, size);
3005 #if defined(CONFIG_SLIRP)
3007 /* slirp network adapter */
3009 static int slirp_inited;
3010 static VLANClientState *slirp_vc;
3012 int slirp_can_output(void)
3014 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3017 void slirp_output(const uint8_t *pkt, int pkt_len)
3019 #if 0
3020 printf("slirp output:\n");
3021 hex_dump(stdout, pkt, pkt_len);
3022 #endif
3023 if (!slirp_vc)
3024 return;
3025 qemu_send_packet(slirp_vc, pkt, pkt_len);
3028 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3030 #if 0
3031 printf("slirp input:\n");
3032 hex_dump(stdout, buf, size);
3033 #endif
3034 slirp_input(buf, size);
3037 static int net_slirp_init(VLANState *vlan)
3039 if (!slirp_inited) {
3040 slirp_inited = 1;
3041 slirp_init();
3043 slirp_vc = qemu_new_vlan_client(vlan,
3044 slirp_receive, NULL, NULL);
3045 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3046 return 0;
3049 static void net_slirp_redir(const char *redir_str)
3051 int is_udp;
3052 char buf[256], *r;
3053 const char *p;
3054 struct in_addr guest_addr;
3055 int host_port, guest_port;
3057 if (!slirp_inited) {
3058 slirp_inited = 1;
3059 slirp_init();
3062 p = redir_str;
3063 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3064 goto fail;
3065 if (!strcmp(buf, "tcp")) {
3066 is_udp = 0;
3067 } else if (!strcmp(buf, "udp")) {
3068 is_udp = 1;
3069 } else {
3070 goto fail;
3073 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3074 goto fail;
3075 host_port = strtol(buf, &r, 0);
3076 if (r == buf)
3077 goto fail;
3079 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3080 goto fail;
3081 if (buf[0] == '\0') {
3082 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3084 if (!inet_aton(buf, &guest_addr))
3085 goto fail;
3087 guest_port = strtol(p, &r, 0);
3088 if (r == p)
3089 goto fail;
3091 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3092 fprintf(stderr, "qemu: could not set up redirection\n");
3093 exit(1);
3095 return;
3096 fail:
3097 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3098 exit(1);
3101 #ifndef _WIN32
3103 char smb_dir[1024];
3105 static void smb_exit(void)
3107 DIR *d;
3108 struct dirent *de;
3109 char filename[1024];
3111 /* erase all the files in the directory */
3112 d = opendir(smb_dir);
3113 for(;;) {
3114 de = readdir(d);
3115 if (!de)
3116 break;
3117 if (strcmp(de->d_name, ".") != 0 &&
3118 strcmp(de->d_name, "..") != 0) {
3119 snprintf(filename, sizeof(filename), "%s/%s",
3120 smb_dir, de->d_name);
3121 unlink(filename);
3124 closedir(d);
3125 rmdir(smb_dir);
3128 /* automatic user mode samba server configuration */
3129 void net_slirp_smb(const char *exported_dir)
3131 char smb_conf[1024];
3132 char smb_cmdline[1024];
3133 FILE *f;
3135 if (!slirp_inited) {
3136 slirp_inited = 1;
3137 slirp_init();
3140 /* XXX: better tmp dir construction */
3141 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3142 if (mkdir(smb_dir, 0700) < 0) {
3143 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3144 exit(1);
3146 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3148 f = fopen(smb_conf, "w");
3149 if (!f) {
3150 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3151 exit(1);
3153 fprintf(f,
3154 "[global]\n"
3155 "private dir=%s\n"
3156 "smb ports=0\n"
3157 "socket address=127.0.0.1\n"
3158 "pid directory=%s\n"
3159 "lock directory=%s\n"
3160 "log file=%s/log.smbd\n"
3161 "smb passwd file=%s/smbpasswd\n"
3162 "security = share\n"
3163 "[qemu]\n"
3164 "path=%s\n"
3165 "read only=no\n"
3166 "guest ok=yes\n",
3167 smb_dir,
3168 smb_dir,
3169 smb_dir,
3170 smb_dir,
3171 smb_dir,
3172 exported_dir
3174 fclose(f);
3175 atexit(smb_exit);
3177 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3178 SMBD_COMMAND, smb_conf);
3180 slirp_add_exec(0, smb_cmdline, 4, 139);
3183 #endif /* !defined(_WIN32) */
3185 #endif /* CONFIG_SLIRP */
3187 #if !defined(_WIN32)
3189 typedef struct TAPState {
3190 VLANClientState *vc;
3191 int fd;
3192 } TAPState;
3194 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3196 TAPState *s = opaque;
3197 int ret;
3198 for(;;) {
3199 ret = write(s->fd, buf, size);
3200 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3201 } else {
3202 break;
3207 static void tap_send(void *opaque)
3209 TAPState *s = opaque;
3210 uint8_t buf[4096];
3211 int size;
3213 size = read(s->fd, buf, sizeof(buf));
3214 if (size > 0) {
3215 qemu_send_packet(s->vc, buf, size);
3219 /* fd support */
3221 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3223 TAPState *s;
3225 s = qemu_mallocz(sizeof(TAPState));
3226 if (!s)
3227 return NULL;
3228 s->fd = fd;
3229 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3230 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3231 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3232 return s;
3235 #ifdef _BSD
3236 static int tap_open(char *ifname, int ifname_size)
3238 int fd;
3239 char *dev;
3240 struct stat s;
3242 fd = open("/dev/tap", O_RDWR);
3243 if (fd < 0) {
3244 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3245 return -1;
3248 fstat(fd, &s);
3249 dev = devname(s.st_rdev, S_IFCHR);
3250 pstrcpy(ifname, ifname_size, dev);
3252 fcntl(fd, F_SETFL, O_NONBLOCK);
3253 return fd;
3255 #elif defined(__sun__)
3256 static int tap_open(char *ifname, int ifname_size)
3258 fprintf(stderr, "warning: tap_open not yet implemented\n");
3259 return -1;
3261 #else
3262 static int tap_open(char *ifname, int ifname_size)
3264 struct ifreq ifr;
3265 int fd, ret;
3267 fd = open("/dev/net/tun", O_RDWR);
3268 if (fd < 0) {
3269 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3270 return -1;
3272 memset(&ifr, 0, sizeof(ifr));
3273 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3274 if (ifname[0] != '\0')
3275 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3276 else
3277 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3278 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3279 if (ret != 0) {
3280 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3281 close(fd);
3282 return -1;
3284 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3285 fcntl(fd, F_SETFL, O_NONBLOCK);
3286 return fd;
3288 #endif
3290 static int net_tap_init(VLANState *vlan, const char *ifname1,
3291 const char *setup_script)
3293 TAPState *s;
3294 int pid, status, fd;
3295 char *args[3];
3296 char **parg;
3297 char ifname[128];
3299 if (ifname1 != NULL)
3300 pstrcpy(ifname, sizeof(ifname), ifname1);
3301 else
3302 ifname[0] = '\0';
3303 fd = tap_open(ifname, sizeof(ifname));
3304 if (fd < 0)
3305 return -1;
3307 if (!setup_script || !strcmp(setup_script, "no"))
3308 setup_script = "";
3309 if (setup_script[0] != '\0') {
3310 /* try to launch network init script */
3311 pid = fork();
3312 if (pid >= 0) {
3313 if (pid == 0) {
3314 parg = args;
3315 *parg++ = (char *)setup_script;
3316 *parg++ = ifname;
3317 *parg++ = NULL;
3318 execv(setup_script, args);
3319 _exit(1);
3321 while (waitpid(pid, &status, 0) != pid);
3322 if (!WIFEXITED(status) ||
3323 WEXITSTATUS(status) != 0) {
3324 fprintf(stderr, "%s: could not launch network script\n",
3325 setup_script);
3326 return -1;
3330 s = net_tap_fd_init(vlan, fd);
3331 if (!s)
3332 return -1;
3333 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3334 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3335 return 0;
3338 #endif /* !_WIN32 */
3340 /* network connection */
3341 typedef struct NetSocketState {
3342 VLANClientState *vc;
3343 int fd;
3344 int state; /* 0 = getting length, 1 = getting data */
3345 int index;
3346 int packet_len;
3347 uint8_t buf[4096];
3348 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3349 } NetSocketState;
3351 typedef struct NetSocketListenState {
3352 VLANState *vlan;
3353 int fd;
3354 } NetSocketListenState;
3356 /* XXX: we consider we can send the whole packet without blocking */
3357 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3359 NetSocketState *s = opaque;
3360 uint32_t len;
3361 len = htonl(size);
3363 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3364 send_all(s->fd, buf, size);
3367 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3369 NetSocketState *s = opaque;
3370 sendto(s->fd, buf, size, 0,
3371 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3374 static void net_socket_send(void *opaque)
3376 NetSocketState *s = opaque;
3377 int l, size, err;
3378 uint8_t buf1[4096];
3379 const uint8_t *buf;
3381 size = recv(s->fd, buf1, sizeof(buf1), 0);
3382 if (size < 0) {
3383 err = socket_error();
3384 if (err != EWOULDBLOCK)
3385 goto eoc;
3386 } else if (size == 0) {
3387 /* end of connection */
3388 eoc:
3389 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3390 closesocket(s->fd);
3391 return;
3393 buf = buf1;
3394 while (size > 0) {
3395 /* reassemble a packet from the network */
3396 switch(s->state) {
3397 case 0:
3398 l = 4 - s->index;
3399 if (l > size)
3400 l = size;
3401 memcpy(s->buf + s->index, buf, l);
3402 buf += l;
3403 size -= l;
3404 s->index += l;
3405 if (s->index == 4) {
3406 /* got length */
3407 s->packet_len = ntohl(*(uint32_t *)s->buf);
3408 s->index = 0;
3409 s->state = 1;
3411 break;
3412 case 1:
3413 l = s->packet_len - s->index;
3414 if (l > size)
3415 l = size;
3416 memcpy(s->buf + s->index, buf, l);
3417 s->index += l;
3418 buf += l;
3419 size -= l;
3420 if (s->index >= s->packet_len) {
3421 qemu_send_packet(s->vc, s->buf, s->packet_len);
3422 s->index = 0;
3423 s->state = 0;
3425 break;
3430 static void net_socket_send_dgram(void *opaque)
3432 NetSocketState *s = opaque;
3433 int size;
3435 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3436 if (size < 0)
3437 return;
3438 if (size == 0) {
3439 /* end of connection */
3440 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3441 return;
3443 qemu_send_packet(s->vc, s->buf, size);
3446 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3448 struct ip_mreq imr;
3449 int fd;
3450 int val, ret;
3451 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3452 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3453 inet_ntoa(mcastaddr->sin_addr),
3454 (int)ntohl(mcastaddr->sin_addr.s_addr));
3455 return -1;
3458 fd = socket(PF_INET, SOCK_DGRAM, 0);
3459 if (fd < 0) {
3460 perror("socket(PF_INET, SOCK_DGRAM)");
3461 return -1;
3464 val = 1;
3465 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3466 (const char *)&val, sizeof(val));
3467 if (ret < 0) {
3468 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3469 goto fail;
3472 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3473 if (ret < 0) {
3474 perror("bind");
3475 goto fail;
3478 /* Add host to multicast group */
3479 imr.imr_multiaddr = mcastaddr->sin_addr;
3480 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3482 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3483 (const char *)&imr, sizeof(struct ip_mreq));
3484 if (ret < 0) {
3485 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3486 goto fail;
3489 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3490 val = 1;
3491 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3492 (const char *)&val, sizeof(val));
3493 if (ret < 0) {
3494 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3495 goto fail;
3498 socket_set_nonblock(fd);
3499 return fd;
3500 fail:
3501 if (fd >= 0)
3502 closesocket(fd);
3503 return -1;
3506 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3507 int is_connected)
3509 struct sockaddr_in saddr;
3510 int newfd;
3511 socklen_t saddr_len;
3512 NetSocketState *s;
3514 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3515 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3516 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3519 if (is_connected) {
3520 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3521 /* must be bound */
3522 if (saddr.sin_addr.s_addr==0) {
3523 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3524 fd);
3525 return NULL;
3527 /* clone dgram socket */
3528 newfd = net_socket_mcast_create(&saddr);
3529 if (newfd < 0) {
3530 /* error already reported by net_socket_mcast_create() */
3531 close(fd);
3532 return NULL;
3534 /* clone newfd to fd, close newfd */
3535 dup2(newfd, fd);
3536 close(newfd);
3538 } else {
3539 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3540 fd, strerror(errno));
3541 return NULL;
3545 s = qemu_mallocz(sizeof(NetSocketState));
3546 if (!s)
3547 return NULL;
3548 s->fd = fd;
3550 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3551 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3553 /* mcast: save bound address as dst */
3554 if (is_connected) s->dgram_dst=saddr;
3556 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3557 "socket: fd=%d (%s mcast=%s:%d)",
3558 fd, is_connected? "cloned" : "",
3559 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3560 return s;
3563 static void net_socket_connect(void *opaque)
3565 NetSocketState *s = opaque;
3566 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3569 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3570 int is_connected)
3572 NetSocketState *s;
3573 s = qemu_mallocz(sizeof(NetSocketState));
3574 if (!s)
3575 return NULL;
3576 s->fd = fd;
3577 s->vc = qemu_new_vlan_client(vlan,
3578 net_socket_receive, NULL, s);
3579 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3580 "socket: fd=%d", fd);
3581 if (is_connected) {
3582 net_socket_connect(s);
3583 } else {
3584 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3586 return s;
3589 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3590 int is_connected)
3592 int so_type=-1, optlen=sizeof(so_type);
3594 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3595 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3596 return NULL;
3598 switch(so_type) {
3599 case SOCK_DGRAM:
3600 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3601 case SOCK_STREAM:
3602 return net_socket_fd_init_stream(vlan, fd, is_connected);
3603 default:
3604 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3605 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3606 return net_socket_fd_init_stream(vlan, fd, is_connected);
3608 return NULL;
3611 static void net_socket_accept(void *opaque)
3613 NetSocketListenState *s = opaque;
3614 NetSocketState *s1;
3615 struct sockaddr_in saddr;
3616 socklen_t len;
3617 int fd;
3619 for(;;) {
3620 len = sizeof(saddr);
3621 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3622 if (fd < 0 && errno != EINTR) {
3623 return;
3624 } else if (fd >= 0) {
3625 break;
3628 s1 = net_socket_fd_init(s->vlan, fd, 1);
3629 if (!s1) {
3630 closesocket(fd);
3631 } else {
3632 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3633 "socket: connection from %s:%d",
3634 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3638 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3640 NetSocketListenState *s;
3641 int fd, val, ret;
3642 struct sockaddr_in saddr;
3644 if (parse_host_port(&saddr, host_str) < 0)
3645 return -1;
3647 s = qemu_mallocz(sizeof(NetSocketListenState));
3648 if (!s)
3649 return -1;
3651 fd = socket(PF_INET, SOCK_STREAM, 0);
3652 if (fd < 0) {
3653 perror("socket");
3654 return -1;
3656 socket_set_nonblock(fd);
3658 /* allow fast reuse */
3659 val = 1;
3660 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3662 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3663 if (ret < 0) {
3664 perror("bind");
3665 return -1;
3667 ret = listen(fd, 0);
3668 if (ret < 0) {
3669 perror("listen");
3670 return -1;
3672 s->vlan = vlan;
3673 s->fd = fd;
3674 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3675 return 0;
3678 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3680 NetSocketState *s;
3681 int fd, connected, ret, err;
3682 struct sockaddr_in saddr;
3684 if (parse_host_port(&saddr, host_str) < 0)
3685 return -1;
3687 fd = socket(PF_INET, SOCK_STREAM, 0);
3688 if (fd < 0) {
3689 perror("socket");
3690 return -1;
3692 socket_set_nonblock(fd);
3694 connected = 0;
3695 for(;;) {
3696 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3697 if (ret < 0) {
3698 err = socket_error();
3699 if (err == EINTR || err == EWOULDBLOCK) {
3700 } else if (err == EINPROGRESS) {
3701 break;
3702 } else {
3703 perror("connect");
3704 closesocket(fd);
3705 return -1;
3707 } else {
3708 connected = 1;
3709 break;
3712 s = net_socket_fd_init(vlan, fd, connected);
3713 if (!s)
3714 return -1;
3715 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3716 "socket: connect to %s:%d",
3717 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3718 return 0;
3721 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3723 NetSocketState *s;
3724 int fd;
3725 struct sockaddr_in saddr;
3727 if (parse_host_port(&saddr, host_str) < 0)
3728 return -1;
3731 fd = net_socket_mcast_create(&saddr);
3732 if (fd < 0)
3733 return -1;
3735 s = net_socket_fd_init(vlan, fd, 0);
3736 if (!s)
3737 return -1;
3739 s->dgram_dst = saddr;
3741 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3742 "socket: mcast=%s:%d",
3743 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3744 return 0;
3748 static int get_param_value(char *buf, int buf_size,
3749 const char *tag, const char *str)
3751 const char *p;
3752 char *q;
3753 char option[128];
3755 p = str;
3756 for(;;) {
3757 q = option;
3758 while (*p != '\0' && *p != '=') {
3759 if ((q - option) < sizeof(option) - 1)
3760 *q++ = *p;
3761 p++;
3763 *q = '\0';
3764 if (*p != '=')
3765 break;
3766 p++;
3767 if (!strcmp(tag, option)) {
3768 q = buf;
3769 while (*p != '\0' && *p != ',') {
3770 if ((q - buf) < buf_size - 1)
3771 *q++ = *p;
3772 p++;
3774 *q = '\0';
3775 return q - buf;
3776 } else {
3777 while (*p != '\0' && *p != ',') {
3778 p++;
3781 if (*p != ',')
3782 break;
3783 p++;
3785 return 0;
3788 static int net_client_init(const char *str)
3790 const char *p;
3791 char *q;
3792 char device[64];
3793 char buf[1024];
3794 int vlan_id, ret;
3795 VLANState *vlan;
3797 p = str;
3798 q = device;
3799 while (*p != '\0' && *p != ',') {
3800 if ((q - device) < sizeof(device) - 1)
3801 *q++ = *p;
3802 p++;
3804 *q = '\0';
3805 if (*p == ',')
3806 p++;
3807 vlan_id = 0;
3808 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3809 vlan_id = strtol(buf, NULL, 0);
3811 vlan = qemu_find_vlan(vlan_id);
3812 if (!vlan) {
3813 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3814 return -1;
3816 if (!strcmp(device, "nic")) {
3817 NICInfo *nd;
3818 uint8_t *macaddr;
3820 if (nb_nics >= MAX_NICS) {
3821 fprintf(stderr, "Too Many NICs\n");
3822 return -1;
3824 nd = &nd_table[nb_nics];
3825 macaddr = nd->macaddr;
3826 macaddr[0] = 0x52;
3827 macaddr[1] = 0x54;
3828 macaddr[2] = 0x00;
3829 macaddr[3] = 0x12;
3830 macaddr[4] = 0x34;
3831 macaddr[5] = 0x56 + nb_nics;
3833 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3834 if (parse_macaddr(macaddr, buf) < 0) {
3835 fprintf(stderr, "invalid syntax for ethernet address\n");
3836 return -1;
3839 if (get_param_value(buf, sizeof(buf), "model", p)) {
3840 nd->model = strdup(buf);
3842 nd->vlan = vlan;
3843 nb_nics++;
3844 ret = 0;
3845 } else
3846 if (!strcmp(device, "none")) {
3847 /* does nothing. It is needed to signal that no network cards
3848 are wanted */
3849 ret = 0;
3850 } else
3851 #ifdef CONFIG_SLIRP
3852 if (!strcmp(device, "user")) {
3853 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3854 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3856 ret = net_slirp_init(vlan);
3857 } else
3858 #endif
3859 #ifdef _WIN32
3860 if (!strcmp(device, "tap")) {
3861 char ifname[64];
3862 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3863 fprintf(stderr, "tap: no interface name\n");
3864 return -1;
3866 ret = tap_win32_init(vlan, ifname);
3867 } else
3868 #else
3869 if (!strcmp(device, "tap")) {
3870 char ifname[64];
3871 char setup_script[1024];
3872 int fd;
3873 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3874 fd = strtol(buf, NULL, 0);
3875 ret = -1;
3876 if (net_tap_fd_init(vlan, fd))
3877 ret = 0;
3878 } else {
3879 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3880 ifname[0] = '\0';
3882 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3883 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3885 ret = net_tap_init(vlan, ifname, setup_script);
3887 } else
3888 #endif
3889 if (!strcmp(device, "socket")) {
3890 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3891 int fd;
3892 fd = strtol(buf, NULL, 0);
3893 ret = -1;
3894 if (net_socket_fd_init(vlan, fd, 1))
3895 ret = 0;
3896 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3897 ret = net_socket_listen_init(vlan, buf);
3898 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3899 ret = net_socket_connect_init(vlan, buf);
3900 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3901 ret = net_socket_mcast_init(vlan, buf);
3902 } else {
3903 fprintf(stderr, "Unknown socket options: %s\n", p);
3904 return -1;
3906 } else
3908 fprintf(stderr, "Unknown network device: %s\n", device);
3909 return -1;
3911 if (ret < 0) {
3912 fprintf(stderr, "Could not initialize device '%s'\n", device);
3915 return ret;
3918 void do_info_network(void)
3920 VLANState *vlan;
3921 VLANClientState *vc;
3923 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3924 term_printf("VLAN %d devices:\n", vlan->id);
3925 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3926 term_printf(" %s\n", vc->info_str);
3930 /***********************************************************/
3931 /* USB devices */
3933 static USBPort *used_usb_ports;
3934 static USBPort *free_usb_ports;
3936 /* ??? Maybe change this to register a hub to keep track of the topology. */
3937 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3938 usb_attachfn attach)
3940 port->opaque = opaque;
3941 port->index = index;
3942 port->attach = attach;
3943 port->next = free_usb_ports;
3944 free_usb_ports = port;
3947 static int usb_device_add(const char *devname)
3949 const char *p;
3950 USBDevice *dev;
3951 USBPort *port;
3953 if (!free_usb_ports)
3954 return -1;
3956 if (strstart(devname, "host:", &p)) {
3957 dev = usb_host_device_open(p);
3958 } else if (!strcmp(devname, "mouse")) {
3959 dev = usb_mouse_init();
3960 } else if (!strcmp(devname, "tablet")) {
3961 dev = usb_tablet_init();
3962 } else if (strstart(devname, "disk:", &p)) {
3963 dev = usb_msd_init(p);
3964 } else {
3965 return -1;
3967 if (!dev)
3968 return -1;
3970 /* Find a USB port to add the device to. */
3971 port = free_usb_ports;
3972 if (!port->next) {
3973 USBDevice *hub;
3975 /* Create a new hub and chain it on. */
3976 free_usb_ports = NULL;
3977 port->next = used_usb_ports;
3978 used_usb_ports = port;
3980 hub = usb_hub_init(VM_USB_HUB_SIZE);
3981 usb_attach(port, hub);
3982 port = free_usb_ports;
3985 free_usb_ports = port->next;
3986 port->next = used_usb_ports;
3987 used_usb_ports = port;
3988 usb_attach(port, dev);
3989 return 0;
3992 static int usb_device_del(const char *devname)
3994 USBPort *port;
3995 USBPort **lastp;
3996 USBDevice *dev;
3997 int bus_num, addr;
3998 const char *p;
4000 if (!used_usb_ports)
4001 return -1;
4003 p = strchr(devname, '.');
4004 if (!p)
4005 return -1;
4006 bus_num = strtoul(devname, NULL, 0);
4007 addr = strtoul(p + 1, NULL, 0);
4008 if (bus_num != 0)
4009 return -1;
4011 lastp = &used_usb_ports;
4012 port = used_usb_ports;
4013 while (port && port->dev->addr != addr) {
4014 lastp = &port->next;
4015 port = port->next;
4018 if (!port)
4019 return -1;
4021 dev = port->dev;
4022 *lastp = port->next;
4023 usb_attach(port, NULL);
4024 dev->handle_destroy(dev);
4025 port->next = free_usb_ports;
4026 free_usb_ports = port;
4027 return 0;
4030 void do_usb_add(const char *devname)
4032 int ret;
4033 ret = usb_device_add(devname);
4034 if (ret < 0)
4035 term_printf("Could not add USB device '%s'\n", devname);
4038 void do_usb_del(const char *devname)
4040 int ret;
4041 ret = usb_device_del(devname);
4042 if (ret < 0)
4043 term_printf("Could not remove USB device '%s'\n", devname);
4046 void usb_info(void)
4048 USBDevice *dev;
4049 USBPort *port;
4050 const char *speed_str;
4052 if (!usb_enabled) {
4053 term_printf("USB support not enabled\n");
4054 return;
4057 for (port = used_usb_ports; port; port = port->next) {
4058 dev = port->dev;
4059 if (!dev)
4060 continue;
4061 switch(dev->speed) {
4062 case USB_SPEED_LOW:
4063 speed_str = "1.5";
4064 break;
4065 case USB_SPEED_FULL:
4066 speed_str = "12";
4067 break;
4068 case USB_SPEED_HIGH:
4069 speed_str = "480";
4070 break;
4071 default:
4072 speed_str = "?";
4073 break;
4075 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4076 0, dev->addr, speed_str, dev->devname);
4080 /***********************************************************/
4081 /* pid file */
4083 static char *pid_filename;
4085 /* Remove PID file. Called on normal exit */
4087 static void remove_pidfile(void)
4089 unlink (pid_filename);
4092 static void create_pidfile(const char *filename)
4094 struct stat pidstat;
4095 FILE *f;
4097 /* Try to write our PID to the named file */
4098 if (stat(filename, &pidstat) < 0) {
4099 if (errno == ENOENT) {
4100 if ((f = fopen (filename, "w")) == NULL) {
4101 perror("Opening pidfile");
4102 exit(1);
4104 fprintf(f, "%d\n", getpid());
4105 fclose(f);
4106 pid_filename = qemu_strdup(filename);
4107 if (!pid_filename) {
4108 fprintf(stderr, "Could not save PID filename");
4109 exit(1);
4111 atexit(remove_pidfile);
4113 } else {
4114 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4115 filename);
4116 exit(1);
4120 /***********************************************************/
4121 /* dumb display */
4123 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4127 static void dumb_resize(DisplayState *ds, int w, int h)
4131 static void dumb_refresh(DisplayState *ds)
4133 vga_hw_update();
4136 void dumb_display_init(DisplayState *ds)
4138 ds->data = NULL;
4139 ds->linesize = 0;
4140 ds->depth = 0;
4141 ds->dpy_update = dumb_update;
4142 ds->dpy_resize = dumb_resize;
4143 ds->dpy_refresh = dumb_refresh;
4146 /***********************************************************/
4147 /* I/O handling */
4149 #define MAX_IO_HANDLERS 64
4151 typedef struct IOHandlerRecord {
4152 int fd;
4153 IOCanRWHandler *fd_read_poll;
4154 IOHandler *fd_read;
4155 IOHandler *fd_write;
4156 int deleted;
4157 void *opaque;
4158 /* temporary data */
4159 struct pollfd *ufd;
4160 struct IOHandlerRecord *next;
4161 } IOHandlerRecord;
4163 static IOHandlerRecord *first_io_handler;
4165 /* XXX: fd_read_poll should be suppressed, but an API change is
4166 necessary in the character devices to suppress fd_can_read(). */
4167 int qemu_set_fd_handler2(int fd,
4168 IOCanRWHandler *fd_read_poll,
4169 IOHandler *fd_read,
4170 IOHandler *fd_write,
4171 void *opaque)
4173 IOHandlerRecord **pioh, *ioh;
4175 if (!fd_read && !fd_write) {
4176 pioh = &first_io_handler;
4177 for(;;) {
4178 ioh = *pioh;
4179 if (ioh == NULL)
4180 break;
4181 if (ioh->fd == fd) {
4182 ioh->deleted = 1;
4183 break;
4185 pioh = &ioh->next;
4187 } else {
4188 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4189 if (ioh->fd == fd)
4190 goto found;
4192 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4193 if (!ioh)
4194 return -1;
4195 ioh->next = first_io_handler;
4196 first_io_handler = ioh;
4197 found:
4198 ioh->fd = fd;
4199 ioh->fd_read_poll = fd_read_poll;
4200 ioh->fd_read = fd_read;
4201 ioh->fd_write = fd_write;
4202 ioh->opaque = opaque;
4203 ioh->deleted = 0;
4205 return 0;
4208 int qemu_set_fd_handler(int fd,
4209 IOHandler *fd_read,
4210 IOHandler *fd_write,
4211 void *opaque)
4213 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4216 /***********************************************************/
4217 /* Polling handling */
4219 typedef struct PollingEntry {
4220 PollingFunc *func;
4221 void *opaque;
4222 struct PollingEntry *next;
4223 } PollingEntry;
4225 static PollingEntry *first_polling_entry;
4227 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4229 PollingEntry **ppe, *pe;
4230 pe = qemu_mallocz(sizeof(PollingEntry));
4231 if (!pe)
4232 return -1;
4233 pe->func = func;
4234 pe->opaque = opaque;
4235 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4236 *ppe = pe;
4237 return 0;
4240 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4242 PollingEntry **ppe, *pe;
4243 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4244 pe = *ppe;
4245 if (pe->func == func && pe->opaque == opaque) {
4246 *ppe = pe->next;
4247 qemu_free(pe);
4248 break;
4253 #ifdef _WIN32
4254 /***********************************************************/
4255 /* Wait objects support */
4256 typedef struct WaitObjects {
4257 int num;
4258 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4259 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4260 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4261 } WaitObjects;
4263 static WaitObjects wait_objects = {0};
4265 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4267 WaitObjects *w = &wait_objects;
4269 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4270 return -1;
4271 w->events[w->num] = handle;
4272 w->func[w->num] = func;
4273 w->opaque[w->num] = opaque;
4274 w->num++;
4275 return 0;
4278 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4280 int i, found;
4281 WaitObjects *w = &wait_objects;
4283 found = 0;
4284 for (i = 0; i < w->num; i++) {
4285 if (w->events[i] == handle)
4286 found = 1;
4287 if (found) {
4288 w->events[i] = w->events[i + 1];
4289 w->func[i] = w->func[i + 1];
4290 w->opaque[i] = w->opaque[i + 1];
4293 if (found)
4294 w->num--;
4296 #endif
4298 #define SELF_ANNOUNCE_ROUNDS 5
4299 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4300 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4301 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4303 static int announce_self_create(uint8_t *buf,
4304 uint8_t *mac_addr)
4306 uint32_t magic = EXPERIMENTAL_MAGIC;
4307 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
4309 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4311 memset(buf, 0xff, 6); /* h_dst */
4312 memcpy(buf + 6, mac_addr, 6); /* h_src */
4313 memcpy(buf + 12, &proto, 2); /* h_proto */
4314 memcpy(buf + 14, &magic, 4); /* magic */
4316 return 18; /* len */
4319 static void qemu_announce_self(void)
4321 int i, j, len;
4322 VLANState *vlan;
4323 VLANClientState *vc;
4324 uint8_t buf[256];
4326 for (i = 0; i < nb_nics; i++) {
4327 len = announce_self_create(buf, nd_table[i].macaddr);
4328 vlan = nd_table[i].vlan;
4329 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4330 if (vc->fd_read == tap_receive) /* send only if tap */
4331 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
4332 vc->fd_read(vc->opaque, buf, len);
4337 /***********************************************************/
4338 /* savevm/loadvm support */
4340 #define IO_BUF_SIZE 32768
4342 struct QEMUFile {
4343 QEMUFilePutBufferFunc *put_buffer;
4344 QEMUFileGetBufferFunc *get_buffer;
4345 QEMUFileCloseFunc *close;
4346 void *opaque;
4348 int64_t buf_offset; /* start of buffer when writing, end of buffer
4349 when reading */
4350 int buf_index;
4351 int buf_size; /* 0 when writing */
4352 uint8_t buf[IO_BUF_SIZE];
4355 typedef struct QEMUFileFD
4357 int fd;
4358 } QEMUFileFD;
4360 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4362 QEMUFileFD *s = opaque;
4363 int offset = 0;
4364 ssize_t len;
4366 again:
4367 len = read(s->fd, buf + offset, size - offset);
4368 if (len == -1) {
4369 if (errno == EINTR || errno == EAGAIN)
4370 goto again;
4373 return len;
4376 QEMUFile *qemu_fopen_fd(int fd)
4378 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
4379 s->fd = fd;
4380 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
4383 typedef struct QEMUFileUnix
4385 FILE *outfile;
4386 } QEMUFileUnix;
4388 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4390 QEMUFileUnix *s = opaque;
4391 fseek(s->outfile, pos, SEEK_SET);
4392 fwrite(buf, 1, size, s->outfile);
4395 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4397 QEMUFileUnix *s = opaque;
4398 fseek(s->outfile, pos, SEEK_SET);
4399 return fread(buf, 1, size, s->outfile);
4402 static void file_close(void *opaque)
4404 QEMUFileUnix *s = opaque;
4405 fclose(s->outfile);
4406 qemu_free(s);
4409 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
4411 QEMUFileUnix *s;
4413 s = qemu_mallocz(sizeof(QEMUFileUnix));
4414 if (!s)
4415 return NULL;
4417 s->outfile = fopen(filename, mode);
4418 if (!s->outfile)
4419 goto fail;
4421 if (!strcmp(mode, "wb"))
4422 return qemu_fopen(s, file_put_buffer, NULL, file_close);
4423 else if (!strcmp(mode, "rb"))
4424 return qemu_fopen(s, NULL, file_get_buffer, file_close);
4426 fail:
4427 if (s->outfile)
4428 fclose(s->outfile);
4429 qemu_free(s);
4430 return NULL;
4433 typedef struct QEMUFileBdrv
4435 BlockDriverState *bs;
4436 int64_t base_offset;
4437 } QEMUFileBdrv;
4439 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4441 QEMUFileBdrv *s = opaque;
4442 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
4445 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4447 QEMUFileBdrv *s = opaque;
4448 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
4451 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4453 QEMUFileBdrv *s;
4455 s = qemu_mallocz(sizeof(QEMUFileBdrv));
4456 if (!s)
4457 return NULL;
4459 s->bs = bs;
4460 s->base_offset = offset;
4462 if (is_writable)
4463 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
4465 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
4468 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
4469 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
4471 QEMUFile *f;
4473 f = qemu_mallocz(sizeof(QEMUFile));
4474 if (!f)
4475 return NULL;
4477 f->opaque = opaque;
4478 f->put_buffer = put_buffer;
4479 f->get_buffer = get_buffer;
4480 f->close = close;
4482 return f;
4485 void qemu_fflush(QEMUFile *f)
4487 if (!f->put_buffer)
4488 return;
4490 if (f->buf_index > 0) {
4491 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
4492 f->buf_offset += f->buf_index;
4493 f->buf_index = 0;
4497 static void qemu_fill_buffer(QEMUFile *f)
4499 int len;
4501 if (!f->get_buffer)
4502 return;
4504 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
4505 if (len < 0)
4506 len = 0;
4508 f->buf_index = 0;
4509 f->buf_size = len;
4510 f->buf_offset += len;
4513 void qemu_fclose(QEMUFile *f)
4515 qemu_fflush(f);
4516 if (f->close)
4517 f->close(f->opaque);
4518 qemu_free(f);
4521 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4523 int l;
4524 while (size > 0) {
4525 l = IO_BUF_SIZE - f->buf_index;
4526 if (l > size)
4527 l = size;
4528 memcpy(f->buf + f->buf_index, buf, l);
4529 f->buf_index += l;
4530 buf += l;
4531 size -= l;
4532 if (f->buf_index >= IO_BUF_SIZE)
4533 qemu_fflush(f);
4537 void qemu_put_byte(QEMUFile *f, int v)
4539 f->buf[f->buf_index++] = v;
4540 if (f->buf_index >= IO_BUF_SIZE)
4541 qemu_fflush(f);
4544 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4546 int size, l;
4548 size = size1;
4549 while (size > 0) {
4550 l = f->buf_size - f->buf_index;
4551 if (l == 0) {
4552 qemu_fill_buffer(f);
4553 l = f->buf_size - f->buf_index;
4554 if (l == 0)
4555 break;
4557 if (l > size)
4558 l = size;
4559 memcpy(buf, f->buf + f->buf_index, l);
4560 f->buf_index += l;
4561 buf += l;
4562 size -= l;
4564 return size1 - size;
4567 int qemu_get_byte(QEMUFile *f)
4569 if (f->buf_index >= f->buf_size) {
4570 qemu_fill_buffer(f);
4571 if (f->buf_index >= f->buf_size)
4572 return 0;
4574 return f->buf[f->buf_index++];
4577 int64_t qemu_ftell(QEMUFile *f)
4579 return f->buf_offset - f->buf_size + f->buf_index;
4582 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4584 if (whence == SEEK_SET) {
4585 /* nothing to do */
4586 } else if (whence == SEEK_CUR) {
4587 pos += qemu_ftell(f);
4588 } else {
4589 /* SEEK_END not supported */
4590 return -1;
4592 if (f->put_buffer) {
4593 qemu_fflush(f);
4594 f->buf_offset = pos;
4595 } else {
4596 f->buf_offset = pos;
4597 f->buf_index = 0;
4598 f->buf_size = 0;
4600 return pos;
4603 void qemu_put_be16(QEMUFile *f, unsigned int v)
4605 qemu_put_byte(f, v >> 8);
4606 qemu_put_byte(f, v);
4609 void qemu_put_be32(QEMUFile *f, unsigned int v)
4611 qemu_put_byte(f, v >> 24);
4612 qemu_put_byte(f, v >> 16);
4613 qemu_put_byte(f, v >> 8);
4614 qemu_put_byte(f, v);
4617 void qemu_put_be64(QEMUFile *f, uint64_t v)
4619 qemu_put_be32(f, v >> 32);
4620 qemu_put_be32(f, v);
4623 unsigned int qemu_get_be16(QEMUFile *f)
4625 unsigned int v;
4626 v = qemu_get_byte(f) << 8;
4627 v |= qemu_get_byte(f);
4628 return v;
4631 unsigned int qemu_get_be32(QEMUFile *f)
4633 unsigned int v;
4634 v = qemu_get_byte(f) << 24;
4635 v |= qemu_get_byte(f) << 16;
4636 v |= qemu_get_byte(f) << 8;
4637 v |= qemu_get_byte(f);
4638 return v;
4641 uint64_t qemu_get_be64(QEMUFile *f)
4643 uint64_t v;
4644 v = (uint64_t)qemu_get_be32(f) << 32;
4645 v |= qemu_get_be32(f);
4646 return v;
4649 typedef struct SaveStateEntry {
4650 char idstr[256];
4651 int instance_id;
4652 int version_id;
4653 SaveStateHandler *save_state;
4654 LoadStateHandler *load_state;
4655 void *opaque;
4656 struct SaveStateEntry *next;
4657 } SaveStateEntry;
4659 static SaveStateEntry *first_se;
4661 int register_savevm(const char *idstr,
4662 int instance_id,
4663 int version_id,
4664 SaveStateHandler *save_state,
4665 LoadStateHandler *load_state,
4666 void *opaque)
4668 SaveStateEntry *se, **pse;
4670 se = qemu_malloc(sizeof(SaveStateEntry));
4671 if (!se)
4672 return -1;
4673 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4674 se->instance_id = instance_id;
4675 se->version_id = version_id;
4676 se->save_state = save_state;
4677 se->load_state = load_state;
4678 se->opaque = opaque;
4679 se->next = NULL;
4681 /* add at the end of list */
4682 pse = &first_se;
4683 while (*pse != NULL)
4684 pse = &(*pse)->next;
4685 *pse = se;
4686 return 0;
4689 #define QEMU_VM_FILE_MAGIC 0x5145564d
4690 #define QEMU_VM_FILE_VERSION 0x00000002
4692 int qemu_savevm_state(QEMUFile *f)
4694 SaveStateEntry *se;
4695 int len, ret;
4696 int64_t cur_pos, len_pos, total_len_pos;
4698 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4699 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4700 total_len_pos = qemu_ftell(f);
4701 qemu_put_be64(f, 0); /* total size */
4703 for(se = first_se; se != NULL; se = se->next) {
4704 /* ID string */
4705 len = strlen(se->idstr);
4706 qemu_put_byte(f, len);
4707 qemu_put_buffer(f, se->idstr, len);
4709 qemu_put_be32(f, se->instance_id);
4710 qemu_put_be32(f, se->version_id);
4712 /* record size: filled later */
4713 len_pos = qemu_ftell(f);
4714 qemu_put_be32(f, 0);
4716 se->save_state(f, se->opaque);
4718 /* fill record size */
4719 cur_pos = qemu_ftell(f);
4720 len = cur_pos - len_pos - 4;
4721 qemu_fseek(f, len_pos, SEEK_SET);
4722 qemu_put_be32(f, len);
4723 qemu_fseek(f, cur_pos, SEEK_SET);
4725 cur_pos = qemu_ftell(f);
4726 qemu_fseek(f, total_len_pos, SEEK_SET);
4727 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4728 qemu_fseek(f, cur_pos, SEEK_SET);
4730 ret = 0;
4731 return ret;
4734 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4736 SaveStateEntry *se;
4738 for(se = first_se; se != NULL; se = se->next) {
4739 if (!strcmp(se->idstr, idstr) &&
4740 instance_id == se->instance_id)
4741 return se;
4743 return NULL;
4746 int qemu_loadvm_state(QEMUFile *f)
4748 SaveStateEntry *se;
4749 int len, ret, instance_id, record_len, version_id;
4750 int64_t total_len, end_pos, cur_pos;
4751 unsigned int v;
4752 char idstr[256];
4754 v = qemu_get_be32(f);
4755 if (v != QEMU_VM_FILE_MAGIC)
4756 goto fail;
4757 v = qemu_get_be32(f);
4758 if (v != QEMU_VM_FILE_VERSION) {
4759 fail:
4760 ret = -1;
4761 goto the_end;
4763 total_len = qemu_get_be64(f);
4764 end_pos = total_len + qemu_ftell(f);
4765 for(;;) {
4766 if (qemu_ftell(f) >= end_pos)
4767 break;
4768 len = qemu_get_byte(f);
4769 qemu_get_buffer(f, idstr, len);
4770 idstr[len] = '\0';
4771 instance_id = qemu_get_be32(f);
4772 version_id = qemu_get_be32(f);
4773 record_len = qemu_get_be32(f);
4774 #if 0
4775 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4776 idstr, instance_id, version_id, record_len);
4777 #endif
4778 cur_pos = qemu_ftell(f);
4779 se = find_se(idstr, instance_id);
4780 if (!se) {
4781 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4782 instance_id, idstr);
4783 } else {
4784 ret = se->load_state(f, se->opaque, version_id);
4785 if (ret < 0) {
4786 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4787 instance_id, idstr);
4788 goto the_end;
4791 /* always seek to exact end of record */
4792 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4794 ret = 0;
4795 the_end:
4796 return ret;
4799 int qemu_live_savevm_state(QEMUFile *f)
4801 SaveStateEntry *se;
4802 int len, ret;
4804 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4805 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4807 for(se = first_se; se != NULL; se = se->next) {
4808 len = strlen(se->idstr);
4810 qemu_put_byte(f, len);
4811 qemu_put_buffer(f, se->idstr, len);
4812 qemu_put_be32(f, se->instance_id);
4813 qemu_put_be32(f, se->version_id);
4815 se->save_state(f, se->opaque);
4818 qemu_put_byte(f, 0);
4820 ret = 0;
4821 return ret;
4824 int qemu_live_loadvm_state(QEMUFile *f)
4826 SaveStateEntry *se;
4827 int len, ret, instance_id, version_id;
4828 unsigned int v;
4829 char idstr[256];
4831 v = qemu_get_be32(f);
4832 if (v != QEMU_VM_FILE_MAGIC)
4833 goto fail;
4834 v = qemu_get_be32(f);
4835 if (v != QEMU_VM_FILE_VERSION) {
4836 fail:
4837 ret = -1;
4838 goto the_end;
4841 for(;;) {
4842 len = qemu_get_byte(f);
4843 if (len == 0)
4844 break;
4845 qemu_get_buffer(f, idstr, len);
4846 idstr[len] = '\0';
4847 instance_id = qemu_get_be32(f);
4848 version_id = qemu_get_be32(f);
4849 se = find_se(idstr, instance_id);
4850 if (!se) {
4851 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4852 instance_id, idstr);
4853 } else {
4854 if (version_id > se->version_id) { /* src version > dst version */
4855 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
4856 idstr, version_id, se->version_id);
4857 ret = -1;
4858 goto the_end;
4860 ret = se->load_state(f, se->opaque, version_id);
4861 if (ret < 0) {
4862 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4863 instance_id, idstr);
4864 goto the_end;
4868 ret = 0;
4870 qemu_announce_self();
4872 the_end:
4873 return ret;
4876 /* device can contain snapshots */
4877 static int bdrv_can_snapshot(BlockDriverState *bs)
4879 return (bs &&
4880 !bdrv_is_removable(bs) &&
4881 !bdrv_is_read_only(bs));
4884 /* device must be snapshots in order to have a reliable snapshot */
4885 static int bdrv_has_snapshot(BlockDriverState *bs)
4887 return (bs &&
4888 !bdrv_is_removable(bs) &&
4889 !bdrv_is_read_only(bs));
4892 static BlockDriverState *get_bs_snapshots(void)
4894 BlockDriverState *bs;
4895 int i;
4897 if (bs_snapshots)
4898 return bs_snapshots;
4899 for(i = 0; i <= MAX_DISKS; i++) {
4900 bs = bs_table[i];
4901 if (bdrv_can_snapshot(bs))
4902 goto ok;
4904 return NULL;
4906 bs_snapshots = bs;
4907 return bs;
4910 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4911 const char *name)
4913 QEMUSnapshotInfo *sn_tab, *sn;
4914 int nb_sns, i, ret;
4916 ret = -ENOENT;
4917 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4918 if (nb_sns < 0)
4919 return ret;
4920 for(i = 0; i < nb_sns; i++) {
4921 sn = &sn_tab[i];
4922 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4923 *sn_info = *sn;
4924 ret = 0;
4925 break;
4928 qemu_free(sn_tab);
4929 return ret;
4932 void do_savevm(const char *name)
4934 BlockDriverState *bs, *bs1;
4935 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4936 int must_delete, ret, i;
4937 BlockDriverInfo bdi1, *bdi = &bdi1;
4938 QEMUFile *f;
4939 int saved_vm_running;
4940 #ifdef _WIN32
4941 struct _timeb tb;
4942 #else
4943 struct timeval tv;
4944 #endif
4946 bs = get_bs_snapshots();
4947 if (!bs) {
4948 term_printf("No block device can accept snapshots\n");
4949 return;
4952 /* ??? Should this occur after vm_stop? */
4953 qemu_aio_flush();
4955 saved_vm_running = vm_running;
4956 vm_stop(0);
4958 must_delete = 0;
4959 if (name) {
4960 ret = bdrv_snapshot_find(bs, old_sn, name);
4961 if (ret >= 0) {
4962 must_delete = 1;
4965 memset(sn, 0, sizeof(*sn));
4966 if (must_delete) {
4967 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4968 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4969 } else {
4970 if (name)
4971 pstrcpy(sn->name, sizeof(sn->name), name);
4974 /* fill auxiliary fields */
4975 #ifdef _WIN32
4976 _ftime(&tb);
4977 sn->date_sec = tb.time;
4978 sn->date_nsec = tb.millitm * 1000000;
4979 #else
4980 gettimeofday(&tv, NULL);
4981 sn->date_sec = tv.tv_sec;
4982 sn->date_nsec = tv.tv_usec * 1000;
4983 #endif
4984 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4986 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4987 term_printf("Device %s does not support VM state snapshots\n",
4988 bdrv_get_device_name(bs));
4989 goto the_end;
4992 /* save the VM state */
4993 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4994 if (!f) {
4995 term_printf("Could not open VM state file\n");
4996 goto the_end;
4998 ret = qemu_savevm_state(f);
4999 sn->vm_state_size = qemu_ftell(f);
5000 qemu_fclose(f);
5001 if (ret < 0) {
5002 term_printf("Error %d while writing VM\n", ret);
5003 goto the_end;
5006 /* create the snapshots */
5008 for(i = 0; i < MAX_DISKS; i++) {
5009 bs1 = bs_table[i];
5010 if (bdrv_has_snapshot(bs1)) {
5011 if (must_delete) {
5012 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5013 if (ret < 0) {
5014 term_printf("Error while deleting snapshot on '%s'\n",
5015 bdrv_get_device_name(bs1));
5018 ret = bdrv_snapshot_create(bs1, sn);
5019 if (ret < 0) {
5020 term_printf("Error while creating snapshot on '%s'\n",
5021 bdrv_get_device_name(bs1));
5026 the_end:
5027 if (saved_vm_running)
5028 vm_start();
5031 void do_loadvm(const char *name)
5033 BlockDriverState *bs, *bs1;
5034 BlockDriverInfo bdi1, *bdi = &bdi1;
5035 QEMUFile *f;
5036 int i, ret;
5037 int saved_vm_running;
5039 bs = get_bs_snapshots();
5040 if (!bs) {
5041 term_printf("No block device supports snapshots\n");
5042 return;
5045 /* Flush all IO requests so they don't interfere with the new state. */
5046 qemu_aio_flush();
5048 saved_vm_running = vm_running;
5049 vm_stop(0);
5051 for(i = 0; i <= MAX_DISKS; i++) {
5052 bs1 = bs_table[i];
5053 if (bdrv_has_snapshot(bs1)) {
5054 ret = bdrv_snapshot_goto(bs1, name);
5055 if (ret < 0) {
5056 if (bs != bs1)
5057 term_printf("Warning: ");
5058 switch(ret) {
5059 case -ENOTSUP:
5060 term_printf("Snapshots not supported on device '%s'\n",
5061 bdrv_get_device_name(bs1));
5062 break;
5063 case -ENOENT:
5064 term_printf("Could not find snapshot '%s' on device '%s'\n",
5065 name, bdrv_get_device_name(bs1));
5066 break;
5067 default:
5068 term_printf("Error %d while activating snapshot on '%s'\n",
5069 ret, bdrv_get_device_name(bs1));
5070 break;
5072 /* fatal on snapshot block device */
5073 if (bs == bs1)
5074 goto the_end;
5079 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5080 term_printf("Device %s does not support VM state snapshots\n",
5081 bdrv_get_device_name(bs));
5082 return;
5085 /* restore the VM state */
5086 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5087 if (!f) {
5088 term_printf("Could not open VM state file\n");
5089 goto the_end;
5091 ret = qemu_loadvm_state(f);
5092 qemu_fclose(f);
5093 if (ret < 0) {
5094 term_printf("Error %d while loading VM state\n", ret);
5096 the_end:
5097 if (saved_vm_running)
5098 vm_start();
5101 void do_delvm(const char *name)
5103 BlockDriverState *bs, *bs1;
5104 int i, ret;
5106 bs = get_bs_snapshots();
5107 if (!bs) {
5108 term_printf("No block device supports snapshots\n");
5109 return;
5112 for(i = 0; i <= MAX_DISKS; i++) {
5113 bs1 = bs_table[i];
5114 if (bdrv_has_snapshot(bs1)) {
5115 ret = bdrv_snapshot_delete(bs1, name);
5116 if (ret < 0) {
5117 if (ret == -ENOTSUP)
5118 term_printf("Snapshots not supported on device '%s'\n",
5119 bdrv_get_device_name(bs1));
5120 else
5121 term_printf("Error %d while deleting snapshot on '%s'\n",
5122 ret, bdrv_get_device_name(bs1));
5128 void do_info_snapshots(void)
5130 BlockDriverState *bs, *bs1;
5131 QEMUSnapshotInfo *sn_tab, *sn;
5132 int nb_sns, i;
5133 char buf[256];
5135 bs = get_bs_snapshots();
5136 if (!bs) {
5137 term_printf("No available block device supports snapshots\n");
5138 return;
5140 term_printf("Snapshot devices:");
5141 for(i = 0; i <= MAX_DISKS; i++) {
5142 bs1 = bs_table[i];
5143 if (bdrv_has_snapshot(bs1)) {
5144 if (bs == bs1)
5145 term_printf(" %s", bdrv_get_device_name(bs1));
5148 term_printf("\n");
5150 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5151 if (nb_sns < 0) {
5152 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5153 return;
5155 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5156 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5157 for(i = 0; i < nb_sns; i++) {
5158 sn = &sn_tab[i];
5159 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5161 qemu_free(sn_tab);
5164 /***********************************************************/
5165 /* cpu save/restore */
5167 #if defined(TARGET_I386)
5169 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5171 qemu_put_be32(f, dt->selector);
5172 qemu_put_betl(f, dt->base);
5173 qemu_put_be32(f, dt->limit);
5174 qemu_put_be32(f, dt->flags);
5177 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5179 dt->selector = qemu_get_be32(f);
5180 dt->base = qemu_get_betl(f);
5181 dt->limit = qemu_get_be32(f);
5182 dt->flags = qemu_get_be32(f);
5185 void cpu_save(QEMUFile *f, void *opaque)
5187 CPUState *env = opaque;
5188 uint16_t fptag, fpus, fpuc, fpregs_format;
5189 uint32_t hflags;
5190 int i;
5192 #ifdef USE_KVM
5193 if (kvm_allowed)
5194 kvm_save_registers(env);
5195 #endif
5197 for(i = 0; i < CPU_NB_REGS; i++)
5198 qemu_put_betls(f, &env->regs[i]);
5199 qemu_put_betls(f, &env->eip);
5200 qemu_put_betls(f, &env->eflags);
5201 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5202 qemu_put_be32s(f, &hflags);
5204 /* FPU */
5205 fpuc = env->fpuc;
5206 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5207 fptag = 0;
5208 for(i = 0; i < 8; i++) {
5209 fptag |= ((!env->fptags[i]) << i);
5212 qemu_put_be16s(f, &fpuc);
5213 qemu_put_be16s(f, &fpus);
5214 qemu_put_be16s(f, &fptag);
5216 #ifdef USE_X86LDOUBLE
5217 fpregs_format = 0;
5218 #else
5219 fpregs_format = 1;
5220 #endif
5221 qemu_put_be16s(f, &fpregs_format);
5223 for(i = 0; i < 8; i++) {
5224 #ifdef USE_X86LDOUBLE
5226 uint64_t mant;
5227 uint16_t exp;
5228 /* we save the real CPU data (in case of MMX usage only 'mant'
5229 contains the MMX register */
5230 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5231 qemu_put_be64(f, mant);
5232 qemu_put_be16(f, exp);
5234 #else
5235 /* if we use doubles for float emulation, we save the doubles to
5236 avoid losing information in case of MMX usage. It can give
5237 problems if the image is restored on a CPU where long
5238 doubles are used instead. */
5239 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5240 #endif
5243 for(i = 0; i < 6; i++)
5244 cpu_put_seg(f, &env->segs[i]);
5245 cpu_put_seg(f, &env->ldt);
5246 cpu_put_seg(f, &env->tr);
5247 cpu_put_seg(f, &env->gdt);
5248 cpu_put_seg(f, &env->idt);
5250 qemu_put_be32s(f, &env->sysenter_cs);
5251 qemu_put_be32s(f, &env->sysenter_esp);
5252 qemu_put_be32s(f, &env->sysenter_eip);
5254 qemu_put_betls(f, &env->cr[0]);
5255 qemu_put_betls(f, &env->cr[2]);
5256 qemu_put_betls(f, &env->cr[3]);
5257 qemu_put_betls(f, &env->cr[4]);
5259 for(i = 0; i < 8; i++)
5260 qemu_put_betls(f, &env->dr[i]);
5262 /* MMU */
5263 qemu_put_be32s(f, &env->a20_mask);
5265 /* XMM */
5266 qemu_put_be32s(f, &env->mxcsr);
5267 for(i = 0; i < CPU_NB_REGS; i++) {
5268 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5269 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5272 #ifdef TARGET_X86_64
5273 qemu_put_be64s(f, &env->efer);
5274 qemu_put_be64s(f, &env->star);
5275 qemu_put_be64s(f, &env->lstar);
5276 qemu_put_be64s(f, &env->cstar);
5277 qemu_put_be64s(f, &env->fmask);
5278 qemu_put_be64s(f, &env->kernelgsbase);
5279 #endif
5280 qemu_put_be32s(f, &env->smbase);
5282 #ifdef USE_KVM
5283 if (kvm_allowed) {
5284 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5285 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
5287 qemu_put_be64s(f, &env->tsc);
5289 #endif
5293 #ifdef USE_X86LDOUBLE
5294 /* XXX: add that in a FPU generic layer */
5295 union x86_longdouble {
5296 uint64_t mant;
5297 uint16_t exp;
5300 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5301 #define EXPBIAS1 1023
5302 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5303 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5305 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5307 int e;
5308 /* mantissa */
5309 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5310 /* exponent + sign */
5311 e = EXPD1(temp) - EXPBIAS1 + 16383;
5312 e |= SIGND1(temp) >> 16;
5313 p->exp = e;
5315 #endif
5317 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5319 CPUState *env = opaque;
5320 int i, guess_mmx;
5321 uint32_t hflags;
5322 uint16_t fpus, fpuc, fptag, fpregs_format;
5324 if (version_id != 3 && version_id != 4)
5325 return -EINVAL;
5326 for(i = 0; i < CPU_NB_REGS; i++)
5327 qemu_get_betls(f, &env->regs[i]);
5328 qemu_get_betls(f, &env->eip);
5329 qemu_get_betls(f, &env->eflags);
5330 qemu_get_be32s(f, &hflags);
5332 qemu_get_be16s(f, &fpuc);
5333 qemu_get_be16s(f, &fpus);
5334 qemu_get_be16s(f, &fptag);
5335 qemu_get_be16s(f, &fpregs_format);
5337 /* NOTE: we cannot always restore the FPU state if the image come
5338 from a host with a different 'USE_X86LDOUBLE' define. We guess
5339 if we are in an MMX state to restore correctly in that case. */
5340 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5341 for(i = 0; i < 8; i++) {
5342 uint64_t mant;
5343 uint16_t exp;
5345 switch(fpregs_format) {
5346 case 0:
5347 mant = qemu_get_be64(f);
5348 exp = qemu_get_be16(f);
5349 #ifdef USE_X86LDOUBLE
5350 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5351 #else
5352 /* difficult case */
5353 if (guess_mmx)
5354 env->fpregs[i].mmx.MMX_Q(0) = mant;
5355 else
5356 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5357 #endif
5358 break;
5359 case 1:
5360 mant = qemu_get_be64(f);
5361 #ifdef USE_X86LDOUBLE
5363 union x86_longdouble *p;
5364 /* difficult case */
5365 p = (void *)&env->fpregs[i];
5366 if (guess_mmx) {
5367 p->mant = mant;
5368 p->exp = 0xffff;
5369 } else {
5370 fp64_to_fp80(p, mant);
5373 #else
5374 env->fpregs[i].mmx.MMX_Q(0) = mant;
5375 #endif
5376 break;
5377 default:
5378 return -EINVAL;
5382 env->fpuc = fpuc;
5383 /* XXX: restore FPU round state */
5384 env->fpstt = (fpus >> 11) & 7;
5385 env->fpus = fpus & ~0x3800;
5386 fptag ^= 0xff;
5387 for(i = 0; i < 8; i++) {
5388 env->fptags[i] = (fptag >> i) & 1;
5391 for(i = 0; i < 6; i++)
5392 cpu_get_seg(f, &env->segs[i]);
5393 cpu_get_seg(f, &env->ldt);
5394 cpu_get_seg(f, &env->tr);
5395 cpu_get_seg(f, &env->gdt);
5396 cpu_get_seg(f, &env->idt);
5398 qemu_get_be32s(f, &env->sysenter_cs);
5399 qemu_get_be32s(f, &env->sysenter_esp);
5400 qemu_get_be32s(f, &env->sysenter_eip);
5402 qemu_get_betls(f, &env->cr[0]);
5403 qemu_get_betls(f, &env->cr[2]);
5404 qemu_get_betls(f, &env->cr[3]);
5405 qemu_get_betls(f, &env->cr[4]);
5407 for(i = 0; i < 8; i++)
5408 qemu_get_betls(f, &env->dr[i]);
5410 /* MMU */
5411 qemu_get_be32s(f, &env->a20_mask);
5413 qemu_get_be32s(f, &env->mxcsr);
5414 for(i = 0; i < CPU_NB_REGS; i++) {
5415 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5416 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5419 #ifdef TARGET_X86_64
5420 qemu_get_be64s(f, &env->efer);
5421 qemu_get_be64s(f, &env->star);
5422 qemu_get_be64s(f, &env->lstar);
5423 qemu_get_be64s(f, &env->cstar);
5424 qemu_get_be64s(f, &env->fmask);
5425 qemu_get_be64s(f, &env->kernelgsbase);
5426 #endif
5427 if (version_id >= 4)
5428 qemu_get_be32s(f, &env->smbase);
5430 /* XXX: compute hflags from scratch, except for CPL and IIF */
5431 env->hflags = hflags;
5432 tlb_flush(env, 1);
5433 #ifdef USE_KVM
5434 if (kvm_allowed) {
5435 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
5436 because no userspace IRQs will ever clear this flag */
5437 env->hflags &= ~HF_HALTED_MASK;
5438 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5439 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
5441 qemu_get_be64s(f, &env->tsc);
5442 kvm_load_registers(env);
5444 #endif
5445 return 0;
5448 #elif defined(TARGET_PPC)
5449 void cpu_save(QEMUFile *f, void *opaque)
5453 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5455 return 0;
5458 #elif defined(TARGET_MIPS)
5459 void cpu_save(QEMUFile *f, void *opaque)
5463 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5465 return 0;
5468 #elif defined(TARGET_SPARC)
5469 void cpu_save(QEMUFile *f, void *opaque)
5471 CPUState *env = opaque;
5472 int i;
5473 uint32_t tmp;
5475 for(i = 0; i < 8; i++)
5476 qemu_put_betls(f, &env->gregs[i]);
5477 for(i = 0; i < NWINDOWS * 16; i++)
5478 qemu_put_betls(f, &env->regbase[i]);
5480 /* FPU */
5481 for(i = 0; i < TARGET_FPREGS; i++) {
5482 union {
5483 float32 f;
5484 uint32_t i;
5485 } u;
5486 u.f = env->fpr[i];
5487 qemu_put_be32(f, u.i);
5490 qemu_put_betls(f, &env->pc);
5491 qemu_put_betls(f, &env->npc);
5492 qemu_put_betls(f, &env->y);
5493 tmp = GET_PSR(env);
5494 qemu_put_be32(f, tmp);
5495 qemu_put_betls(f, &env->fsr);
5496 qemu_put_betls(f, &env->tbr);
5497 #ifndef TARGET_SPARC64
5498 qemu_put_be32s(f, &env->wim);
5499 /* MMU */
5500 for(i = 0; i < 16; i++)
5501 qemu_put_be32s(f, &env->mmuregs[i]);
5502 #endif
5505 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5507 CPUState *env = opaque;
5508 int i;
5509 uint32_t tmp;
5511 for(i = 0; i < 8; i++)
5512 qemu_get_betls(f, &env->gregs[i]);
5513 for(i = 0; i < NWINDOWS * 16; i++)
5514 qemu_get_betls(f, &env->regbase[i]);
5516 /* FPU */
5517 for(i = 0; i < TARGET_FPREGS; i++) {
5518 union {
5519 float32 f;
5520 uint32_t i;
5521 } u;
5522 u.i = qemu_get_be32(f);
5523 env->fpr[i] = u.f;
5526 qemu_get_betls(f, &env->pc);
5527 qemu_get_betls(f, &env->npc);
5528 qemu_get_betls(f, &env->y);
5529 tmp = qemu_get_be32(f);
5530 env->cwp = 0; /* needed to ensure that the wrapping registers are
5531 correctly updated */
5532 PUT_PSR(env, tmp);
5533 qemu_get_betls(f, &env->fsr);
5534 qemu_get_betls(f, &env->tbr);
5535 #ifndef TARGET_SPARC64
5536 qemu_get_be32s(f, &env->wim);
5537 /* MMU */
5538 for(i = 0; i < 16; i++)
5539 qemu_get_be32s(f, &env->mmuregs[i]);
5540 #endif
5541 tlb_flush(env, 1);
5542 return 0;
5545 #elif defined(TARGET_ARM)
5547 /* ??? Need to implement these. */
5548 void cpu_save(QEMUFile *f, void *opaque)
5552 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5554 return 0;
5557 #else
5559 #warning No CPU save/restore functions
5561 #endif
5563 /***********************************************************/
5564 /* ram save/restore */
5566 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5568 int v;
5570 v = qemu_get_byte(f);
5571 switch(v) {
5572 case 0:
5573 if (qemu_get_buffer(f, buf, len) != len)
5574 return -EIO;
5575 break;
5576 case 1:
5577 v = qemu_get_byte(f);
5578 memset(buf, v, len);
5579 break;
5580 default:
5581 return -EINVAL;
5583 return 0;
5586 static int ram_load_v1(QEMUFile *f, void *opaque)
5588 int i, ret;
5590 if (qemu_get_be32(f) != phys_ram_size)
5591 return -EINVAL;
5592 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5593 #ifdef USE_KVM
5594 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5595 continue;
5596 #endif
5597 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5598 if (ret)
5599 return ret;
5601 return 0;
5604 #define BDRV_HASH_BLOCK_SIZE 1024
5605 #define IOBUF_SIZE 4096
5606 #define RAM_CBLOCK_MAGIC 0xfabe
5608 typedef struct RamCompressState {
5609 z_stream zstream;
5610 QEMUFile *f;
5611 uint8_t buf[IOBUF_SIZE];
5612 } RamCompressState;
5614 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5616 int ret;
5617 memset(s, 0, sizeof(*s));
5618 s->f = f;
5619 ret = deflateInit2(&s->zstream, 1,
5620 Z_DEFLATED, 15,
5621 9, Z_DEFAULT_STRATEGY);
5622 if (ret != Z_OK)
5623 return -1;
5624 s->zstream.avail_out = IOBUF_SIZE;
5625 s->zstream.next_out = s->buf;
5626 return 0;
5629 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5631 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5632 qemu_put_be16(s->f, len);
5633 qemu_put_buffer(s->f, buf, len);
5636 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5638 int ret;
5640 s->zstream.avail_in = len;
5641 s->zstream.next_in = (uint8_t *)buf;
5642 while (s->zstream.avail_in > 0) {
5643 ret = deflate(&s->zstream, Z_NO_FLUSH);
5644 if (ret != Z_OK)
5645 return -1;
5646 if (s->zstream.avail_out == 0) {
5647 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5648 s->zstream.avail_out = IOBUF_SIZE;
5649 s->zstream.next_out = s->buf;
5652 return 0;
5655 static void ram_compress_close(RamCompressState *s)
5657 int len, ret;
5659 /* compress last bytes */
5660 for(;;) {
5661 ret = deflate(&s->zstream, Z_FINISH);
5662 if (ret == Z_OK || ret == Z_STREAM_END) {
5663 len = IOBUF_SIZE - s->zstream.avail_out;
5664 if (len > 0) {
5665 ram_put_cblock(s, s->buf, len);
5667 s->zstream.avail_out = IOBUF_SIZE;
5668 s->zstream.next_out = s->buf;
5669 if (ret == Z_STREAM_END)
5670 break;
5671 } else {
5672 goto fail;
5675 fail:
5676 deflateEnd(&s->zstream);
5679 typedef struct RamDecompressState {
5680 z_stream zstream;
5681 QEMUFile *f;
5682 uint8_t buf[IOBUF_SIZE];
5683 } RamDecompressState;
5685 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5687 int ret;
5688 memset(s, 0, sizeof(*s));
5689 s->f = f;
5690 ret = inflateInit(&s->zstream);
5691 if (ret != Z_OK)
5692 return -1;
5693 return 0;
5696 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5698 int ret, clen;
5700 s->zstream.avail_out = len;
5701 s->zstream.next_out = buf;
5702 while (s->zstream.avail_out > 0) {
5703 if (s->zstream.avail_in == 0) {
5704 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5705 return -1;
5706 clen = qemu_get_be16(s->f);
5707 if (clen > IOBUF_SIZE)
5708 return -1;
5709 qemu_get_buffer(s->f, s->buf, clen);
5710 s->zstream.avail_in = clen;
5711 s->zstream.next_in = s->buf;
5713 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5714 if (ret != Z_OK && ret != Z_STREAM_END) {
5715 return -1;
5718 return 0;
5721 static void ram_decompress_close(RamDecompressState *s)
5723 inflateEnd(&s->zstream);
5726 static void ram_save_live(QEMUFile *f, void *opaque)
5728 target_ulong addr;
5730 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
5731 #ifdef USE_KVM
5732 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
5733 continue;
5734 #endif
5735 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
5736 qemu_put_be32(f, addr);
5737 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5740 qemu_put_be32(f, 1);
5743 static void ram_save_static(QEMUFile *f, void *opaque)
5745 int i;
5746 RamCompressState s1, *s = &s1;
5747 uint8_t buf[10];
5749 qemu_put_be32(f, phys_ram_size);
5750 if (ram_compress_open(s, f) < 0)
5751 return;
5752 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5753 #ifdef USE_KVM
5754 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5755 continue;
5756 #endif
5757 #if 0
5758 if (tight_savevm_enabled) {
5759 int64_t sector_num;
5760 int j;
5762 /* find if the memory block is available on a virtual
5763 block device */
5764 sector_num = -1;
5765 for(j = 0; j < MAX_DISKS; j++) {
5766 if (bs_table[j]) {
5767 sector_num = bdrv_hash_find(bs_table[j],
5768 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5769 if (sector_num >= 0)
5770 break;
5773 if (j == MAX_DISKS)
5774 goto normal_compress;
5775 buf[0] = 1;
5776 buf[1] = j;
5777 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5778 ram_compress_buf(s, buf, 10);
5779 } else
5780 #endif
5782 // normal_compress:
5783 buf[0] = 0;
5784 ram_compress_buf(s, buf, 1);
5785 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5788 ram_compress_close(s);
5791 static void ram_save(QEMUFile *f, void *opaque)
5793 int in_migration = cpu_physical_memory_get_dirty_tracking();
5795 qemu_put_byte(f, in_migration);
5797 if (in_migration)
5798 ram_save_live(f, opaque);
5799 else
5800 ram_save_static(f, opaque);
5803 static int ram_load_live(QEMUFile *f, void *opaque)
5805 target_ulong addr;
5807 do {
5808 addr = qemu_get_be32(f);
5809 if (addr == 1)
5810 break;
5812 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5813 } while (1);
5815 return 0;
5818 static int ram_load_static(QEMUFile *f, void *opaque)
5820 RamDecompressState s1, *s = &s1;
5821 uint8_t buf[10];
5822 int i;
5824 if (qemu_get_be32(f) != phys_ram_size)
5825 return -EINVAL;
5826 if (ram_decompress_open(s, f) < 0)
5827 return -EINVAL;
5828 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5829 #ifdef USE_KVM
5830 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5831 continue;
5832 #endif
5833 if (ram_decompress_buf(s, buf, 1) < 0) {
5834 fprintf(stderr, "Error while reading ram block header\n");
5835 goto error;
5837 if (buf[0] == 0) {
5838 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5839 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5840 goto error;
5842 } else
5843 #if 0
5844 if (buf[0] == 1) {
5845 int bs_index;
5846 int64_t sector_num;
5848 ram_decompress_buf(s, buf + 1, 9);
5849 bs_index = buf[1];
5850 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5851 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5852 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5853 goto error;
5855 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5856 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5857 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5858 bs_index, sector_num);
5859 goto error;
5861 } else
5862 #endif
5864 error:
5865 printf("Error block header\n");
5866 return -EINVAL;
5869 ram_decompress_close(s);
5870 return 0;
5873 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5875 int ret;
5877 switch (version_id) {
5878 case 1:
5879 ret = ram_load_v1(f, opaque);
5880 break;
5881 case 3:
5882 if (qemu_get_byte(f)) {
5883 ret = ram_load_live(f, opaque);
5884 break;
5886 case 2:
5887 ret = ram_load_static(f, opaque);
5888 break;
5889 default:
5890 ret = -EINVAL;
5891 break;
5894 return ret;
5897 /***********************************************************/
5898 /* bottom halves (can be seen as timers which expire ASAP) */
5900 struct QEMUBH {
5901 QEMUBHFunc *cb;
5902 void *opaque;
5903 int scheduled;
5904 QEMUBH *next;
5907 static QEMUBH *first_bh = NULL;
5909 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5911 QEMUBH *bh;
5912 bh = qemu_mallocz(sizeof(QEMUBH));
5913 if (!bh)
5914 return NULL;
5915 bh->cb = cb;
5916 bh->opaque = opaque;
5917 return bh;
5920 int qemu_bh_poll(void)
5922 QEMUBH *bh, **pbh;
5923 int ret;
5925 ret = 0;
5926 for(;;) {
5927 pbh = &first_bh;
5928 bh = *pbh;
5929 if (!bh)
5930 break;
5931 ret = 1;
5932 *pbh = bh->next;
5933 bh->scheduled = 0;
5934 bh->cb(bh->opaque);
5936 return ret;
5939 void qemu_bh_schedule(QEMUBH *bh)
5941 CPUState *env = cpu_single_env;
5942 if (bh->scheduled)
5943 return;
5944 bh->scheduled = 1;
5945 bh->next = first_bh;
5946 first_bh = bh;
5948 /* stop the currently executing CPU to execute the BH ASAP */
5949 if (env) {
5950 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5954 void qemu_bh_cancel(QEMUBH *bh)
5956 QEMUBH **pbh;
5957 if (bh->scheduled) {
5958 pbh = &first_bh;
5959 while (*pbh != bh)
5960 pbh = &(*pbh)->next;
5961 *pbh = bh->next;
5962 bh->scheduled = 0;
5966 void qemu_bh_delete(QEMUBH *bh)
5968 qemu_bh_cancel(bh);
5969 qemu_free(bh);
5972 /***********************************************************/
5973 /* machine registration */
5975 QEMUMachine *first_machine = NULL;
5977 int qemu_register_machine(QEMUMachine *m)
5979 QEMUMachine **pm;
5980 pm = &first_machine;
5981 while (*pm != NULL)
5982 pm = &(*pm)->next;
5983 m->next = NULL;
5984 *pm = m;
5985 return 0;
5988 QEMUMachine *find_machine(const char *name)
5990 QEMUMachine *m;
5992 for(m = first_machine; m != NULL; m = m->next) {
5993 if (!strcmp(m->name, name))
5994 return m;
5996 return NULL;
5999 /***********************************************************/
6000 /* main execution loop */
6002 void gui_update(void *opaque)
6004 display_state.dpy_refresh(&display_state);
6005 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6008 struct vm_change_state_entry {
6009 VMChangeStateHandler *cb;
6010 void *opaque;
6011 LIST_ENTRY (vm_change_state_entry) entries;
6014 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6016 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6017 void *opaque)
6019 VMChangeStateEntry *e;
6021 e = qemu_mallocz(sizeof (*e));
6022 if (!e)
6023 return NULL;
6025 e->cb = cb;
6026 e->opaque = opaque;
6027 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6028 return e;
6031 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6033 LIST_REMOVE (e, entries);
6034 qemu_free (e);
6037 static void vm_state_notify(int running)
6039 VMChangeStateEntry *e;
6041 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6042 e->cb(e->opaque, running);
6046 /* XXX: support several handlers */
6047 static VMStopHandler *vm_stop_cb;
6048 static void *vm_stop_opaque;
6050 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6052 vm_stop_cb = cb;
6053 vm_stop_opaque = opaque;
6054 return 0;
6057 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6059 vm_stop_cb = NULL;
6062 void vm_start(void)
6064 if (!vm_running) {
6065 cpu_enable_ticks();
6066 vm_running = 1;
6067 vm_state_notify(1);
6071 void vm_stop(int reason)
6073 if (vm_running) {
6074 cpu_disable_ticks();
6075 vm_running = 0;
6076 if (reason != 0) {
6077 if (vm_stop_cb) {
6078 vm_stop_cb(vm_stop_opaque, reason);
6081 vm_state_notify(0);
6085 /* reset/shutdown handler */
6087 typedef struct QEMUResetEntry {
6088 QEMUResetHandler *func;
6089 void *opaque;
6090 struct QEMUResetEntry *next;
6091 } QEMUResetEntry;
6093 static QEMUResetEntry *first_reset_entry;
6094 static int reset_requested;
6095 static int shutdown_requested;
6096 static int powerdown_requested;
6098 int qemu_shutdown_requested(void)
6100 int r = shutdown_requested;
6101 shutdown_requested = 0;
6102 return r;
6105 int qemu_reset_requested(void)
6107 int r = reset_requested;
6108 reset_requested = 0;
6109 return r;
6112 int qemu_powerdown_requested(void)
6114 int r = powerdown_requested;
6115 powerdown_requested = 0;
6116 return r;
6119 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6121 QEMUResetEntry **pre, *re;
6123 pre = &first_reset_entry;
6124 while (*pre != NULL)
6125 pre = &(*pre)->next;
6126 re = qemu_mallocz(sizeof(QEMUResetEntry));
6127 re->func = func;
6128 re->opaque = opaque;
6129 re->next = NULL;
6130 *pre = re;
6133 void qemu_system_reset(void)
6135 QEMUResetEntry *re;
6137 /* reset all devices */
6138 for(re = first_reset_entry; re != NULL; re = re->next) {
6139 re->func(re->opaque);
6143 void qemu_system_reset_request(void)
6145 if (no_reboot) {
6146 shutdown_requested = 1;
6147 } else {
6148 reset_requested = 1;
6150 if (cpu_single_env)
6151 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6154 void qemu_system_shutdown_request(void)
6156 shutdown_requested = 1;
6157 if (cpu_single_env)
6158 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6161 void qemu_system_powerdown_request(void)
6163 powerdown_requested = 1;
6164 if (cpu_single_env)
6165 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6168 void main_loop_wait(int timeout)
6170 IOHandlerRecord *ioh;
6171 fd_set rfds, wfds, xfds;
6172 int ret, nfds;
6173 struct timeval tv;
6174 PollingEntry *pe;
6177 /* XXX: need to suppress polling by better using win32 events */
6178 ret = 0;
6179 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6180 ret |= pe->func(pe->opaque);
6182 #ifdef _WIN32
6183 if (ret == 0 && timeout > 0) {
6184 int err;
6185 WaitObjects *w = &wait_objects;
6187 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6188 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6189 if (w->func[ret - WAIT_OBJECT_0])
6190 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6191 } else if (ret == WAIT_TIMEOUT) {
6192 } else {
6193 err = GetLastError();
6194 fprintf(stderr, "Wait error %d %d\n", ret, err);
6197 #endif
6198 /* poll any events */
6199 /* XXX: separate device handlers from system ones */
6200 nfds = -1;
6201 FD_ZERO(&rfds);
6202 FD_ZERO(&wfds);
6203 FD_ZERO(&xfds);
6204 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6205 if (ioh->deleted)
6206 continue;
6207 if (ioh->fd_read &&
6208 (!ioh->fd_read_poll ||
6209 ioh->fd_read_poll(ioh->opaque) != 0)) {
6210 FD_SET(ioh->fd, &rfds);
6211 if (ioh->fd > nfds)
6212 nfds = ioh->fd;
6214 if (ioh->fd_write) {
6215 FD_SET(ioh->fd, &wfds);
6216 if (ioh->fd > nfds)
6217 nfds = ioh->fd;
6221 tv.tv_sec = 0;
6222 #ifdef _WIN32
6223 tv.tv_usec = 0;
6224 #else
6225 tv.tv_usec = timeout * 1000;
6226 #endif
6227 #if defined(CONFIG_SLIRP)
6228 if (slirp_inited) {
6229 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6231 #endif
6232 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6233 if (ret > 0) {
6234 IOHandlerRecord **pioh;
6236 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6237 if (ioh->deleted)
6238 continue;
6239 if (FD_ISSET(ioh->fd, &rfds)) {
6240 ioh->fd_read(ioh->opaque);
6242 if (FD_ISSET(ioh->fd, &wfds)) {
6243 ioh->fd_write(ioh->opaque);
6247 /* remove deleted IO handlers */
6248 pioh = &first_io_handler;
6249 while (*pioh) {
6250 ioh = *pioh;
6251 if (ioh->deleted) {
6252 *pioh = ioh->next;
6253 qemu_free(ioh);
6254 } else
6255 pioh = &ioh->next;
6258 #if defined(CONFIG_SLIRP)
6259 if (slirp_inited) {
6260 if (ret < 0) {
6261 FD_ZERO(&rfds);
6262 FD_ZERO(&wfds);
6263 FD_ZERO(&xfds);
6265 slirp_select_poll(&rfds, &wfds, &xfds);
6267 #endif
6268 qemu_aio_poll();
6269 qemu_bh_poll();
6271 if (vm_running) {
6272 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6273 qemu_get_clock(vm_clock));
6274 /* run dma transfers, if any */
6275 DMA_run();
6278 /* real time timers */
6279 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6280 qemu_get_clock(rt_clock));
6283 static CPUState *cur_cpu;
6285 int main_loop(void)
6287 int ret, timeout;
6288 #ifdef CONFIG_PROFILER
6289 int64_t ti;
6290 #endif
6291 CPUState *env;
6294 #ifdef USE_KVM
6295 if (kvm_allowed) {
6296 kvm_main_loop();
6297 cpu_disable_ticks();
6298 return 0;
6300 #endif
6301 cur_cpu = first_cpu;
6302 for(;;) {
6303 if (vm_running) {
6305 env = cur_cpu;
6306 for(;;) {
6307 /* get next cpu */
6308 env = env->next_cpu;
6309 if (!env)
6310 env = first_cpu;
6311 #ifdef CONFIG_PROFILER
6312 ti = profile_getclock();
6313 #endif
6314 ret = cpu_exec(env);
6315 #ifdef CONFIG_PROFILER
6316 qemu_time += profile_getclock() - ti;
6317 #endif
6318 if (ret != EXCP_HALTED)
6319 break;
6320 /* all CPUs are halted ? */
6321 if (env == cur_cpu) {
6322 ret = EXCP_HLT;
6323 break;
6326 cur_cpu = env;
6328 if (shutdown_requested) {
6329 ret = EXCP_INTERRUPT;
6330 break;
6332 if (reset_requested) {
6333 reset_requested = 0;
6334 qemu_system_reset();
6335 #ifdef USE_KVM
6336 if (kvm_allowed)
6337 kvm_load_registers(env);
6338 #endif
6339 ret = EXCP_INTERRUPT;
6341 if (powerdown_requested) {
6342 powerdown_requested = 0;
6343 qemu_system_powerdown();
6344 ret = EXCP_INTERRUPT;
6346 if (ret == EXCP_DEBUG) {
6347 vm_stop(EXCP_DEBUG);
6349 /* if hlt instruction, we wait until the next IRQ */
6350 /* XXX: use timeout computed from timers */
6351 if (ret == EXCP_HLT)
6352 timeout = 10;
6353 else
6354 timeout = 0;
6355 } else {
6356 timeout = 10;
6358 #ifdef CONFIG_PROFILER
6359 ti = profile_getclock();
6360 #endif
6361 main_loop_wait(timeout);
6362 #ifdef CONFIG_PROFILER
6363 dev_time += profile_getclock() - ti;
6364 #endif
6366 cpu_disable_ticks();
6367 return ret;
6370 void help(void)
6372 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6373 "usage: %s [options] [disk_image]\n"
6374 "\n"
6375 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6376 "\n"
6377 "Standard options:\n"
6378 "-M machine select emulated machine (-M ? for list)\n"
6379 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6380 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6381 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6382 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6383 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6384 "-snapshot write to temporary files instead of disk image files\n"
6385 #ifdef CONFIG_SDL
6386 "-no-quit disable SDL window close capability\n"
6387 #endif
6388 #ifdef TARGET_I386
6389 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6390 #endif
6391 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6392 "-smp n set the number of CPUs to 'n' [default=1]\n"
6393 "-nographic disable graphical output and redirect serial I/Os to console\n"
6394 #ifndef _WIN32
6395 "-k language use keyboard layout (for example \"fr\" for French)\n"
6396 #endif
6397 #ifdef HAS_AUDIO
6398 "-audio-help print list of audio drivers and their options\n"
6399 "-soundhw c1,... enable audio support\n"
6400 " and only specified sound cards (comma separated list)\n"
6401 " use -soundhw ? to get the list of supported cards\n"
6402 " use -soundhw all to enable all of them\n"
6403 #endif
6404 "-localtime set the real time clock to local time [default=utc]\n"
6405 "-full-screen start in full screen\n"
6406 #ifdef TARGET_I386
6407 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6408 #endif
6409 "-usb enable the USB driver (will be the default soon)\n"
6410 "-usbdevice name add the host or guest USB device 'name'\n"
6411 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6412 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6413 #endif
6414 "\n"
6415 "Network options:\n"
6416 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6417 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6418 #ifdef CONFIG_SLIRP
6419 "-net user[,vlan=n][,hostname=host]\n"
6420 " connect the user mode network stack to VLAN 'n' and send\n"
6421 " hostname 'host' to DHCP clients\n"
6422 #endif
6423 #ifdef _WIN32
6424 "-net tap[,vlan=n],ifname=name\n"
6425 " connect the host TAP network interface to VLAN 'n'\n"
6426 #else
6427 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6428 " connect the host TAP network interface to VLAN 'n' and use\n"
6429 " the network script 'file' (default=%s);\n"
6430 " use 'script=no' to disable script execution;\n"
6431 " use 'fd=h' to connect to an already opened TAP interface\n"
6432 #endif
6433 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6434 " connect the vlan 'n' to another VLAN using a socket connection\n"
6435 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6436 " connect the vlan 'n' to multicast maddr and port\n"
6437 "-net none use it alone to have zero network devices; if no -net option\n"
6438 " is provided, the default is '-net nic -net user'\n"
6439 "\n"
6440 #ifdef CONFIG_SLIRP
6441 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6442 #ifndef _WIN32
6443 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6444 #endif
6445 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6446 " redirect TCP or UDP connections from host to guest [-net user]\n"
6447 #endif
6448 "\n"
6449 "Linux boot specific:\n"
6450 "-kernel bzImage use 'bzImage' as kernel image\n"
6451 "-append cmdline use 'cmdline' as kernel command line\n"
6452 "-initrd file use 'file' as initial ram disk\n"
6453 "\n"
6454 "Debug/Expert options:\n"
6455 "-monitor dev redirect the monitor to char device 'dev'\n"
6456 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6457 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
6458 "-serial dev redirect the serial port to char device 'dev'\n"
6459 "-parallel dev redirect the parallel port to char device 'dev'\n"
6460 "-pidfile file Write PID to 'file'\n"
6461 "-S freeze CPU at startup (use 'c' to start execution)\n"
6462 "-s wait gdb connection to port %d\n"
6463 "-p port change gdb connection port\n"
6464 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6465 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6466 " translation (t=none or lba) (usually qemu can guess them)\n"
6467 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6468 #ifdef USE_KQEMU
6469 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6470 "-no-kqemu disable KQEMU kernel module usage\n"
6471 #endif
6472 #ifdef USE_KVM
6473 "-no-kvm disable KVM hardware virtualization\n"
6474 #endif
6475 #ifdef USE_CODE_COPY
6476 "-no-code-copy disable code copy acceleration\n"
6477 #endif
6478 #ifdef TARGET_I386
6479 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6480 " (default is CL-GD5446 PCI VGA)\n"
6481 "-no-acpi disable ACPI\n"
6482 #endif
6483 "-no-reboot exit instead of rebooting\n"
6484 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6485 "-vnc display start a VNC server on display\n"
6486 #ifndef _WIN32
6487 "-daemonize daemonize QEMU after initializing\n"
6488 #endif
6489 "-tdf inject timer interrupts that got lost\n"
6490 #if defined(__linux__)
6491 "-no-rtc don't use /dev/rtc for timer alarm (do use gettimeofday)\n"
6492 #endif
6493 "-option-rom rom load a file, rom, into the option ROM space\n"
6494 "\n"
6495 "During emulation, the following keys are useful:\n"
6496 "ctrl-alt-f toggle full screen\n"
6497 "ctrl-alt-n switch to virtual console 'n'\n"
6498 "ctrl-alt toggle mouse and keyboard grab\n"
6499 "\n"
6500 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6502 "qemu",
6503 DEFAULT_RAM_SIZE,
6504 #ifndef _WIN32
6505 DEFAULT_NETWORK_SCRIPT,
6506 #endif
6507 DEFAULT_GDBSTUB_PORT,
6508 "/tmp/qemu.log");
6509 exit(1);
6512 #define HAS_ARG 0x0001
6514 enum {
6515 QEMU_OPTION_h,
6517 QEMU_OPTION_M,
6518 QEMU_OPTION_fda,
6519 QEMU_OPTION_fdb,
6520 QEMU_OPTION_hda,
6521 QEMU_OPTION_hdb,
6522 QEMU_OPTION_hdc,
6523 QEMU_OPTION_hdd,
6524 QEMU_OPTION_cdrom,
6525 QEMU_OPTION_boot,
6526 QEMU_OPTION_snapshot,
6527 #ifdef TARGET_I386
6528 QEMU_OPTION_no_fd_bootchk,
6529 #endif
6530 QEMU_OPTION_m,
6531 QEMU_OPTION_nographic,
6532 #ifdef HAS_AUDIO
6533 QEMU_OPTION_audio_help,
6534 QEMU_OPTION_soundhw,
6535 #endif
6537 QEMU_OPTION_net,
6538 QEMU_OPTION_tftp,
6539 QEMU_OPTION_smb,
6540 QEMU_OPTION_redir,
6542 QEMU_OPTION_kernel,
6543 QEMU_OPTION_append,
6544 QEMU_OPTION_initrd,
6546 QEMU_OPTION_S,
6547 QEMU_OPTION_s,
6548 QEMU_OPTION_p,
6549 QEMU_OPTION_d,
6550 QEMU_OPTION_hdachs,
6551 QEMU_OPTION_L,
6552 QEMU_OPTION_no_code_copy,
6553 QEMU_OPTION_k,
6554 QEMU_OPTION_localtime,
6555 QEMU_OPTION_cirrusvga,
6556 QEMU_OPTION_g,
6557 QEMU_OPTION_std_vga,
6558 QEMU_OPTION_monitor,
6559 QEMU_OPTION_balloon,
6560 QEMU_OPTION_vmchannel,
6561 QEMU_OPTION_serial,
6562 QEMU_OPTION_parallel,
6563 QEMU_OPTION_loadvm,
6564 QEMU_OPTION_full_screen,
6565 QEMU_OPTION_no_quit,
6566 QEMU_OPTION_pidfile,
6567 QEMU_OPTION_no_kqemu,
6568 QEMU_OPTION_kernel_kqemu,
6569 QEMU_OPTION_win2k_hack,
6570 QEMU_OPTION_usb,
6571 QEMU_OPTION_usbdevice,
6572 QEMU_OPTION_smp,
6573 QEMU_OPTION_vnc,
6574 QEMU_OPTION_no_acpi,
6575 QEMU_OPTION_no_kvm,
6576 QEMU_OPTION_no_kvm_irqchip,
6577 QEMU_OPTION_no_reboot,
6578 QEMU_OPTION_daemonize,
6579 QEMU_OPTION_option_rom,
6580 QEMU_OPTION_semihosting,
6581 QEMU_OPTION_incoming,
6582 QEMU_OPTION_tdf,
6583 #if defined(__linux__)
6584 QEMU_OPTION_no_rtc,
6585 #endif
6586 QEMU_OPTION_cpu_vendor,
6589 typedef struct QEMUOption {
6590 const char *name;
6591 int flags;
6592 int index;
6593 } QEMUOption;
6595 const QEMUOption qemu_options[] = {
6596 { "h", 0, QEMU_OPTION_h },
6597 { "help", 0, QEMU_OPTION_h },
6599 { "M", HAS_ARG, QEMU_OPTION_M },
6600 { "fda", HAS_ARG, QEMU_OPTION_fda },
6601 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6602 { "hda", HAS_ARG, QEMU_OPTION_hda },
6603 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6604 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6605 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6606 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6607 { "boot", HAS_ARG, QEMU_OPTION_boot },
6608 { "snapshot", 0, QEMU_OPTION_snapshot },
6609 #ifdef TARGET_I386
6610 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6611 #endif
6612 { "m", HAS_ARG, QEMU_OPTION_m },
6613 { "nographic", 0, QEMU_OPTION_nographic },
6614 { "k", HAS_ARG, QEMU_OPTION_k },
6615 #ifdef HAS_AUDIO
6616 { "audio-help", 0, QEMU_OPTION_audio_help },
6617 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6618 #endif
6620 { "net", HAS_ARG, QEMU_OPTION_net},
6621 #ifdef CONFIG_SLIRP
6622 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6623 #ifndef _WIN32
6624 { "smb", HAS_ARG, QEMU_OPTION_smb },
6625 #endif
6626 { "redir", HAS_ARG, QEMU_OPTION_redir },
6627 #endif
6629 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6630 { "append", HAS_ARG, QEMU_OPTION_append },
6631 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6633 { "S", 0, QEMU_OPTION_S },
6634 { "s", 0, QEMU_OPTION_s },
6635 { "p", HAS_ARG, QEMU_OPTION_p },
6636 { "d", HAS_ARG, QEMU_OPTION_d },
6637 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6638 { "L", HAS_ARG, QEMU_OPTION_L },
6639 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6640 #ifdef USE_KQEMU
6641 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6642 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6643 #endif
6644 #ifdef USE_KVM
6645 { "no-kvm", 0, QEMU_OPTION_no_kvm },
6646 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
6647 #endif
6648 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6649 { "g", 1, QEMU_OPTION_g },
6650 #endif
6651 { "localtime", 0, QEMU_OPTION_localtime },
6652 { "std-vga", 0, QEMU_OPTION_std_vga },
6653 { "monitor", 1, QEMU_OPTION_monitor },
6654 { "balloon", 1, QEMU_OPTION_balloon },
6655 { "vmchannel", 1, QEMU_OPTION_vmchannel },
6656 { "serial", 1, QEMU_OPTION_serial },
6657 { "parallel", 1, QEMU_OPTION_parallel },
6658 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6659 { "incoming", 1, QEMU_OPTION_incoming },
6660 { "full-screen", 0, QEMU_OPTION_full_screen },
6661 #ifdef CONFIG_SDL
6662 { "no-quit", 0, QEMU_OPTION_no_quit },
6663 #endif
6664 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6665 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6666 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6667 { "smp", HAS_ARG, QEMU_OPTION_smp },
6668 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6670 /* temporary options */
6671 { "usb", 0, QEMU_OPTION_usb },
6672 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6673 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6674 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6675 { "daemonize", 0, QEMU_OPTION_daemonize },
6676 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6677 #if defined(TARGET_ARM)
6678 { "semihosting", 0, QEMU_OPTION_semihosting },
6679 #endif
6680 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
6681 #if defined(__linux__)
6682 { "no-rtc", 0, QEMU_OPTION_no_rtc },
6683 #endif
6684 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
6685 { NULL },
6688 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6690 /* this stack is only used during signal handling */
6691 #define SIGNAL_STACK_SIZE 32768
6693 static uint8_t *signal_stack;
6695 #endif
6697 /* password input */
6699 static BlockDriverState *get_bdrv(int index)
6701 BlockDriverState *bs;
6703 if (index < 4) {
6704 bs = bs_table[index];
6705 } else if (index < 6) {
6706 bs = fd_table[index - 4];
6707 } else {
6708 bs = NULL;
6710 return bs;
6713 static void read_passwords(void)
6715 BlockDriverState *bs;
6716 int i, j;
6717 char password[256];
6719 for(i = 0; i < 6; i++) {
6720 bs = get_bdrv(i);
6721 if (bs && bdrv_is_encrypted(bs)) {
6722 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6723 for(j = 0; j < 3; j++) {
6724 monitor_readline("Password: ",
6725 1, password, sizeof(password));
6726 if (bdrv_set_key(bs, password) == 0)
6727 break;
6728 term_printf("invalid password\n");
6734 /* XXX: currently we cannot use simultaneously different CPUs */
6735 void register_machines(void)
6737 #if defined(TARGET_I386)
6738 qemu_register_machine(&pc_machine);
6739 qemu_register_machine(&isapc_machine);
6740 #elif defined(TARGET_PPC)
6741 qemu_register_machine(&heathrow_machine);
6742 qemu_register_machine(&core99_machine);
6743 qemu_register_machine(&prep_machine);
6744 #elif defined(TARGET_MIPS)
6745 qemu_register_machine(&mips_machine);
6746 qemu_register_machine(&mips_malta_machine);
6747 #elif defined(TARGET_SPARC)
6748 #ifdef TARGET_SPARC64
6749 qemu_register_machine(&sun4u_machine);
6750 #else
6751 qemu_register_machine(&sun4m_machine);
6752 #endif
6753 #elif defined(TARGET_ARM)
6754 qemu_register_machine(&integratorcp926_machine);
6755 qemu_register_machine(&integratorcp1026_machine);
6756 qemu_register_machine(&versatilepb_machine);
6757 qemu_register_machine(&versatileab_machine);
6758 qemu_register_machine(&realview_machine);
6759 #elif defined(TARGET_SH4)
6760 qemu_register_machine(&shix_machine);
6761 #else
6762 #error unsupported CPU
6763 #endif
6766 #ifdef HAS_AUDIO
6767 struct soundhw soundhw[] = {
6768 #ifdef TARGET_I386
6770 "pcspk",
6771 "PC speaker",
6774 { .init_isa = pcspk_audio_init }
6776 #endif
6778 "sb16",
6779 "Creative Sound Blaster 16",
6782 { .init_isa = SB16_init }
6785 #ifdef CONFIG_ADLIB
6787 "adlib",
6788 #ifdef HAS_YMF262
6789 "Yamaha YMF262 (OPL3)",
6790 #else
6791 "Yamaha YM3812 (OPL2)",
6792 #endif
6795 { .init_isa = Adlib_init }
6797 #endif
6799 #ifdef CONFIG_GUS
6801 "gus",
6802 "Gravis Ultrasound GF1",
6805 { .init_isa = GUS_init }
6807 #endif
6810 "es1370",
6811 "ENSONIQ AudioPCI ES1370",
6814 { .init_pci = es1370_init }
6817 { NULL, NULL, 0, 0, { NULL } }
6820 static void select_soundhw (const char *optarg)
6822 struct soundhw *c;
6824 if (*optarg == '?') {
6825 show_valid_cards:
6827 printf ("Valid sound card names (comma separated):\n");
6828 for (c = soundhw; c->name; ++c) {
6829 printf ("%-11s %s\n", c->name, c->descr);
6831 printf ("\n-soundhw all will enable all of the above\n");
6832 exit (*optarg != '?');
6834 else {
6835 size_t l;
6836 const char *p;
6837 char *e;
6838 int bad_card = 0;
6840 if (!strcmp (optarg, "all")) {
6841 for (c = soundhw; c->name; ++c) {
6842 c->enabled = 1;
6844 return;
6847 p = optarg;
6848 while (*p) {
6849 e = strchr (p, ',');
6850 l = !e ? strlen (p) : (size_t) (e - p);
6852 for (c = soundhw; c->name; ++c) {
6853 if (!strncmp (c->name, p, l)) {
6854 c->enabled = 1;
6855 break;
6859 if (!c->name) {
6860 if (l > 80) {
6861 fprintf (stderr,
6862 "Unknown sound card name (too big to show)\n");
6864 else {
6865 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6866 (int) l, p);
6868 bad_card = 1;
6870 p += l + (e != NULL);
6873 if (bad_card)
6874 goto show_valid_cards;
6877 #endif
6879 #ifdef _WIN32
6880 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6882 exit(STATUS_CONTROL_C_EXIT);
6883 return TRUE;
6885 #endif
6887 #define MAX_NET_CLIENTS 32
6889 static int saved_argc;
6890 static char **saved_argv;
6892 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
6894 *argc = saved_argc;
6895 *argv = saved_argv;
6896 *opt_daemonize = daemonize;
6897 *opt_incoming = incoming;
6900 int main(int argc, char **argv)
6902 #ifdef CONFIG_GDBSTUB
6903 int use_gdbstub, gdbstub_port;
6904 #endif
6905 int i, cdrom_index;
6906 int snapshot, linux_boot;
6907 const char *initrd_filename;
6908 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6909 const char *kernel_filename, *kernel_cmdline;
6910 DisplayState *ds = &display_state;
6911 int cyls, heads, secs, translation;
6912 char net_clients[MAX_NET_CLIENTS][256];
6913 int nb_net_clients;
6914 int optind;
6915 const char *r, *optarg;
6916 CharDriverState *monitor_hd;
6917 char monitor_device[128];
6918 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
6919 int vmchannel_device_index;
6920 char serial_devices[MAX_SERIAL_PORTS][128];
6921 int serial_device_index;
6922 char parallel_devices[MAX_PARALLEL_PORTS][128];
6923 int parallel_device_index;
6924 const char *loadvm = NULL;
6925 QEMUMachine *machine;
6926 char usb_devices[MAX_USB_CMDLINE][128];
6927 int usb_devices_index;
6928 int fds[2];
6930 saved_argc = argc;
6931 saved_argv = argv;
6933 LIST_INIT (&vm_change_state_head);
6934 #ifndef _WIN32
6936 struct sigaction act;
6937 sigfillset(&act.sa_mask);
6938 act.sa_flags = 0;
6939 act.sa_handler = SIG_IGN;
6940 sigaction(SIGPIPE, &act, NULL);
6942 #else
6943 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6944 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6945 QEMU to run on a single CPU */
6947 HANDLE h;
6948 DWORD mask, smask;
6949 int i;
6950 h = GetCurrentProcess();
6951 if (GetProcessAffinityMask(h, &mask, &smask)) {
6952 for(i = 0; i < 32; i++) {
6953 if (mask & (1 << i))
6954 break;
6956 if (i != 32) {
6957 mask = 1 << i;
6958 SetProcessAffinityMask(h, mask);
6962 #endif
6964 register_machines();
6965 machine = first_machine;
6966 initrd_filename = NULL;
6967 for(i = 0; i < MAX_FD; i++)
6968 fd_filename[i] = NULL;
6969 for(i = 0; i < MAX_DISKS; i++)
6970 hd_filename[i] = NULL;
6971 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6972 vga_ram_size = VGA_RAM_SIZE;
6973 bios_size = BIOS_SIZE;
6974 #ifdef CONFIG_GDBSTUB
6975 use_gdbstub = 0;
6976 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6977 #endif
6978 snapshot = 0;
6979 nographic = 0;
6980 kernel_filename = NULL;
6981 kernel_cmdline = "";
6982 #ifdef TARGET_PPC
6983 cdrom_index = 1;
6984 #else
6985 cdrom_index = 2;
6986 #endif
6987 cyls = heads = secs = 0;
6988 translation = BIOS_ATA_TRANSLATION_AUTO;
6989 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6991 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
6992 vmchannel_devices[i][0] = '\0';
6993 vmchannel_device_index = 0;
6995 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6996 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6997 serial_devices[i][0] = '\0';
6998 serial_device_index = 0;
7000 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7001 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7002 parallel_devices[i][0] = '\0';
7003 parallel_device_index = 0;
7005 usb_devices_index = 0;
7007 nb_net_clients = 0;
7009 nb_nics = 0;
7010 /* default mac address of the first network interface */
7012 optind = 1;
7013 for(;;) {
7014 if (optind >= argc)
7015 break;
7016 r = argv[optind];
7017 if (r[0] != '-') {
7018 hd_filename[0] = argv[optind++];
7019 } else {
7020 const QEMUOption *popt;
7022 optind++;
7023 /* Treat --foo the same as -foo. */
7024 if (r[1] == '-')
7025 r++;
7026 popt = qemu_options;
7027 for(;;) {
7028 if (!popt->name) {
7029 fprintf(stderr, "%s: invalid option -- '%s'\n",
7030 argv[0], r);
7031 exit(1);
7033 if (!strcmp(popt->name, r + 1))
7034 break;
7035 popt++;
7037 if (popt->flags & HAS_ARG) {
7038 if (optind >= argc) {
7039 fprintf(stderr, "%s: option '%s' requires an argument\n",
7040 argv[0], r);
7041 exit(1);
7043 optarg = argv[optind++];
7044 } else {
7045 optarg = NULL;
7048 switch(popt->index) {
7049 case QEMU_OPTION_M:
7050 machine = find_machine(optarg);
7051 if (!machine) {
7052 QEMUMachine *m;
7053 printf("Supported machines are:\n");
7054 for(m = first_machine; m != NULL; m = m->next) {
7055 printf("%-10s %s%s\n",
7056 m->name, m->desc,
7057 m == first_machine ? " (default)" : "");
7059 exit(1);
7061 break;
7062 case QEMU_OPTION_initrd:
7063 initrd_filename = optarg;
7064 break;
7065 case QEMU_OPTION_hda:
7066 case QEMU_OPTION_hdb:
7067 case QEMU_OPTION_hdc:
7068 case QEMU_OPTION_hdd:
7070 int hd_index;
7071 hd_index = popt->index - QEMU_OPTION_hda;
7072 hd_filename[hd_index] = optarg;
7073 if (hd_index == cdrom_index)
7074 cdrom_index = -1;
7076 break;
7077 case QEMU_OPTION_snapshot:
7078 snapshot = 1;
7079 break;
7080 case QEMU_OPTION_hdachs:
7082 const char *p;
7083 p = optarg;
7084 cyls = strtol(p, (char **)&p, 0);
7085 if (cyls < 1 || cyls > 16383)
7086 goto chs_fail;
7087 if (*p != ',')
7088 goto chs_fail;
7089 p++;
7090 heads = strtol(p, (char **)&p, 0);
7091 if (heads < 1 || heads > 16)
7092 goto chs_fail;
7093 if (*p != ',')
7094 goto chs_fail;
7095 p++;
7096 secs = strtol(p, (char **)&p, 0);
7097 if (secs < 1 || secs > 63)
7098 goto chs_fail;
7099 if (*p == ',') {
7100 p++;
7101 if (!strcmp(p, "none"))
7102 translation = BIOS_ATA_TRANSLATION_NONE;
7103 else if (!strcmp(p, "lba"))
7104 translation = BIOS_ATA_TRANSLATION_LBA;
7105 else if (!strcmp(p, "auto"))
7106 translation = BIOS_ATA_TRANSLATION_AUTO;
7107 else
7108 goto chs_fail;
7109 } else if (*p != '\0') {
7110 chs_fail:
7111 fprintf(stderr, "qemu: invalid physical CHS format\n");
7112 exit(1);
7115 break;
7116 case QEMU_OPTION_nographic:
7117 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7118 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7119 nographic = 1;
7120 break;
7121 case QEMU_OPTION_kernel:
7122 kernel_filename = optarg;
7123 break;
7124 case QEMU_OPTION_append:
7125 kernel_cmdline = optarg;
7126 break;
7127 case QEMU_OPTION_cdrom:
7128 if (cdrom_index >= 0) {
7129 hd_filename[cdrom_index] = optarg;
7131 break;
7132 case QEMU_OPTION_boot:
7133 boot_device = optarg[0];
7134 if (boot_device != 'a' &&
7135 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7136 // Network boot
7137 boot_device != 'n' &&
7138 #endif
7139 boot_device != 'c' && boot_device != 'd') {
7140 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7141 exit(1);
7143 break;
7144 case QEMU_OPTION_fda:
7145 fd_filename[0] = optarg;
7146 break;
7147 case QEMU_OPTION_fdb:
7148 fd_filename[1] = optarg;
7149 break;
7150 #ifdef TARGET_I386
7151 case QEMU_OPTION_no_fd_bootchk:
7152 fd_bootchk = 0;
7153 break;
7154 #endif
7155 case QEMU_OPTION_no_code_copy:
7156 code_copy_enabled = 0;
7157 break;
7158 case QEMU_OPTION_net:
7159 if (nb_net_clients >= MAX_NET_CLIENTS) {
7160 fprintf(stderr, "qemu: too many network clients\n");
7161 exit(1);
7163 pstrcpy(net_clients[nb_net_clients],
7164 sizeof(net_clients[0]),
7165 optarg);
7166 nb_net_clients++;
7167 break;
7168 #ifdef CONFIG_SLIRP
7169 case QEMU_OPTION_tftp:
7170 tftp_prefix = optarg;
7171 break;
7172 #ifndef _WIN32
7173 case QEMU_OPTION_smb:
7174 net_slirp_smb(optarg);
7175 break;
7176 #endif
7177 case QEMU_OPTION_redir:
7178 net_slirp_redir(optarg);
7179 break;
7180 #endif
7181 #ifdef HAS_AUDIO
7182 case QEMU_OPTION_audio_help:
7183 AUD_help ();
7184 exit (0);
7185 break;
7186 case QEMU_OPTION_soundhw:
7187 select_soundhw (optarg);
7188 break;
7189 #endif
7190 case QEMU_OPTION_h:
7191 help();
7192 break;
7193 case QEMU_OPTION_m:
7194 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
7195 if (ram_size <= 0)
7196 help();
7197 if (ram_size > PHYS_RAM_MAX_SIZE) {
7198 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7199 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7200 exit(1);
7202 break;
7203 case QEMU_OPTION_d:
7205 int mask;
7206 CPULogItem *item;
7208 mask = cpu_str_to_log_mask(optarg);
7209 if (!mask) {
7210 printf("Log items (comma separated):\n");
7211 for(item = cpu_log_items; item->mask != 0; item++) {
7212 printf("%-10s %s\n", item->name, item->help);
7214 exit(1);
7216 cpu_set_log(mask);
7218 break;
7219 #ifdef CONFIG_GDBSTUB
7220 case QEMU_OPTION_s:
7221 use_gdbstub = 1;
7222 break;
7223 case QEMU_OPTION_p:
7224 gdbstub_port = atoi(optarg);
7225 break;
7226 #endif
7227 case QEMU_OPTION_L:
7228 bios_dir = optarg;
7229 break;
7230 case QEMU_OPTION_S:
7231 autostart = 0;
7232 break;
7233 case QEMU_OPTION_k:
7234 keyboard_layout = optarg;
7235 break;
7236 case QEMU_OPTION_localtime:
7237 rtc_utc = 0;
7238 break;
7239 case QEMU_OPTION_cirrusvga:
7240 cirrus_vga_enabled = 1;
7241 break;
7242 case QEMU_OPTION_std_vga:
7243 cirrus_vga_enabled = 0;
7244 break;
7245 case QEMU_OPTION_g:
7247 const char *p;
7248 int w, h, depth;
7249 p = optarg;
7250 w = strtol(p, (char **)&p, 10);
7251 if (w <= 0) {
7252 graphic_error:
7253 fprintf(stderr, "qemu: invalid resolution or depth\n");
7254 exit(1);
7256 if (*p != 'x')
7257 goto graphic_error;
7258 p++;
7259 h = strtol(p, (char **)&p, 10);
7260 if (h <= 0)
7261 goto graphic_error;
7262 if (*p == 'x') {
7263 p++;
7264 depth = strtol(p, (char **)&p, 10);
7265 if (depth != 8 && depth != 15 && depth != 16 &&
7266 depth != 24 && depth != 32)
7267 goto graphic_error;
7268 } else if (*p == '\0') {
7269 depth = graphic_depth;
7270 } else {
7271 goto graphic_error;
7274 graphic_width = w;
7275 graphic_height = h;
7276 graphic_depth = depth;
7278 break;
7279 case QEMU_OPTION_monitor:
7280 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7281 break;
7282 case QEMU_OPTION_balloon:
7283 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7284 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7285 exit(1);
7287 if (balloon_used) {
7288 fprintf(stderr, "qemu: only one balloon device can be used\n");
7289 exit(1);
7291 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
7292 vmchannel_device_index++;
7293 balloon_used = 1;
7294 break;
7295 case QEMU_OPTION_vmchannel:
7296 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7297 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7298 exit(1);
7300 pstrcpy(vmchannel_devices[vmchannel_device_index],
7301 sizeof(vmchannel_devices[0]), optarg);
7302 vmchannel_device_index++;
7303 break;
7304 case QEMU_OPTION_serial:
7305 if (serial_device_index >= MAX_SERIAL_PORTS) {
7306 fprintf(stderr, "qemu: too many serial ports\n");
7307 exit(1);
7309 pstrcpy(serial_devices[serial_device_index],
7310 sizeof(serial_devices[0]), optarg);
7311 serial_device_index++;
7312 break;
7313 case QEMU_OPTION_parallel:
7314 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7315 fprintf(stderr, "qemu: too many parallel ports\n");
7316 exit(1);
7318 pstrcpy(parallel_devices[parallel_device_index],
7319 sizeof(parallel_devices[0]), optarg);
7320 parallel_device_index++;
7321 break;
7322 case QEMU_OPTION_loadvm:
7323 loadvm = optarg;
7324 break;
7325 case QEMU_OPTION_incoming:
7326 incoming = optarg;
7327 break;
7328 case QEMU_OPTION_full_screen:
7329 full_screen = 1;
7330 break;
7331 #ifdef CONFIG_SDL
7332 case QEMU_OPTION_no_quit:
7333 no_quit = 1;
7334 break;
7335 #endif
7336 case QEMU_OPTION_pidfile:
7337 create_pidfile(optarg);
7338 break;
7339 #ifdef TARGET_I386
7340 case QEMU_OPTION_win2k_hack:
7341 win2k_install_hack = 1;
7342 break;
7343 #endif
7344 #ifdef USE_KQEMU
7345 case QEMU_OPTION_no_kqemu:
7346 kqemu_allowed = 0;
7347 break;
7348 case QEMU_OPTION_kernel_kqemu:
7349 kqemu_allowed = 2;
7350 break;
7351 #endif
7352 #ifdef USE_KVM
7353 case QEMU_OPTION_no_kvm:
7354 kvm_allowed = 0;
7355 break;
7356 case QEMU_OPTION_no_kvm_irqchip:
7357 kvm_irqchip = 0;
7358 break;
7359 #endif
7360 case QEMU_OPTION_usb:
7361 usb_enabled = 1;
7362 break;
7363 case QEMU_OPTION_usbdevice:
7364 usb_enabled = 1;
7365 if (usb_devices_index >= MAX_USB_CMDLINE) {
7366 fprintf(stderr, "Too many USB devices\n");
7367 exit(1);
7369 pstrcpy(usb_devices[usb_devices_index],
7370 sizeof(usb_devices[usb_devices_index]),
7371 optarg);
7372 usb_devices_index++;
7373 break;
7374 case QEMU_OPTION_smp:
7375 smp_cpus = atoi(optarg);
7376 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7377 fprintf(stderr, "Invalid number of CPUs\n");
7378 exit(1);
7380 break;
7381 case QEMU_OPTION_vnc:
7382 vnc_display = optarg;
7383 break;
7384 case QEMU_OPTION_no_acpi:
7385 acpi_enabled = 0;
7386 break;
7387 case QEMU_OPTION_no_reboot:
7388 no_reboot = 1;
7389 break;
7390 case QEMU_OPTION_daemonize:
7391 daemonize = 1;
7392 break;
7393 case QEMU_OPTION_option_rom:
7394 if (nb_option_roms >= MAX_OPTION_ROMS) {
7395 fprintf(stderr, "Too many option ROMs\n");
7396 exit(1);
7398 option_rom[nb_option_roms] = optarg;
7399 nb_option_roms++;
7400 break;
7401 case QEMU_OPTION_semihosting:
7402 semihosting_enabled = 1;
7403 break;
7404 case QEMU_OPTION_tdf:
7405 time_drift_fix = 1;
7406 #if defined(__linux__)
7407 case QEMU_OPTION_no_rtc:
7408 use_rtc = 0;
7409 break;
7410 #endif
7411 case QEMU_OPTION_cpu_vendor:
7412 cpu_vendor_string = optarg;
7413 break;
7418 #ifndef _WIN32
7419 if (daemonize) {
7420 pid_t pid;
7422 if (pipe(fds) == -1)
7423 exit(1);
7425 pid = fork();
7426 if (pid > 0) {
7427 uint8_t status;
7428 ssize_t len;
7430 close(fds[1]);
7432 again:
7433 len = read(fds[0], &status, 1);
7434 if (len == -1 && (errno == EINTR))
7435 goto again;
7437 if (len != 1 || status != 0)
7438 exit(1);
7439 else
7440 exit(0);
7441 } else if (pid < 0)
7442 exit(1);
7444 setsid();
7446 pid = fork();
7447 if (pid > 0)
7448 exit(0);
7449 else if (pid < 0)
7450 exit(1);
7452 umask(027);
7454 signal(SIGTSTP, SIG_IGN);
7455 signal(SIGTTOU, SIG_IGN);
7456 signal(SIGTTIN, SIG_IGN);
7458 #endif
7460 #if USE_KVM
7461 if (kvm_allowed) {
7462 if (kvm_qemu_init() < 0) {
7463 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
7464 kvm_allowed = 0;
7467 #endif
7469 #ifdef USE_KQEMU
7470 if (smp_cpus > 1)
7471 kqemu_allowed = 0;
7472 #endif
7473 linux_boot = (kernel_filename != NULL);
7475 if (!linux_boot &&
7476 hd_filename[0] == '\0' &&
7477 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7478 fd_filename[0] == '\0')
7479 help();
7481 /* boot to floppy or the default cd if no hard disk defined yet */
7482 if (hd_filename[0] == '\0' && boot_device == 'c') {
7483 if (fd_filename[0] != '\0')
7484 boot_device = 'a';
7485 else
7486 boot_device = 'd';
7489 setvbuf(stdout, NULL, _IOLBF, 0);
7491 init_timers();
7492 init_timer_alarm();
7493 qemu_aio_init();
7495 #ifdef _WIN32
7496 socket_init();
7497 #endif
7499 /* init network clients */
7500 if (nb_net_clients == 0) {
7501 /* if no clients, we use a default config */
7502 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7503 "nic");
7504 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7505 "user");
7506 nb_net_clients = 2;
7509 for(i = 0;i < nb_net_clients; i++) {
7510 if (net_client_init(net_clients[i]) < 0)
7511 exit(1);
7514 #ifdef TARGET_I386
7515 if (boot_device == 'n') {
7516 for (i = 0; i < nb_nics; i++) {
7517 const char *model = nd_table[i].model;
7518 char buf[1024];
7519 if (model == NULL)
7520 model = "ne2k_pci";
7521 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7522 if (get_image_size(buf) > 0) {
7523 option_rom[nb_option_roms] = strdup(buf);
7524 nb_option_roms++;
7525 break;
7528 if (i == nb_nics) {
7529 fprintf(stderr, "No valid PXE rom found for network device\n");
7530 exit(1);
7532 boot_device = 'c'; /* to prevent confusion by the BIOS */
7534 #endif
7536 /* init the memory */
7537 phys_ram_size = ram_size + vga_ram_size + bios_size;
7540 for (i = 0; i < nb_option_roms; i++) {
7541 int ret = get_image_size(option_rom[i]);
7542 if (ret == -1) {
7543 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7544 exit(1);
7546 phys_ram_size += ret;
7549 #if USE_KVM
7550 /* Initialize kvm */
7551 if (kvm_allowed) {
7552 phys_ram_size += KVM_EXTRA_PAGES * 4096;
7553 if (kvm_qemu_create_context() < 0) {
7554 fprintf(stderr, "Could not create KVM context\n");
7555 exit(1);
7557 } else {
7558 phys_ram_base = qemu_vmalloc(phys_ram_size);
7559 if (!phys_ram_base) {
7560 fprintf(stderr, "Could not allocate physical memory\n");
7561 exit(1);
7564 #else
7565 phys_ram_base = qemu_vmalloc(phys_ram_size);
7566 if (!phys_ram_base) {
7567 fprintf(stderr, "Could not allocate physical memory\n");
7568 exit(1);
7570 #endif
7572 /* we always create the cdrom drive, even if no disk is there */
7573 bdrv_init();
7574 if (cdrom_index >= 0) {
7575 bs_table[cdrom_index] = bdrv_new("cdrom");
7576 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7579 /* open the virtual block devices */
7580 for(i = 0; i < MAX_DISKS; i++) {
7581 if (hd_filename[i]) {
7582 if (!bs_table[i]) {
7583 char buf[64];
7584 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7585 bs_table[i] = bdrv_new(buf);
7587 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7588 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7589 hd_filename[i]);
7590 exit(1);
7592 if (i == 0 && cyls != 0) {
7593 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7594 bdrv_set_translation_hint(bs_table[i], translation);
7599 /* we always create at least one floppy disk */
7600 fd_table[0] = bdrv_new("fda");
7601 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7603 for(i = 0; i < MAX_FD; i++) {
7604 if (fd_filename[i]) {
7605 if (!fd_table[i]) {
7606 char buf[64];
7607 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7608 fd_table[i] = bdrv_new(buf);
7609 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7611 if (fd_filename[i] != '\0') {
7612 if (bdrv_open(fd_table[i], fd_filename[i],
7613 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7614 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7615 fd_filename[i]);
7616 exit(1);
7622 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7623 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
7625 init_ioports();
7627 /* terminal init */
7628 if (nographic) {
7629 dumb_display_init(ds);
7630 } else if (vnc_display != NULL) {
7631 vnc_display_init(ds, vnc_display);
7632 } else {
7633 #if defined(CONFIG_SDL)
7634 sdl_display_init(ds, full_screen);
7635 #elif defined(CONFIG_COCOA)
7636 cocoa_display_init(ds, full_screen);
7637 #else
7638 dumb_display_init(ds);
7639 #endif
7642 monitor_hd = qemu_chr_open(monitor_device);
7643 if (!monitor_hd) {
7644 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7645 exit(1);
7647 monitor_init(monitor_hd, !nographic);
7649 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
7650 const char *devname = vmchannel_devices[i];
7651 if (devname[0] != '\0' && strcmp(devname, "none")) {
7652 int devid;
7653 char *termn;
7655 if (strstart(devname, "di:", &devname)) {
7656 devid = strtol(devname, &termn, 16);
7657 devname = termn + 1;
7659 else {
7660 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
7661 devname);
7662 exit(1);
7664 vmchannel_hds[i] = qemu_chr_open(devname);
7665 if (!vmchannel_hds[i]) {
7666 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
7667 devname);
7668 exit(1);
7670 vmchannel_init(vmchannel_hds[i], devid, i);
7674 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7675 const char *devname = serial_devices[i];
7676 if (devname[0] != '\0' && strcmp(devname, "none")) {
7677 serial_hds[i] = qemu_chr_open(devname);
7678 if (!serial_hds[i]) {
7679 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7680 devname);
7681 exit(1);
7683 if (!strcmp(devname, "vc"))
7684 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7688 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7689 const char *devname = parallel_devices[i];
7690 if (devname[0] != '\0' && strcmp(devname, "none")) {
7691 parallel_hds[i] = qemu_chr_open(devname);
7692 if (!parallel_hds[i]) {
7693 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7694 devname);
7695 exit(1);
7697 if (!strcmp(devname, "vc"))
7698 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7702 machine->init(ram_size, vga_ram_size, boot_device,
7703 ds, fd_filename, snapshot,
7704 kernel_filename, kernel_cmdline, initrd_filename);
7706 /* init USB devices */
7707 if (usb_enabled) {
7708 for(i = 0; i < usb_devices_index; i++) {
7709 if (usb_device_add(usb_devices[i]) < 0) {
7710 fprintf(stderr, "Warning: could not add USB device %s\n",
7711 usb_devices[i]);
7716 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7717 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7719 #ifdef USE_KVM
7720 if (kvm_allowed)
7721 kvm_init_ap();
7722 #endif
7724 #ifdef CONFIG_GDBSTUB
7725 if (use_gdbstub) {
7726 /* XXX: use standard host:port notation and modify options
7727 accordingly. */
7728 if (gdbserver_start_port(gdbstub_port) < 0) {
7729 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7730 gdbstub_port);
7731 exit(1);
7733 } else
7734 #endif
7735 if (loadvm) {
7736 do_loadvm(loadvm);
7739 if (incoming) {
7740 int rc;
7742 rc = migrate_incoming(incoming);
7743 if (rc != 0) {
7744 fprintf(stderr, "Migration failed rc=%d\n", rc);
7745 exit(rc);
7750 /* XXX: simplify init */
7751 read_passwords();
7752 if (autostart) {
7753 vm_start();
7757 if (daemonize) {
7758 uint8_t status = 0;
7759 ssize_t len;
7760 int fd;
7762 again1:
7763 len = write(fds[1], &status, 1);
7764 if (len == -1 && (errno == EINTR))
7765 goto again1;
7767 if (len != 1)
7768 exit(1);
7770 chdir("/");
7771 fd = open("/dev/null", O_RDWR);
7772 if (fd == -1)
7773 exit(1);
7775 dup2(fd, 0);
7776 dup2(fd, 1);
7777 dup2(fd, 2);
7779 close(fd);
7782 main_loop();
7783 quit_timers();
7784 return 0;