kvm: libkvm: fix some warnings
[qemu-kvm/fedora.git] / vl.c
blobc970dd6a807414d908d3b690c2f11082258b65f8
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 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
107 #ifdef TARGET_PPC
108 #define DEFAULT_RAM_SIZE 144
109 #else
110 #define DEFAULT_RAM_SIZE 128
111 #endif
112 /* in ms */
113 #define GUI_REFRESH_INTERVAL 30
115 /* Max number of USB devices that can be specified on the commandline. */
116 #define MAX_USB_CMDLINE 8
118 /* XXX: use a two level table to limit memory usage */
119 #define MAX_IOPORTS 65536
121 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
122 char phys_ram_file[1024];
123 void *ioport_opaque[MAX_IOPORTS];
124 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
125 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
126 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
127 to store the VM snapshots */
128 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
129 /* point to the block driver where the snapshots are managed */
130 BlockDriverState *bs_snapshots;
131 int vga_ram_size;
132 int bios_size;
133 static DisplayState display_state;
134 int nographic;
135 const char* keyboard_layout = NULL;
136 int64_t ticks_per_sec;
137 int boot_device = 'c';
138 int ram_size;
139 int pit_min_timer_count = 0;
140 int nb_nics;
141 NICInfo nd_table[MAX_NICS];
142 QEMUTimer *gui_timer;
143 int vm_running;
144 int rtc_utc = 1;
145 int cirrus_vga_enabled = 1;
146 #ifdef TARGET_SPARC
147 int graphic_width = 1024;
148 int graphic_height = 768;
149 #else
150 int graphic_width = 800;
151 int graphic_height = 600;
152 #endif
153 int graphic_depth = 15;
154 int full_screen = 0;
155 int no_quit = 0;
156 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
157 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
158 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
159 #ifdef TARGET_I386
160 int win2k_install_hack = 0;
161 #endif
162 int usb_enabled = 0;
163 static VLANState *first_vlan;
164 int smp_cpus = 1;
165 const char *vnc_display;
166 #if defined(TARGET_SPARC)
167 #define MAX_CPUS 16
168 #elif defined(TARGET_I386)
169 #define MAX_CPUS 255
170 #else
171 #define MAX_CPUS 1
172 #endif
173 int acpi_enabled = 1;
174 int fd_bootchk = 1;
175 int no_reboot = 0;
176 int daemonize = 0;
177 const char *incoming;
178 const char *option_rom[MAX_OPTION_ROMS];
179 int nb_option_roms;
180 int semihosting_enabled = 0;
181 int autostart = 1;
183 /***********************************************************/
184 /* x86 ISA bus support */
186 target_phys_addr_t isa_mem_base = 0;
187 PicState2 *isa_pic;
189 uint32_t default_ioport_readb(void *opaque, uint32_t address)
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr, "inb: port=0x%04x\n", address);
193 #endif
194 return 0xff;
197 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
199 #ifdef DEBUG_UNUSED_IOPORT
200 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
201 #endif
204 /* default is to make two byte accesses */
205 uint32_t default_ioport_readw(void *opaque, uint32_t address)
207 uint32_t data;
208 data = ioport_read_table[0][address](ioport_opaque[address], address);
209 address = (address + 1) & (MAX_IOPORTS - 1);
210 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
211 return data;
214 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
216 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
217 address = (address + 1) & (MAX_IOPORTS - 1);
218 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
221 uint32_t default_ioport_readl(void *opaque, uint32_t address)
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr, "inl: port=0x%04x\n", address);
225 #endif
226 return 0xffffffff;
229 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
231 #ifdef DEBUG_UNUSED_IOPORT
232 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
233 #endif
236 void init_ioports(void)
238 int i;
240 for(i = 0; i < MAX_IOPORTS; i++) {
241 ioport_read_table[0][i] = default_ioport_readb;
242 ioport_write_table[0][i] = default_ioport_writeb;
243 ioport_read_table[1][i] = default_ioport_readw;
244 ioport_write_table[1][i] = default_ioport_writew;
245 ioport_read_table[2][i] = default_ioport_readl;
246 ioport_write_table[2][i] = default_ioport_writel;
250 /* size is the word size in byte */
251 int register_ioport_read(int start, int length, int size,
252 IOPortReadFunc *func, void *opaque)
254 int i, bsize;
256 if (size == 1) {
257 bsize = 0;
258 } else if (size == 2) {
259 bsize = 1;
260 } else if (size == 4) {
261 bsize = 2;
262 } else {
263 hw_error("register_ioport_read: invalid size");
264 return -1;
266 for(i = start; i < start + length; i += size) {
267 ioport_read_table[bsize][i] = func;
268 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
269 hw_error("register_ioport_read: invalid opaque");
270 ioport_opaque[i] = opaque;
272 return 0;
275 /* size is the word size in byte */
276 int register_ioport_write(int start, int length, int size,
277 IOPortWriteFunc *func, void *opaque)
279 int i, bsize;
281 if (size == 1) {
282 bsize = 0;
283 } else if (size == 2) {
284 bsize = 1;
285 } else if (size == 4) {
286 bsize = 2;
287 } else {
288 hw_error("register_ioport_write: invalid size");
289 return -1;
291 for(i = start; i < start + length; i += size) {
292 ioport_write_table[bsize][i] = func;
293 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
294 hw_error("register_ioport_write: invalid opaque");
295 ioport_opaque[i] = opaque;
297 return 0;
300 void isa_unassign_ioport(int start, int length)
302 int i;
304 for(i = start; i < start + length; i++) {
305 ioport_read_table[0][i] = default_ioport_readb;
306 ioport_read_table[1][i] = default_ioport_readw;
307 ioport_read_table[2][i] = default_ioport_readl;
309 ioport_write_table[0][i] = default_ioport_writeb;
310 ioport_write_table[1][i] = default_ioport_writew;
311 ioport_write_table[2][i] = default_ioport_writel;
315 /***********************************************************/
317 void cpu_outb(CPUState *env, int addr, int val)
319 #ifdef DEBUG_IOPORT
320 if (loglevel & CPU_LOG_IOPORT)
321 fprintf(logfile, "outb: %04x %02x\n", addr, val);
322 #endif
323 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
324 #ifdef USE_KQEMU
325 if (env)
326 env->last_io_time = cpu_get_time_fast();
327 #endif
330 void cpu_outw(CPUState *env, int addr, int val)
332 #ifdef DEBUG_IOPORT
333 if (loglevel & CPU_LOG_IOPORT)
334 fprintf(logfile, "outw: %04x %04x\n", addr, val);
335 #endif
336 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
337 #ifdef USE_KQEMU
338 if (env)
339 env->last_io_time = cpu_get_time_fast();
340 #endif
343 void cpu_outl(CPUState *env, int addr, int val)
345 #ifdef DEBUG_IOPORT
346 if (loglevel & CPU_LOG_IOPORT)
347 fprintf(logfile, "outl: %04x %08x\n", addr, val);
348 #endif
349 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
350 #ifdef USE_KQEMU
351 if (env)
352 env->last_io_time = cpu_get_time_fast();
353 #endif
356 int cpu_inb(CPUState *env, int addr)
358 int val;
359 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
360 #ifdef DEBUG_IOPORT
361 if (loglevel & CPU_LOG_IOPORT)
362 fprintf(logfile, "inb : %04x %02x\n", addr, val);
363 #endif
364 #ifdef USE_KQEMU
365 if (env)
366 env->last_io_time = cpu_get_time_fast();
367 #endif
368 return val;
371 int cpu_inw(CPUState *env, int addr)
373 int val;
374 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
375 #ifdef DEBUG_IOPORT
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "inw : %04x %04x\n", addr, val);
378 #endif
379 #ifdef USE_KQEMU
380 if (env)
381 env->last_io_time = cpu_get_time_fast();
382 #endif
383 return val;
386 int cpu_inl(CPUState *env, int addr)
388 int val;
389 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
390 #ifdef DEBUG_IOPORT
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "inl : %04x %08x\n", addr, val);
393 #endif
394 #ifdef USE_KQEMU
395 if (env)
396 env->last_io_time = cpu_get_time_fast();
397 #endif
398 return val;
401 /***********************************************************/
402 void hw_error(const char *fmt, ...)
404 va_list ap;
405 CPUState *env;
407 va_start(ap, fmt);
408 fprintf(stderr, "qemu: hardware error: ");
409 vfprintf(stderr, fmt, ap);
410 fprintf(stderr, "\n");
411 for(env = first_cpu; env != NULL; env = env->next_cpu) {
412 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
413 #ifdef TARGET_I386
414 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
415 #else
416 cpu_dump_state(env, stderr, fprintf, 0);
417 #endif
419 va_end(ap);
420 abort();
423 /***********************************************************/
424 /* keyboard/mouse */
426 static QEMUPutKBDEvent *qemu_put_kbd_event;
427 static void *qemu_put_kbd_event_opaque;
428 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
429 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
431 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
433 qemu_put_kbd_event_opaque = opaque;
434 qemu_put_kbd_event = func;
437 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
438 void *opaque, int absolute,
439 const char *name)
441 QEMUPutMouseEntry *s, *cursor;
443 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
444 if (!s)
445 return NULL;
447 s->qemu_put_mouse_event = func;
448 s->qemu_put_mouse_event_opaque = opaque;
449 s->qemu_put_mouse_event_absolute = absolute;
450 s->qemu_put_mouse_event_name = qemu_strdup(name);
451 s->next = NULL;
453 if (!qemu_put_mouse_event_head) {
454 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
455 return s;
458 cursor = qemu_put_mouse_event_head;
459 while (cursor->next != NULL)
460 cursor = cursor->next;
462 cursor->next = s;
463 qemu_put_mouse_event_current = s;
465 return s;
468 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
470 QEMUPutMouseEntry *prev = NULL, *cursor;
472 if (!qemu_put_mouse_event_head || entry == NULL)
473 return;
475 cursor = qemu_put_mouse_event_head;
476 while (cursor != NULL && cursor != entry) {
477 prev = cursor;
478 cursor = cursor->next;
481 if (cursor == NULL) // does not exist or list empty
482 return;
483 else if (prev == NULL) { // entry is head
484 qemu_put_mouse_event_head = cursor->next;
485 if (qemu_put_mouse_event_current == entry)
486 qemu_put_mouse_event_current = cursor->next;
487 qemu_free(entry->qemu_put_mouse_event_name);
488 qemu_free(entry);
489 return;
492 prev->next = entry->next;
494 if (qemu_put_mouse_event_current == entry)
495 qemu_put_mouse_event_current = prev;
497 qemu_free(entry->qemu_put_mouse_event_name);
498 qemu_free(entry);
501 void kbd_put_keycode(int keycode)
503 if (qemu_put_kbd_event) {
504 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
508 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
510 QEMUPutMouseEvent *mouse_event;
511 void *mouse_event_opaque;
513 if (!qemu_put_mouse_event_current) {
514 return;
517 mouse_event =
518 qemu_put_mouse_event_current->qemu_put_mouse_event;
519 mouse_event_opaque =
520 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
522 if (mouse_event) {
523 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
527 int kbd_mouse_is_absolute(void)
529 if (!qemu_put_mouse_event_current)
530 return 0;
532 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
535 void do_info_mice(void)
537 QEMUPutMouseEntry *cursor;
538 int index = 0;
540 if (!qemu_put_mouse_event_head) {
541 term_printf("No mouse devices connected\n");
542 return;
545 term_printf("Mouse devices available:\n");
546 cursor = qemu_put_mouse_event_head;
547 while (cursor != NULL) {
548 term_printf("%c Mouse #%d: %s\n",
549 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
550 index, cursor->qemu_put_mouse_event_name);
551 index++;
552 cursor = cursor->next;
556 void do_mouse_set(int index)
558 QEMUPutMouseEntry *cursor;
559 int i = 0;
561 if (!qemu_put_mouse_event_head) {
562 term_printf("No mouse devices connected\n");
563 return;
566 cursor = qemu_put_mouse_event_head;
567 while (cursor != NULL && index != i) {
568 i++;
569 cursor = cursor->next;
572 if (cursor != NULL)
573 qemu_put_mouse_event_current = cursor;
574 else
575 term_printf("Mouse at given index not found\n");
578 /* compute with 96 bit intermediate result: (a*b)/c */
579 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
581 union {
582 uint64_t ll;
583 struct {
584 #ifdef WORDS_BIGENDIAN
585 uint32_t high, low;
586 #else
587 uint32_t low, high;
588 #endif
589 } l;
590 } u, res;
591 uint64_t rl, rh;
593 u.ll = a;
594 rl = (uint64_t)u.l.low * (uint64_t)b;
595 rh = (uint64_t)u.l.high * (uint64_t)b;
596 rh += (rl >> 32);
597 res.l.high = rh / c;
598 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
599 return res.ll;
602 /***********************************************************/
603 /* real time host monotonic timer */
605 #define QEMU_TIMER_BASE 1000000000LL
607 #ifdef WIN32
609 static int64_t clock_freq;
611 static void init_get_clock(void)
613 LARGE_INTEGER freq;
614 int ret;
615 ret = QueryPerformanceFrequency(&freq);
616 if (ret == 0) {
617 fprintf(stderr, "Could not calibrate ticks\n");
618 exit(1);
620 clock_freq = freq.QuadPart;
623 static int64_t get_clock(void)
625 LARGE_INTEGER ti;
626 QueryPerformanceCounter(&ti);
627 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
630 #else
632 static int use_rt_clock;
634 static void init_get_clock(void)
636 use_rt_clock = 0;
637 #if defined(__linux__)
639 struct timespec ts;
640 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
641 use_rt_clock = 1;
644 #endif
647 static int64_t get_clock(void)
649 #if defined(__linux__)
650 if (use_rt_clock) {
651 struct timespec ts;
652 clock_gettime(CLOCK_MONOTONIC, &ts);
653 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
654 } else
655 #endif
657 /* XXX: using gettimeofday leads to problems if the date
658 changes, so it should be avoided. */
659 struct timeval tv;
660 gettimeofday(&tv, NULL);
661 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
665 #endif
667 /***********************************************************/
668 /* guest cycle counter */
670 static int64_t cpu_ticks_prev;
671 static int64_t cpu_ticks_offset;
672 static int64_t cpu_clock_offset;
673 static int cpu_ticks_enabled;
675 /* return the host CPU cycle counter and handle stop/restart */
676 int64_t cpu_get_ticks(void)
678 if (!cpu_ticks_enabled) {
679 return cpu_ticks_offset;
680 } else {
681 int64_t ticks;
682 ticks = cpu_get_real_ticks();
683 if (cpu_ticks_prev > ticks) {
684 /* Note: non increasing ticks may happen if the host uses
685 software suspend */
686 cpu_ticks_offset += cpu_ticks_prev - ticks;
688 cpu_ticks_prev = ticks;
689 return ticks + cpu_ticks_offset;
693 /* return the host CPU monotonic timer and handle stop/restart */
694 static int64_t cpu_get_clock(void)
696 int64_t ti;
697 if (!cpu_ticks_enabled) {
698 return cpu_clock_offset;
699 } else {
700 ti = get_clock();
701 return ti + cpu_clock_offset;
705 /* enable cpu_get_ticks() */
706 void cpu_enable_ticks(void)
708 if (!cpu_ticks_enabled) {
709 cpu_ticks_offset -= cpu_get_real_ticks();
710 cpu_clock_offset -= get_clock();
711 cpu_ticks_enabled = 1;
715 /* disable cpu_get_ticks() : the clock is stopped. You must not call
716 cpu_get_ticks() after that. */
717 void cpu_disable_ticks(void)
719 if (cpu_ticks_enabled) {
720 cpu_ticks_offset = cpu_get_ticks();
721 cpu_clock_offset = cpu_get_clock();
722 cpu_ticks_enabled = 0;
726 /***********************************************************/
727 /* timers */
729 #define QEMU_TIMER_REALTIME 0
730 #define QEMU_TIMER_VIRTUAL 1
732 struct QEMUClock {
733 int type;
734 /* XXX: add frequency */
737 struct QEMUTimer {
738 QEMUClock *clock;
739 int64_t expire_time;
740 QEMUTimerCB *cb;
741 void *opaque;
742 struct QEMUTimer *next;
745 QEMUClock *rt_clock;
746 QEMUClock *vm_clock;
748 static QEMUTimer *active_timers[2];
749 #ifdef _WIN32
750 static MMRESULT timerID;
751 static HANDLE host_alarm = NULL;
752 static unsigned int period = 1;
753 #else
754 /* frequency of the times() clock tick */
755 static int timer_freq;
756 #endif
758 QEMUClock *qemu_new_clock(int type)
760 QEMUClock *clock;
761 clock = qemu_mallocz(sizeof(QEMUClock));
762 if (!clock)
763 return NULL;
764 clock->type = type;
765 return clock;
768 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
770 QEMUTimer *ts;
772 ts = qemu_mallocz(sizeof(QEMUTimer));
773 ts->clock = clock;
774 ts->cb = cb;
775 ts->opaque = opaque;
776 return ts;
779 void qemu_free_timer(QEMUTimer *ts)
781 qemu_free(ts);
784 /* stop a timer, but do not dealloc it */
785 void qemu_del_timer(QEMUTimer *ts)
787 QEMUTimer **pt, *t;
789 /* NOTE: this code must be signal safe because
790 qemu_timer_expired() can be called from a signal. */
791 pt = &active_timers[ts->clock->type];
792 for(;;) {
793 t = *pt;
794 if (!t)
795 break;
796 if (t == ts) {
797 *pt = t->next;
798 break;
800 pt = &t->next;
804 /* modify the current timer so that it will be fired when current_time
805 >= expire_time. The corresponding callback will be called. */
806 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
808 QEMUTimer **pt, *t;
810 qemu_del_timer(ts);
812 /* add the timer in the sorted list */
813 /* NOTE: this code must be signal safe because
814 qemu_timer_expired() can be called from a signal. */
815 pt = &active_timers[ts->clock->type];
816 for(;;) {
817 t = *pt;
818 if (!t)
819 break;
820 if (t->expire_time > expire_time)
821 break;
822 pt = &t->next;
824 ts->expire_time = expire_time;
825 ts->next = *pt;
826 *pt = ts;
829 int qemu_timer_pending(QEMUTimer *ts)
831 QEMUTimer *t;
832 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
833 if (t == ts)
834 return 1;
836 return 0;
839 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
841 if (!timer_head)
842 return 0;
843 return (timer_head->expire_time <= current_time);
846 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
848 QEMUTimer *ts;
850 for(;;) {
851 ts = *ptimer_head;
852 if (!ts || ts->expire_time > current_time)
853 break;
854 /* remove timer from the list before calling the callback */
855 *ptimer_head = ts->next;
856 ts->next = NULL;
858 /* run the callback (the timer list can be modified) */
859 ts->cb(ts->opaque);
863 int64_t qemu_get_clock(QEMUClock *clock)
865 switch(clock->type) {
866 case QEMU_TIMER_REALTIME:
867 return get_clock() / 1000000;
868 default:
869 case QEMU_TIMER_VIRTUAL:
870 return cpu_get_clock();
874 static void init_timers(void)
876 init_get_clock();
877 ticks_per_sec = QEMU_TIMER_BASE;
878 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
879 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
882 /* save a timer */
883 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
885 uint64_t expire_time;
887 if (qemu_timer_pending(ts)) {
888 expire_time = ts->expire_time;
889 } else {
890 expire_time = -1;
892 qemu_put_be64(f, expire_time);
895 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
897 uint64_t expire_time;
899 expire_time = qemu_get_be64(f);
900 if (expire_time != -1) {
901 qemu_mod_timer(ts, expire_time);
902 } else {
903 qemu_del_timer(ts);
907 static void timer_save(QEMUFile *f, void *opaque)
909 if (cpu_ticks_enabled) {
910 hw_error("cannot save state if virtual timers are running");
912 qemu_put_be64s(f, &cpu_ticks_offset);
913 qemu_put_be64s(f, &ticks_per_sec);
914 qemu_put_be64s(f, &cpu_clock_offset);
917 static int timer_load(QEMUFile *f, void *opaque, int version_id)
919 if (version_id != 1 && version_id != 2)
920 return -EINVAL;
921 if (cpu_ticks_enabled) {
922 return -EINVAL;
924 qemu_get_be64s(f, &cpu_ticks_offset);
925 qemu_get_be64s(f, &ticks_per_sec);
926 if (version_id == 2) {
927 qemu_get_be64s(f, &cpu_clock_offset);
929 return 0;
932 #ifdef _WIN32
933 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
934 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
935 #else
936 static void host_alarm_handler(int host_signum)
937 #endif
939 #if 0
940 #define DISP_FREQ 1000
942 static int64_t delta_min = INT64_MAX;
943 static int64_t delta_max, delta_cum, last_clock, delta, ti;
944 static int count;
945 ti = qemu_get_clock(vm_clock);
946 if (last_clock != 0) {
947 delta = ti - last_clock;
948 if (delta < delta_min)
949 delta_min = delta;
950 if (delta > delta_max)
951 delta_max = delta;
952 delta_cum += delta;
953 if (++count == DISP_FREQ) {
954 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
955 muldiv64(delta_min, 1000000, ticks_per_sec),
956 muldiv64(delta_max, 1000000, ticks_per_sec),
957 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
958 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
959 count = 0;
960 delta_min = INT64_MAX;
961 delta_max = 0;
962 delta_cum = 0;
965 last_clock = ti;
967 #endif
968 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
969 qemu_get_clock(vm_clock)) ||
970 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
971 qemu_get_clock(rt_clock))) {
972 #ifdef _WIN32
973 SetEvent(host_alarm);
974 #endif
975 CPUState *env = cpu_single_env;
976 if (env) {
977 /* stop the currently executing cpu because a timer occured */
978 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
979 #ifdef USE_KQEMU
980 if (env->kqemu_enabled) {
981 kqemu_cpu_interrupt(env);
983 #endif
988 #ifndef _WIN32
990 #if defined(__linux__)
992 #define RTC_FREQ 1024
994 static int rtc_fd;
996 static int start_rtc_timer(void)
998 rtc_fd = open("/dev/rtc", O_RDONLY);
999 if (rtc_fd < 0)
1000 return -1;
1001 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1002 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1003 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1004 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1005 goto fail;
1007 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1008 fail:
1009 close(rtc_fd);
1010 return -1;
1012 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1013 return 0;
1016 #else
1018 static int start_rtc_timer(void)
1020 return -1;
1023 #endif /* !defined(__linux__) */
1025 #endif /* !defined(_WIN32) */
1027 static void init_timer_alarm(void)
1029 #ifdef _WIN32
1031 int count=0;
1032 TIMECAPS tc;
1034 ZeroMemory(&tc, sizeof(TIMECAPS));
1035 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1036 if (period < tc.wPeriodMin)
1037 period = tc.wPeriodMin;
1038 timeBeginPeriod(period);
1039 timerID = timeSetEvent(1, // interval (ms)
1040 period, // resolution
1041 host_alarm_handler, // function
1042 (DWORD)&count, // user parameter
1043 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1044 if( !timerID ) {
1045 perror("failed timer alarm");
1046 exit(1);
1048 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1049 if (!host_alarm) {
1050 perror("failed CreateEvent");
1051 exit(1);
1053 qemu_add_wait_object(host_alarm, NULL, NULL);
1055 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1056 #else
1058 struct sigaction act;
1059 struct itimerval itv;
1061 /* get times() syscall frequency */
1062 timer_freq = sysconf(_SC_CLK_TCK);
1064 /* timer signal */
1065 sigfillset(&act.sa_mask);
1066 act.sa_flags = 0;
1067 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1068 act.sa_flags |= SA_ONSTACK;
1069 #endif
1070 act.sa_handler = host_alarm_handler;
1071 sigaction(SIGALRM, &act, NULL);
1073 itv.it_interval.tv_sec = 0;
1074 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1075 itv.it_value.tv_sec = 0;
1076 itv.it_value.tv_usec = 10 * 1000;
1077 setitimer(ITIMER_REAL, &itv, NULL);
1078 /* we probe the tick duration of the kernel to inform the user if
1079 the emulated kernel requested a too high timer frequency */
1080 getitimer(ITIMER_REAL, &itv);
1082 #if defined(__linux__)
1083 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1084 have timers with 1 ms resolution. The correct solution will
1085 be to use the POSIX real time timers available in recent
1086 2.6 kernels */
1087 if (itv.it_interval.tv_usec > 1000 || 1) {
1088 /* try to use /dev/rtc to have a faster timer */
1089 if (start_rtc_timer() < 0)
1090 goto use_itimer;
1091 /* disable itimer */
1092 itv.it_interval.tv_sec = 0;
1093 itv.it_interval.tv_usec = 0;
1094 itv.it_value.tv_sec = 0;
1095 itv.it_value.tv_usec = 0;
1096 setitimer(ITIMER_REAL, &itv, NULL);
1098 /* use the RTC */
1099 sigaction(SIGIO, &act, NULL);
1100 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1101 fcntl(rtc_fd, F_SETOWN, getpid());
1102 } else
1103 #endif /* defined(__linux__) */
1105 use_itimer:
1106 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1107 PIT_FREQ) / 1000000;
1110 #endif
1113 void quit_timers(void)
1115 #ifdef _WIN32
1116 timeKillEvent(timerID);
1117 timeEndPeriod(period);
1118 if (host_alarm) {
1119 CloseHandle(host_alarm);
1120 host_alarm = NULL;
1122 #endif
1125 /***********************************************************/
1126 /* character device */
1128 static void qemu_chr_event(CharDriverState *s, int event)
1130 if (!s->chr_event)
1131 return;
1132 s->chr_event(s->handler_opaque, event);
1135 static void qemu_chr_reset_bh(void *opaque)
1137 CharDriverState *s = opaque;
1138 qemu_chr_event(s, CHR_EVENT_RESET);
1139 qemu_bh_delete(s->bh);
1140 s->bh = NULL;
1143 void qemu_chr_reset(CharDriverState *s)
1145 if (s->bh == NULL) {
1146 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1147 qemu_bh_schedule(s->bh);
1151 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1153 return s->chr_write(s, buf, len);
1156 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1158 if (!s->chr_ioctl)
1159 return -ENOTSUP;
1160 return s->chr_ioctl(s, cmd, arg);
1163 int qemu_chr_can_read(CharDriverState *s)
1165 if (!s->chr_can_read)
1166 return 0;
1167 return s->chr_can_read(s->handler_opaque);
1170 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1172 s->chr_read(s->handler_opaque, buf, len);
1176 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1178 char buf[4096];
1179 va_list ap;
1180 va_start(ap, fmt);
1181 vsnprintf(buf, sizeof(buf), fmt, ap);
1182 qemu_chr_write(s, buf, strlen(buf));
1183 va_end(ap);
1186 void qemu_chr_send_event(CharDriverState *s, int event)
1188 if (s->chr_send_event)
1189 s->chr_send_event(s, event);
1192 void qemu_chr_add_handlers(CharDriverState *s,
1193 IOCanRWHandler *fd_can_read,
1194 IOReadHandler *fd_read,
1195 IOEventHandler *fd_event,
1196 void *opaque)
1198 s->chr_can_read = fd_can_read;
1199 s->chr_read = fd_read;
1200 s->chr_event = fd_event;
1201 s->handler_opaque = opaque;
1202 if (s->chr_update_read_handler)
1203 s->chr_update_read_handler(s);
1206 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1208 return len;
1211 static CharDriverState *qemu_chr_open_null(void)
1213 CharDriverState *chr;
1215 chr = qemu_mallocz(sizeof(CharDriverState));
1216 if (!chr)
1217 return NULL;
1218 chr->chr_write = null_chr_write;
1219 return chr;
1222 #ifdef _WIN32
1224 static void socket_cleanup(void)
1226 WSACleanup();
1229 static int socket_init(void)
1231 WSADATA Data;
1232 int ret, err;
1234 ret = WSAStartup(MAKEWORD(2,2), &Data);
1235 if (ret != 0) {
1236 err = WSAGetLastError();
1237 fprintf(stderr, "WSAStartup: %d\n", err);
1238 return -1;
1240 atexit(socket_cleanup);
1241 return 0;
1244 static int send_all(int fd, const uint8_t *buf, int len1)
1246 int ret, len;
1248 len = len1;
1249 while (len > 0) {
1250 ret = send(fd, buf, len, 0);
1251 if (ret < 0) {
1252 int errno;
1253 errno = WSAGetLastError();
1254 if (errno != WSAEWOULDBLOCK) {
1255 return -1;
1257 } else if (ret == 0) {
1258 break;
1259 } else {
1260 buf += ret;
1261 len -= ret;
1264 return len1 - len;
1267 void socket_set_nonblock(int fd)
1269 unsigned long opt = 1;
1270 ioctlsocket(fd, FIONBIO, &opt);
1273 #else
1275 static int unix_write(int fd, const uint8_t *buf, int len1)
1277 int ret, len;
1279 len = len1;
1280 while (len > 0) {
1281 ret = write(fd, buf, len);
1282 if (ret < 0) {
1283 if (errno != EINTR && errno != EAGAIN)
1284 return -1;
1285 } else if (ret == 0) {
1286 break;
1287 } else {
1288 buf += ret;
1289 len -= ret;
1292 return len1 - len;
1295 static inline int send_all(int fd, const uint8_t *buf, int len1)
1297 return unix_write(fd, buf, len1);
1300 void socket_set_nonblock(int fd)
1302 fcntl(fd, F_SETFL, O_NONBLOCK);
1304 #endif /* !_WIN32 */
1306 #ifndef _WIN32
1308 typedef struct {
1309 int fd_in, fd_out;
1310 int max_size;
1311 } FDCharDriver;
1313 #define STDIO_MAX_CLIENTS 2
1315 static int stdio_nb_clients;
1316 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1318 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1320 FDCharDriver *s = chr->opaque;
1321 return unix_write(s->fd_out, buf, len);
1324 static int fd_chr_read_poll(void *opaque)
1326 CharDriverState *chr = opaque;
1327 FDCharDriver *s = chr->opaque;
1329 s->max_size = qemu_chr_can_read(chr);
1330 return s->max_size;
1333 static void fd_chr_read(void *opaque)
1335 CharDriverState *chr = opaque;
1336 FDCharDriver *s = chr->opaque;
1337 int size, len;
1338 uint8_t buf[1024];
1340 len = sizeof(buf);
1341 if (len > s->max_size)
1342 len = s->max_size;
1343 if (len == 0)
1344 return;
1345 size = read(s->fd_in, buf, len);
1346 if (size == 0) {
1347 /* FD has been closed. Remove it from the active list. */
1348 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1349 return;
1351 if (size > 0) {
1352 qemu_chr_read(chr, buf, size);
1356 static void fd_chr_update_read_handler(CharDriverState *chr)
1358 FDCharDriver *s = chr->opaque;
1360 if (s->fd_in >= 0) {
1361 if (nographic && s->fd_in == 0) {
1362 } else {
1363 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1364 fd_chr_read, NULL, chr);
1369 /* open a character device to a unix fd */
1370 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1372 CharDriverState *chr;
1373 FDCharDriver *s;
1375 chr = qemu_mallocz(sizeof(CharDriverState));
1376 if (!chr)
1377 return NULL;
1378 s = qemu_mallocz(sizeof(FDCharDriver));
1379 if (!s) {
1380 free(chr);
1381 return NULL;
1383 s->fd_in = fd_in;
1384 s->fd_out = fd_out;
1385 chr->opaque = s;
1386 chr->chr_write = fd_chr_write;
1387 chr->chr_update_read_handler = fd_chr_update_read_handler;
1389 qemu_chr_reset(chr);
1391 return chr;
1394 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1396 int fd_out;
1398 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1399 if (fd_out < 0)
1400 return NULL;
1401 return qemu_chr_open_fd(-1, fd_out);
1404 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1406 int fd_in, fd_out;
1407 char filename_in[256], filename_out[256];
1409 snprintf(filename_in, 256, "%s.in", filename);
1410 snprintf(filename_out, 256, "%s.out", filename);
1411 fd_in = open(filename_in, O_RDWR | O_BINARY);
1412 fd_out = open(filename_out, O_RDWR | O_BINARY);
1413 if (fd_in < 0 || fd_out < 0) {
1414 if (fd_in >= 0)
1415 close(fd_in);
1416 if (fd_out >= 0)
1417 close(fd_out);
1418 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1419 if (fd_in < 0)
1420 return NULL;
1422 return qemu_chr_open_fd(fd_in, fd_out);
1426 /* for STDIO, we handle the case where several clients use it
1427 (nographic mode) */
1429 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1431 #define TERM_FIFO_MAX_SIZE 1
1433 static int term_got_escape, client_index;
1434 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1435 static int term_fifo_size;
1436 static int term_timestamps;
1437 static int64_t term_timestamps_start;
1439 void term_print_help(void)
1441 printf("\n"
1442 "C-a h print this help\n"
1443 "C-a x exit emulator\n"
1444 "C-a s save disk data back to file (if -snapshot)\n"
1445 "C-a b send break (magic sysrq)\n"
1446 "C-a t toggle console timestamps\n"
1447 "C-a c switch between console and monitor\n"
1448 "C-a C-a send C-a\n"
1452 /* called when a char is received */
1453 static void stdio_received_byte(int ch)
1455 if (term_got_escape) {
1456 term_got_escape = 0;
1457 switch(ch) {
1458 case 'h':
1459 term_print_help();
1460 break;
1461 case 'x':
1462 exit(0);
1463 break;
1464 case 's':
1466 int i;
1467 for (i = 0; i < MAX_DISKS; i++) {
1468 if (bs_table[i])
1469 bdrv_commit(bs_table[i]);
1472 break;
1473 case 'b':
1474 if (client_index < stdio_nb_clients) {
1475 CharDriverState *chr;
1476 FDCharDriver *s;
1478 chr = stdio_clients[client_index];
1479 s = chr->opaque;
1480 qemu_chr_event(chr, CHR_EVENT_BREAK);
1482 break;
1483 case 'c':
1484 client_index++;
1485 if (client_index >= stdio_nb_clients)
1486 client_index = 0;
1487 if (client_index == 0) {
1488 /* send a new line in the monitor to get the prompt */
1489 ch = '\r';
1490 goto send_char;
1492 break;
1493 case 't':
1494 term_timestamps = !term_timestamps;
1495 term_timestamps_start = -1;
1496 break;
1497 case TERM_ESCAPE:
1498 goto send_char;
1500 } else if (ch == TERM_ESCAPE) {
1501 term_got_escape = 1;
1502 } else {
1503 send_char:
1504 if (client_index < stdio_nb_clients) {
1505 uint8_t buf[1];
1506 CharDriverState *chr;
1508 chr = stdio_clients[client_index];
1509 if (qemu_chr_can_read(chr) > 0) {
1510 buf[0] = ch;
1511 qemu_chr_read(chr, buf, 1);
1512 } else if (term_fifo_size == 0) {
1513 term_fifo[term_fifo_size++] = ch;
1519 static int stdio_read_poll(void *opaque)
1521 CharDriverState *chr;
1523 if (client_index < stdio_nb_clients) {
1524 chr = stdio_clients[client_index];
1525 /* try to flush the queue if needed */
1526 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1527 qemu_chr_read(chr, term_fifo, 1);
1528 term_fifo_size = 0;
1530 /* see if we can absorb more chars */
1531 if (term_fifo_size == 0)
1532 return 1;
1533 else
1534 return 0;
1535 } else {
1536 return 1;
1540 static void stdio_read(void *opaque)
1542 int size;
1543 uint8_t buf[1];
1545 size = read(0, buf, 1);
1546 if (size == 0) {
1547 /* stdin has been closed. Remove it from the active list. */
1548 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1549 return;
1551 if (size > 0)
1552 stdio_received_byte(buf[0]);
1555 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1557 FDCharDriver *s = chr->opaque;
1558 if (!term_timestamps) {
1559 return unix_write(s->fd_out, buf, len);
1560 } else {
1561 int i;
1562 char buf1[64];
1564 for(i = 0; i < len; i++) {
1565 unix_write(s->fd_out, buf + i, 1);
1566 if (buf[i] == '\n') {
1567 int64_t ti;
1568 int secs;
1570 ti = get_clock();
1571 if (term_timestamps_start == -1)
1572 term_timestamps_start = ti;
1573 ti -= term_timestamps_start;
1574 secs = ti / 1000000000;
1575 snprintf(buf1, sizeof(buf1),
1576 "[%02d:%02d:%02d.%03d] ",
1577 secs / 3600,
1578 (secs / 60) % 60,
1579 secs % 60,
1580 (int)((ti / 1000000) % 1000));
1581 unix_write(s->fd_out, buf1, strlen(buf1));
1584 return len;
1588 /* init terminal so that we can grab keys */
1589 static struct termios oldtty;
1590 static int old_fd0_flags;
1592 static void term_exit(void)
1594 tcsetattr (0, TCSANOW, &oldtty);
1595 fcntl(0, F_SETFL, old_fd0_flags);
1598 static void term_init(void)
1600 struct termios tty;
1602 tcgetattr (0, &tty);
1603 oldtty = tty;
1604 old_fd0_flags = fcntl(0, F_GETFL);
1606 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1607 |INLCR|IGNCR|ICRNL|IXON);
1608 tty.c_oflag |= OPOST;
1609 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1610 /* if graphical mode, we allow Ctrl-C handling */
1611 if (nographic)
1612 tty.c_lflag &= ~ISIG;
1613 tty.c_cflag &= ~(CSIZE|PARENB);
1614 tty.c_cflag |= CS8;
1615 tty.c_cc[VMIN] = 1;
1616 tty.c_cc[VTIME] = 0;
1618 tcsetattr (0, TCSANOW, &tty);
1620 atexit(term_exit);
1622 fcntl(0, F_SETFL, O_NONBLOCK);
1625 static CharDriverState *qemu_chr_open_stdio(void)
1627 CharDriverState *chr;
1629 if (nographic) {
1630 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1631 return NULL;
1632 chr = qemu_chr_open_fd(0, 1);
1633 chr->chr_write = stdio_write;
1634 if (stdio_nb_clients == 0)
1635 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1636 client_index = stdio_nb_clients;
1637 } else {
1638 if (stdio_nb_clients != 0)
1639 return NULL;
1640 chr = qemu_chr_open_fd(0, 1);
1642 stdio_clients[stdio_nb_clients++] = chr;
1643 if (stdio_nb_clients == 1) {
1644 /* set the terminal in raw mode */
1645 term_init();
1647 return chr;
1650 #if defined(__linux__)
1651 static CharDriverState *qemu_chr_open_pty(void)
1653 struct termios tty;
1654 char slave_name[1024];
1655 int master_fd, slave_fd;
1657 /* Not satisfying */
1658 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1659 return NULL;
1662 /* Disabling local echo and line-buffered output */
1663 tcgetattr (master_fd, &tty);
1664 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1665 tty.c_cc[VMIN] = 1;
1666 tty.c_cc[VTIME] = 0;
1667 tcsetattr (master_fd, TCSAFLUSH, &tty);
1669 fprintf(stderr, "char device redirected to %s\n", slave_name);
1670 return qemu_chr_open_fd(master_fd, master_fd);
1673 static void tty_serial_init(int fd, int speed,
1674 int parity, int data_bits, int stop_bits)
1676 struct termios tty;
1677 speed_t spd;
1679 #if 0
1680 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1681 speed, parity, data_bits, stop_bits);
1682 #endif
1683 tcgetattr (fd, &tty);
1685 switch(speed) {
1686 case 50:
1687 spd = B50;
1688 break;
1689 case 75:
1690 spd = B75;
1691 break;
1692 case 300:
1693 spd = B300;
1694 break;
1695 case 600:
1696 spd = B600;
1697 break;
1698 case 1200:
1699 spd = B1200;
1700 break;
1701 case 2400:
1702 spd = B2400;
1703 break;
1704 case 4800:
1705 spd = B4800;
1706 break;
1707 case 9600:
1708 spd = B9600;
1709 break;
1710 case 19200:
1711 spd = B19200;
1712 break;
1713 case 38400:
1714 spd = B38400;
1715 break;
1716 case 57600:
1717 spd = B57600;
1718 break;
1719 default:
1720 case 115200:
1721 spd = B115200;
1722 break;
1725 cfsetispeed(&tty, spd);
1726 cfsetospeed(&tty, spd);
1728 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1729 |INLCR|IGNCR|ICRNL|IXON);
1730 tty.c_oflag |= OPOST;
1731 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1732 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1733 switch(data_bits) {
1734 default:
1735 case 8:
1736 tty.c_cflag |= CS8;
1737 break;
1738 case 7:
1739 tty.c_cflag |= CS7;
1740 break;
1741 case 6:
1742 tty.c_cflag |= CS6;
1743 break;
1744 case 5:
1745 tty.c_cflag |= CS5;
1746 break;
1748 switch(parity) {
1749 default:
1750 case 'N':
1751 break;
1752 case 'E':
1753 tty.c_cflag |= PARENB;
1754 break;
1755 case 'O':
1756 tty.c_cflag |= PARENB | PARODD;
1757 break;
1759 if (stop_bits == 2)
1760 tty.c_cflag |= CSTOPB;
1762 tcsetattr (fd, TCSANOW, &tty);
1765 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1767 FDCharDriver *s = chr->opaque;
1769 switch(cmd) {
1770 case CHR_IOCTL_SERIAL_SET_PARAMS:
1772 QEMUSerialSetParams *ssp = arg;
1773 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1774 ssp->data_bits, ssp->stop_bits);
1776 break;
1777 case CHR_IOCTL_SERIAL_SET_BREAK:
1779 int enable = *(int *)arg;
1780 if (enable)
1781 tcsendbreak(s->fd_in, 1);
1783 break;
1784 default:
1785 return -ENOTSUP;
1787 return 0;
1790 static CharDriverState *qemu_chr_open_tty(const char *filename)
1792 CharDriverState *chr;
1793 int fd;
1795 fd = open(filename, O_RDWR | O_NONBLOCK);
1796 if (fd < 0)
1797 return NULL;
1798 fcntl(fd, F_SETFL, O_NONBLOCK);
1799 tty_serial_init(fd, 115200, 'N', 8, 1);
1800 chr = qemu_chr_open_fd(fd, fd);
1801 if (!chr)
1802 return NULL;
1803 chr->chr_ioctl = tty_serial_ioctl;
1804 qemu_chr_reset(chr);
1805 return chr;
1808 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1810 int fd = (int)chr->opaque;
1811 uint8_t b;
1813 switch(cmd) {
1814 case CHR_IOCTL_PP_READ_DATA:
1815 if (ioctl(fd, PPRDATA, &b) < 0)
1816 return -ENOTSUP;
1817 *(uint8_t *)arg = b;
1818 break;
1819 case CHR_IOCTL_PP_WRITE_DATA:
1820 b = *(uint8_t *)arg;
1821 if (ioctl(fd, PPWDATA, &b) < 0)
1822 return -ENOTSUP;
1823 break;
1824 case CHR_IOCTL_PP_READ_CONTROL:
1825 if (ioctl(fd, PPRCONTROL, &b) < 0)
1826 return -ENOTSUP;
1827 *(uint8_t *)arg = b;
1828 break;
1829 case CHR_IOCTL_PP_WRITE_CONTROL:
1830 b = *(uint8_t *)arg;
1831 if (ioctl(fd, PPWCONTROL, &b) < 0)
1832 return -ENOTSUP;
1833 break;
1834 case CHR_IOCTL_PP_READ_STATUS:
1835 if (ioctl(fd, PPRSTATUS, &b) < 0)
1836 return -ENOTSUP;
1837 *(uint8_t *)arg = b;
1838 break;
1839 default:
1840 return -ENOTSUP;
1842 return 0;
1845 static CharDriverState *qemu_chr_open_pp(const char *filename)
1847 CharDriverState *chr;
1848 int fd;
1850 fd = open(filename, O_RDWR);
1851 if (fd < 0)
1852 return NULL;
1854 if (ioctl(fd, PPCLAIM) < 0) {
1855 close(fd);
1856 return NULL;
1859 chr = qemu_mallocz(sizeof(CharDriverState));
1860 if (!chr) {
1861 close(fd);
1862 return NULL;
1864 chr->opaque = (void *)fd;
1865 chr->chr_write = null_chr_write;
1866 chr->chr_ioctl = pp_ioctl;
1868 qemu_chr_reset(chr);
1870 return chr;
1873 #else
1874 static CharDriverState *qemu_chr_open_pty(void)
1876 return NULL;
1878 #endif
1880 #endif /* !defined(_WIN32) */
1882 #ifdef _WIN32
1883 typedef struct {
1884 CharDriverState *chr;
1885 int max_size;
1886 HANDLE hcom, hrecv, hsend;
1887 OVERLAPPED orecv, osend;
1888 BOOL fpipe;
1889 DWORD len;
1890 } WinCharState;
1892 #define NSENDBUF 2048
1893 #define NRECVBUF 2048
1894 #define MAXCONNECT 1
1895 #define NTIMEOUT 5000
1897 static int win_chr_poll(void *opaque);
1898 static int win_chr_pipe_poll(void *opaque);
1900 static void win_chr_close2(WinCharState *s)
1902 if (s->hsend) {
1903 CloseHandle(s->hsend);
1904 s->hsend = NULL;
1906 if (s->hrecv) {
1907 CloseHandle(s->hrecv);
1908 s->hrecv = NULL;
1910 if (s->hcom) {
1911 CloseHandle(s->hcom);
1912 s->hcom = NULL;
1914 if (s->fpipe)
1915 qemu_del_polling_cb(win_chr_pipe_poll, s);
1916 else
1917 qemu_del_polling_cb(win_chr_poll, s);
1920 static void win_chr_close(CharDriverState *chr)
1922 WinCharState *s = chr->opaque;
1923 win_chr_close2(s);
1926 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
1928 COMMCONFIG comcfg;
1929 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1930 COMSTAT comstat;
1931 DWORD size;
1932 DWORD err;
1934 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1935 if (!s->hsend) {
1936 fprintf(stderr, "Failed CreateEvent\n");
1937 goto fail;
1939 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1940 if (!s->hrecv) {
1941 fprintf(stderr, "Failed CreateEvent\n");
1942 goto fail;
1945 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1946 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1947 if (s->hcom == INVALID_HANDLE_VALUE) {
1948 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1949 s->hcom = NULL;
1950 goto fail;
1953 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1954 fprintf(stderr, "Failed SetupComm\n");
1955 goto fail;
1958 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1959 size = sizeof(COMMCONFIG);
1960 GetDefaultCommConfig(filename, &comcfg, &size);
1961 comcfg.dcb.DCBlength = sizeof(DCB);
1962 CommConfigDialog(filename, NULL, &comcfg);
1964 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1965 fprintf(stderr, "Failed SetCommState\n");
1966 goto fail;
1969 if (!SetCommMask(s->hcom, EV_ERR)) {
1970 fprintf(stderr, "Failed SetCommMask\n");
1971 goto fail;
1974 cto.ReadIntervalTimeout = MAXDWORD;
1975 if (!SetCommTimeouts(s->hcom, &cto)) {
1976 fprintf(stderr, "Failed SetCommTimeouts\n");
1977 goto fail;
1980 if (!ClearCommError(s->hcom, &err, &comstat)) {
1981 fprintf(stderr, "Failed ClearCommError\n");
1982 goto fail;
1984 s->chr = chr;
1985 qemu_add_polling_cb(win_chr_poll, s);
1986 return 0;
1988 fail:
1989 win_chr_close2(s);
1990 return -1;
1993 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1995 WinCharState *s = chr->opaque;
1996 DWORD len, ret, size, err;
1998 len = len1;
1999 ZeroMemory(&s->osend, sizeof(s->osend));
2000 s->osend.hEvent = s->hsend;
2001 while (len > 0) {
2002 if (s->hsend)
2003 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2004 else
2005 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2006 if (!ret) {
2007 err = GetLastError();
2008 if (err == ERROR_IO_PENDING) {
2009 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2010 if (ret) {
2011 buf += size;
2012 len -= size;
2013 } else {
2014 break;
2016 } else {
2017 break;
2019 } else {
2020 buf += size;
2021 len -= size;
2024 return len1 - len;
2027 static int win_chr_read_poll(WinCharState *s)
2029 s->max_size = qemu_chr_can_read(s->chr);
2030 return s->max_size;
2033 static void win_chr_readfile(WinCharState *s)
2035 int ret, err;
2036 uint8_t buf[1024];
2037 DWORD size;
2039 ZeroMemory(&s->orecv, sizeof(s->orecv));
2040 s->orecv.hEvent = s->hrecv;
2041 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2042 if (!ret) {
2043 err = GetLastError();
2044 if (err == ERROR_IO_PENDING) {
2045 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2049 if (size > 0) {
2050 qemu_chr_read(s->chr, buf, size);
2054 static void win_chr_read(WinCharState *s)
2056 if (s->len > s->max_size)
2057 s->len = s->max_size;
2058 if (s->len == 0)
2059 return;
2061 win_chr_readfile(s);
2064 static int win_chr_poll(void *opaque)
2066 WinCharState *s = opaque;
2067 COMSTAT status;
2068 DWORD comerr;
2070 ClearCommError(s->hcom, &comerr, &status);
2071 if (status.cbInQue > 0) {
2072 s->len = status.cbInQue;
2073 win_chr_read_poll(s);
2074 win_chr_read(s);
2075 return 1;
2077 return 0;
2080 static CharDriverState *qemu_chr_open_win(const char *filename)
2082 CharDriverState *chr;
2083 WinCharState *s;
2085 chr = qemu_mallocz(sizeof(CharDriverState));
2086 if (!chr)
2087 return NULL;
2088 s = qemu_mallocz(sizeof(WinCharState));
2089 if (!s) {
2090 free(chr);
2091 return NULL;
2093 chr->opaque = s;
2094 chr->chr_write = win_chr_write;
2095 chr->chr_close = win_chr_close;
2097 if (win_chr_init(s, chr, filename) < 0) {
2098 free(s);
2099 free(chr);
2100 return NULL;
2102 qemu_chr_reset(chr);
2103 return chr;
2106 static int win_chr_pipe_poll(void *opaque)
2108 WinCharState *s = opaque;
2109 DWORD size;
2111 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2112 if (size > 0) {
2113 s->len = size;
2114 win_chr_read_poll(s);
2115 win_chr_read(s);
2116 return 1;
2118 return 0;
2121 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2123 OVERLAPPED ov;
2124 int ret;
2125 DWORD size;
2126 char openname[256];
2128 s->fpipe = TRUE;
2130 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2131 if (!s->hsend) {
2132 fprintf(stderr, "Failed CreateEvent\n");
2133 goto fail;
2135 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2136 if (!s->hrecv) {
2137 fprintf(stderr, "Failed CreateEvent\n");
2138 goto fail;
2141 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2142 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2143 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2144 PIPE_WAIT,
2145 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2146 if (s->hcom == INVALID_HANDLE_VALUE) {
2147 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2148 s->hcom = NULL;
2149 goto fail;
2152 ZeroMemory(&ov, sizeof(ov));
2153 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2154 ret = ConnectNamedPipe(s->hcom, &ov);
2155 if (ret) {
2156 fprintf(stderr, "Failed ConnectNamedPipe\n");
2157 goto fail;
2160 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2161 if (!ret) {
2162 fprintf(stderr, "Failed GetOverlappedResult\n");
2163 if (ov.hEvent) {
2164 CloseHandle(ov.hEvent);
2165 ov.hEvent = NULL;
2167 goto fail;
2170 if (ov.hEvent) {
2171 CloseHandle(ov.hEvent);
2172 ov.hEvent = NULL;
2174 qemu_add_polling_cb(win_chr_pipe_poll, s);
2175 return 0;
2177 fail:
2178 win_chr_close2(s);
2179 return -1;
2183 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2185 CharDriverState *chr;
2186 WinCharState *s;
2188 chr = qemu_mallocz(sizeof(CharDriverState));
2189 if (!chr)
2190 return NULL;
2191 s = qemu_mallocz(sizeof(WinCharState));
2192 if (!s) {
2193 free(chr);
2194 return NULL;
2196 chr->opaque = s;
2197 chr->chr_write = win_chr_write;
2198 chr->chr_close = win_chr_close;
2200 if (win_chr_pipe_init(s, filename) < 0) {
2201 free(s);
2202 free(chr);
2203 return NULL;
2205 qemu_chr_reset(chr);
2206 return chr;
2209 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2211 CharDriverState *chr;
2212 WinCharState *s;
2214 chr = qemu_mallocz(sizeof(CharDriverState));
2215 if (!chr)
2216 return NULL;
2217 s = qemu_mallocz(sizeof(WinCharState));
2218 if (!s) {
2219 free(chr);
2220 return NULL;
2222 s->hcom = fd_out;
2223 chr->opaque = s;
2224 chr->chr_write = win_chr_write;
2225 qemu_chr_reset(chr);
2226 return chr;
2229 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2231 HANDLE fd_out;
2233 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2234 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2235 if (fd_out == INVALID_HANDLE_VALUE)
2236 return NULL;
2238 return qemu_chr_open_win_file(fd_out);
2240 #endif
2242 /***********************************************************/
2243 /* UDP Net console */
2245 typedef struct {
2246 int fd;
2247 struct sockaddr_in daddr;
2248 char buf[1024];
2249 int bufcnt;
2250 int bufptr;
2251 int max_size;
2252 } NetCharDriver;
2254 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2256 NetCharDriver *s = chr->opaque;
2258 return sendto(s->fd, buf, len, 0,
2259 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2262 static int udp_chr_read_poll(void *opaque)
2264 CharDriverState *chr = opaque;
2265 NetCharDriver *s = chr->opaque;
2267 s->max_size = qemu_chr_can_read(chr);
2269 /* If there were any stray characters in the queue process them
2270 * first
2272 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2273 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2274 s->bufptr++;
2275 s->max_size = qemu_chr_can_read(chr);
2277 return s->max_size;
2280 static void udp_chr_read(void *opaque)
2282 CharDriverState *chr = opaque;
2283 NetCharDriver *s = chr->opaque;
2285 if (s->max_size == 0)
2286 return;
2287 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2288 s->bufptr = s->bufcnt;
2289 if (s->bufcnt <= 0)
2290 return;
2292 s->bufptr = 0;
2293 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2294 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2295 s->bufptr++;
2296 s->max_size = qemu_chr_can_read(chr);
2300 static void udp_chr_update_read_handler(CharDriverState *chr)
2302 NetCharDriver *s = chr->opaque;
2304 if (s->fd >= 0) {
2305 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2306 udp_chr_read, NULL, chr);
2310 #ifndef _WIN32
2311 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2312 #endif
2313 int parse_host_src_port(struct sockaddr_in *haddr,
2314 struct sockaddr_in *saddr,
2315 const char *str);
2317 static CharDriverState *qemu_chr_open_udp(const char *def)
2319 CharDriverState *chr = NULL;
2320 NetCharDriver *s = NULL;
2321 int fd = -1;
2322 struct sockaddr_in saddr;
2324 chr = qemu_mallocz(sizeof(CharDriverState));
2325 if (!chr)
2326 goto return_err;
2327 s = qemu_mallocz(sizeof(NetCharDriver));
2328 if (!s)
2329 goto return_err;
2331 fd = socket(PF_INET, SOCK_DGRAM, 0);
2332 if (fd < 0) {
2333 perror("socket(PF_INET, SOCK_DGRAM)");
2334 goto return_err;
2337 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2338 printf("Could not parse: %s\n", def);
2339 goto return_err;
2342 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2344 perror("bind");
2345 goto return_err;
2348 s->fd = fd;
2349 s->bufcnt = 0;
2350 s->bufptr = 0;
2351 chr->opaque = s;
2352 chr->chr_write = udp_chr_write;
2353 chr->chr_update_read_handler = udp_chr_update_read_handler;
2354 return chr;
2356 return_err:
2357 if (chr)
2358 free(chr);
2359 if (s)
2360 free(s);
2361 if (fd >= 0)
2362 closesocket(fd);
2363 return NULL;
2366 /***********************************************************/
2367 /* TCP Net console */
2369 typedef struct {
2370 int fd, listen_fd;
2371 int connected;
2372 int max_size;
2373 int do_telnetopt;
2374 int do_nodelay;
2375 int is_unix;
2376 } TCPCharDriver;
2378 static void tcp_chr_accept(void *opaque);
2380 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2382 TCPCharDriver *s = chr->opaque;
2383 if (s->connected) {
2384 return send_all(s->fd, buf, len);
2385 } else {
2386 /* XXX: indicate an error ? */
2387 return len;
2391 static int tcp_chr_read_poll(void *opaque)
2393 CharDriverState *chr = opaque;
2394 TCPCharDriver *s = chr->opaque;
2395 if (!s->connected)
2396 return 0;
2397 s->max_size = qemu_chr_can_read(chr);
2398 return s->max_size;
2401 #define IAC 255
2402 #define IAC_BREAK 243
2403 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2404 TCPCharDriver *s,
2405 char *buf, int *size)
2407 /* Handle any telnet client's basic IAC options to satisfy char by
2408 * char mode with no echo. All IAC options will be removed from
2409 * the buf and the do_telnetopt variable will be used to track the
2410 * state of the width of the IAC information.
2412 * IAC commands come in sets of 3 bytes with the exception of the
2413 * "IAC BREAK" command and the double IAC.
2416 int i;
2417 int j = 0;
2419 for (i = 0; i < *size; i++) {
2420 if (s->do_telnetopt > 1) {
2421 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2422 /* Double IAC means send an IAC */
2423 if (j != i)
2424 buf[j] = buf[i];
2425 j++;
2426 s->do_telnetopt = 1;
2427 } else {
2428 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2429 /* Handle IAC break commands by sending a serial break */
2430 qemu_chr_event(chr, CHR_EVENT_BREAK);
2431 s->do_telnetopt++;
2433 s->do_telnetopt++;
2435 if (s->do_telnetopt >= 4) {
2436 s->do_telnetopt = 1;
2438 } else {
2439 if ((unsigned char)buf[i] == IAC) {
2440 s->do_telnetopt = 2;
2441 } else {
2442 if (j != i)
2443 buf[j] = buf[i];
2444 j++;
2448 *size = j;
2451 static void tcp_chr_read(void *opaque)
2453 CharDriverState *chr = opaque;
2454 TCPCharDriver *s = chr->opaque;
2455 uint8_t buf[1024];
2456 int len, size;
2458 if (!s->connected || s->max_size <= 0)
2459 return;
2460 len = sizeof(buf);
2461 if (len > s->max_size)
2462 len = s->max_size;
2463 size = recv(s->fd, buf, len, 0);
2464 if (size == 0) {
2465 /* connection closed */
2466 s->connected = 0;
2467 if (s->listen_fd >= 0) {
2468 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2470 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2471 closesocket(s->fd);
2472 s->fd = -1;
2473 } else if (size > 0) {
2474 if (s->do_telnetopt)
2475 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2476 if (size > 0)
2477 qemu_chr_read(chr, buf, size);
2481 static void tcp_chr_connect(void *opaque)
2483 CharDriverState *chr = opaque;
2484 TCPCharDriver *s = chr->opaque;
2486 s->connected = 1;
2487 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2488 tcp_chr_read, NULL, chr);
2489 qemu_chr_reset(chr);
2492 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2493 static void tcp_chr_telnet_init(int fd)
2495 char buf[3];
2496 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2497 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2498 send(fd, (char *)buf, 3, 0);
2499 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2500 send(fd, (char *)buf, 3, 0);
2501 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2502 send(fd, (char *)buf, 3, 0);
2503 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2504 send(fd, (char *)buf, 3, 0);
2507 static void socket_set_nodelay(int fd)
2509 int val = 1;
2510 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2513 static void tcp_chr_accept(void *opaque)
2515 CharDriverState *chr = opaque;
2516 TCPCharDriver *s = chr->opaque;
2517 struct sockaddr_in saddr;
2518 #ifndef _WIN32
2519 struct sockaddr_un uaddr;
2520 #endif
2521 struct sockaddr *addr;
2522 socklen_t len;
2523 int fd;
2525 for(;;) {
2526 #ifndef _WIN32
2527 if (s->is_unix) {
2528 len = sizeof(uaddr);
2529 addr = (struct sockaddr *)&uaddr;
2530 } else
2531 #endif
2533 len = sizeof(saddr);
2534 addr = (struct sockaddr *)&saddr;
2536 fd = accept(s->listen_fd, addr, &len);
2537 if (fd < 0 && errno != EINTR) {
2538 return;
2539 } else if (fd >= 0) {
2540 if (s->do_telnetopt)
2541 tcp_chr_telnet_init(fd);
2542 break;
2545 socket_set_nonblock(fd);
2546 if (s->do_nodelay)
2547 socket_set_nodelay(fd);
2548 s->fd = fd;
2549 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2550 tcp_chr_connect(chr);
2553 static void tcp_chr_close(CharDriverState *chr)
2555 TCPCharDriver *s = chr->opaque;
2556 if (s->fd >= 0)
2557 closesocket(s->fd);
2558 if (s->listen_fd >= 0)
2559 closesocket(s->listen_fd);
2560 qemu_free(s);
2563 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2564 int is_telnet,
2565 int is_unix)
2567 CharDriverState *chr = NULL;
2568 TCPCharDriver *s = NULL;
2569 int fd = -1, ret, err, val;
2570 int is_listen = 0;
2571 int is_waitconnect = 1;
2572 int do_nodelay = 0;
2573 const char *ptr;
2574 struct sockaddr_in saddr;
2575 #ifndef _WIN32
2576 struct sockaddr_un uaddr;
2577 #endif
2578 struct sockaddr *addr;
2579 socklen_t addrlen;
2581 #ifndef _WIN32
2582 if (is_unix) {
2583 addr = (struct sockaddr *)&uaddr;
2584 addrlen = sizeof(uaddr);
2585 if (parse_unix_path(&uaddr, host_str) < 0)
2586 goto fail;
2587 } else
2588 #endif
2590 addr = (struct sockaddr *)&saddr;
2591 addrlen = sizeof(saddr);
2592 if (parse_host_port(&saddr, host_str) < 0)
2593 goto fail;
2596 ptr = host_str;
2597 while((ptr = strchr(ptr,','))) {
2598 ptr++;
2599 if (!strncmp(ptr,"server",6)) {
2600 is_listen = 1;
2601 } else if (!strncmp(ptr,"nowait",6)) {
2602 is_waitconnect = 0;
2603 } else if (!strncmp(ptr,"nodelay",6)) {
2604 do_nodelay = 1;
2605 } else {
2606 printf("Unknown option: %s\n", ptr);
2607 goto fail;
2610 if (!is_listen)
2611 is_waitconnect = 0;
2613 chr = qemu_mallocz(sizeof(CharDriverState));
2614 if (!chr)
2615 goto fail;
2616 s = qemu_mallocz(sizeof(TCPCharDriver));
2617 if (!s)
2618 goto fail;
2620 #ifndef _WIN32
2621 if (is_unix)
2622 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2623 else
2624 #endif
2625 fd = socket(PF_INET, SOCK_STREAM, 0);
2627 if (fd < 0)
2628 goto fail;
2630 if (!is_waitconnect)
2631 socket_set_nonblock(fd);
2633 s->connected = 0;
2634 s->fd = -1;
2635 s->listen_fd = -1;
2636 s->is_unix = is_unix;
2637 s->do_nodelay = do_nodelay && !is_unix;
2639 chr->opaque = s;
2640 chr->chr_write = tcp_chr_write;
2641 chr->chr_close = tcp_chr_close;
2643 if (is_listen) {
2644 /* allow fast reuse */
2645 #ifndef _WIN32
2646 if (is_unix) {
2647 char path[109];
2648 strncpy(path, uaddr.sun_path, 108);
2649 path[108] = 0;
2650 unlink(path);
2651 } else
2652 #endif
2654 val = 1;
2655 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2658 ret = bind(fd, addr, addrlen);
2659 if (ret < 0)
2660 goto fail;
2662 ret = listen(fd, 0);
2663 if (ret < 0)
2664 goto fail;
2666 s->listen_fd = fd;
2667 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2668 if (is_telnet)
2669 s->do_telnetopt = 1;
2670 } else {
2671 for(;;) {
2672 ret = connect(fd, addr, addrlen);
2673 if (ret < 0) {
2674 err = socket_error();
2675 if (err == EINTR || err == EWOULDBLOCK) {
2676 } else if (err == EINPROGRESS) {
2677 break;
2678 } else {
2679 goto fail;
2681 } else {
2682 s->connected = 1;
2683 break;
2686 s->fd = fd;
2687 socket_set_nodelay(fd);
2688 if (s->connected)
2689 tcp_chr_connect(chr);
2690 else
2691 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2694 if (is_listen && is_waitconnect) {
2695 printf("QEMU waiting for connection on: %s\n", host_str);
2696 tcp_chr_accept(chr);
2697 socket_set_nonblock(s->listen_fd);
2700 return chr;
2701 fail:
2702 if (fd >= 0)
2703 closesocket(fd);
2704 qemu_free(s);
2705 qemu_free(chr);
2706 return NULL;
2709 CharDriverState *qemu_chr_open(const char *filename)
2711 const char *p;
2713 if (!strcmp(filename, "vc")) {
2714 return text_console_init(&display_state);
2715 } else if (!strcmp(filename, "null")) {
2716 return qemu_chr_open_null();
2717 } else
2718 if (strstart(filename, "tcp:", &p)) {
2719 return qemu_chr_open_tcp(p, 0, 0);
2720 } else
2721 if (strstart(filename, "telnet:", &p)) {
2722 return qemu_chr_open_tcp(p, 1, 0);
2723 } else
2724 if (strstart(filename, "udp:", &p)) {
2725 return qemu_chr_open_udp(p);
2726 } else
2727 #ifndef _WIN32
2728 if (strstart(filename, "unix:", &p)) {
2729 return qemu_chr_open_tcp(p, 0, 1);
2730 } else if (strstart(filename, "file:", &p)) {
2731 return qemu_chr_open_file_out(p);
2732 } else if (strstart(filename, "pipe:", &p)) {
2733 return qemu_chr_open_pipe(p);
2734 } else if (!strcmp(filename, "pty")) {
2735 return qemu_chr_open_pty();
2736 } else if (!strcmp(filename, "stdio")) {
2737 return qemu_chr_open_stdio();
2738 } else
2739 #endif
2740 #if defined(__linux__)
2741 if (strstart(filename, "/dev/parport", NULL)) {
2742 return qemu_chr_open_pp(filename);
2743 } else
2744 if (strstart(filename, "/dev/", NULL)) {
2745 return qemu_chr_open_tty(filename);
2746 } else
2747 #endif
2748 #ifdef _WIN32
2749 if (strstart(filename, "COM", NULL)) {
2750 return qemu_chr_open_win(filename);
2751 } else
2752 if (strstart(filename, "pipe:", &p)) {
2753 return qemu_chr_open_win_pipe(p);
2754 } else
2755 if (strstart(filename, "file:", &p)) {
2756 return qemu_chr_open_win_file_out(p);
2758 #endif
2760 return NULL;
2764 void qemu_chr_close(CharDriverState *chr)
2766 if (chr->chr_close)
2767 chr->chr_close(chr);
2770 /***********************************************************/
2771 /* network device redirectors */
2773 void hex_dump(FILE *f, const uint8_t *buf, int size)
2775 int len, i, j, c;
2777 for(i=0;i<size;i+=16) {
2778 len = size - i;
2779 if (len > 16)
2780 len = 16;
2781 fprintf(f, "%08x ", i);
2782 for(j=0;j<16;j++) {
2783 if (j < len)
2784 fprintf(f, " %02x", buf[i+j]);
2785 else
2786 fprintf(f, " ");
2788 fprintf(f, " ");
2789 for(j=0;j<len;j++) {
2790 c = buf[i+j];
2791 if (c < ' ' || c > '~')
2792 c = '.';
2793 fprintf(f, "%c", c);
2795 fprintf(f, "\n");
2799 static int parse_macaddr(uint8_t *macaddr, const char *p)
2801 int i;
2802 for(i = 0; i < 6; i++) {
2803 macaddr[i] = strtol(p, (char **)&p, 16);
2804 if (i == 5) {
2805 if (*p != '\0')
2806 return -1;
2807 } else {
2808 if (*p != ':')
2809 return -1;
2810 p++;
2813 return 0;
2816 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2818 const char *p, *p1;
2819 int len;
2820 p = *pp;
2821 p1 = strchr(p, sep);
2822 if (!p1)
2823 return -1;
2824 len = p1 - p;
2825 p1++;
2826 if (buf_size > 0) {
2827 if (len > buf_size - 1)
2828 len = buf_size - 1;
2829 memcpy(buf, p, len);
2830 buf[len] = '\0';
2832 *pp = p1;
2833 return 0;
2836 int parse_host_src_port(struct sockaddr_in *haddr,
2837 struct sockaddr_in *saddr,
2838 const char *input_str)
2840 char *str = strdup(input_str);
2841 char *host_str = str;
2842 char *src_str;
2843 char *ptr;
2846 * Chop off any extra arguments at the end of the string which
2847 * would start with a comma, then fill in the src port information
2848 * if it was provided else use the "any address" and "any port".
2850 if ((ptr = strchr(str,',')))
2851 *ptr = '\0';
2853 if ((src_str = strchr(input_str,'@'))) {
2854 *src_str = '\0';
2855 src_str++;
2858 if (parse_host_port(haddr, host_str) < 0)
2859 goto fail;
2861 if (!src_str || *src_str == '\0')
2862 src_str = ":0";
2864 if (parse_host_port(saddr, src_str) < 0)
2865 goto fail;
2867 free(str);
2868 return(0);
2870 fail:
2871 free(str);
2872 return -1;
2875 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2877 char buf[512];
2878 struct hostent *he;
2879 const char *p, *r;
2880 int port;
2882 p = str;
2883 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2884 return -1;
2885 saddr->sin_family = AF_INET;
2886 if (buf[0] == '\0') {
2887 saddr->sin_addr.s_addr = 0;
2888 } else {
2889 if (isdigit(buf[0])) {
2890 if (!inet_aton(buf, &saddr->sin_addr))
2891 return -1;
2892 } else {
2893 if ((he = gethostbyname(buf)) == NULL)
2894 return - 1;
2895 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2898 port = strtol(p, (char **)&r, 0);
2899 if (r == p)
2900 return -1;
2901 saddr->sin_port = htons(port);
2902 return 0;
2905 #ifndef _WIN32
2906 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2908 const char *p;
2909 int len;
2911 len = MIN(108, strlen(str));
2912 p = strchr(str, ',');
2913 if (p)
2914 len = MIN(len, p - str);
2916 memset(uaddr, 0, sizeof(*uaddr));
2918 uaddr->sun_family = AF_UNIX;
2919 memcpy(uaddr->sun_path, str, len);
2921 return 0;
2923 #endif
2925 /* find or alloc a new VLAN */
2926 VLANState *qemu_find_vlan(int id)
2928 VLANState **pvlan, *vlan;
2929 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2930 if (vlan->id == id)
2931 return vlan;
2933 vlan = qemu_mallocz(sizeof(VLANState));
2934 if (!vlan)
2935 return NULL;
2936 vlan->id = id;
2937 vlan->next = NULL;
2938 pvlan = &first_vlan;
2939 while (*pvlan != NULL)
2940 pvlan = &(*pvlan)->next;
2941 *pvlan = vlan;
2942 return vlan;
2945 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2946 IOReadHandler *fd_read,
2947 IOCanRWHandler *fd_can_read,
2948 void *opaque)
2950 VLANClientState *vc, **pvc;
2951 vc = qemu_mallocz(sizeof(VLANClientState));
2952 if (!vc)
2953 return NULL;
2954 vc->fd_read = fd_read;
2955 vc->fd_can_read = fd_can_read;
2956 vc->opaque = opaque;
2957 vc->vlan = vlan;
2959 vc->next = NULL;
2960 pvc = &vlan->first_client;
2961 while (*pvc != NULL)
2962 pvc = &(*pvc)->next;
2963 *pvc = vc;
2964 return vc;
2967 int qemu_can_send_packet(VLANClientState *vc1)
2969 VLANState *vlan = vc1->vlan;
2970 VLANClientState *vc;
2972 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2973 if (vc != vc1) {
2974 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2975 return 0;
2978 return 1;
2981 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2983 VLANState *vlan = vc1->vlan;
2984 VLANClientState *vc;
2986 #if 0
2987 printf("vlan %d send:\n", vlan->id);
2988 hex_dump(stdout, buf, size);
2989 #endif
2990 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2991 if (vc != vc1) {
2992 vc->fd_read(vc->opaque, buf, size);
2997 #if defined(CONFIG_SLIRP)
2999 /* slirp network adapter */
3001 static int slirp_inited;
3002 static VLANClientState *slirp_vc;
3004 int slirp_can_output(void)
3006 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3009 void slirp_output(const uint8_t *pkt, int pkt_len)
3011 #if 0
3012 printf("slirp output:\n");
3013 hex_dump(stdout, pkt, pkt_len);
3014 #endif
3015 if (!slirp_vc)
3016 return;
3017 qemu_send_packet(slirp_vc, pkt, pkt_len);
3020 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3022 #if 0
3023 printf("slirp input:\n");
3024 hex_dump(stdout, buf, size);
3025 #endif
3026 slirp_input(buf, size);
3029 static int net_slirp_init(VLANState *vlan)
3031 if (!slirp_inited) {
3032 slirp_inited = 1;
3033 slirp_init();
3035 slirp_vc = qemu_new_vlan_client(vlan,
3036 slirp_receive, NULL, NULL);
3037 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3038 return 0;
3041 static void net_slirp_redir(const char *redir_str)
3043 int is_udp;
3044 char buf[256], *r;
3045 const char *p;
3046 struct in_addr guest_addr;
3047 int host_port, guest_port;
3049 if (!slirp_inited) {
3050 slirp_inited = 1;
3051 slirp_init();
3054 p = redir_str;
3055 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3056 goto fail;
3057 if (!strcmp(buf, "tcp")) {
3058 is_udp = 0;
3059 } else if (!strcmp(buf, "udp")) {
3060 is_udp = 1;
3061 } else {
3062 goto fail;
3065 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3066 goto fail;
3067 host_port = strtol(buf, &r, 0);
3068 if (r == buf)
3069 goto fail;
3071 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3072 goto fail;
3073 if (buf[0] == '\0') {
3074 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3076 if (!inet_aton(buf, &guest_addr))
3077 goto fail;
3079 guest_port = strtol(p, &r, 0);
3080 if (r == p)
3081 goto fail;
3083 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3084 fprintf(stderr, "qemu: could not set up redirection\n");
3085 exit(1);
3087 return;
3088 fail:
3089 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3090 exit(1);
3093 #ifndef _WIN32
3095 char smb_dir[1024];
3097 static void smb_exit(void)
3099 DIR *d;
3100 struct dirent *de;
3101 char filename[1024];
3103 /* erase all the files in the directory */
3104 d = opendir(smb_dir);
3105 for(;;) {
3106 de = readdir(d);
3107 if (!de)
3108 break;
3109 if (strcmp(de->d_name, ".") != 0 &&
3110 strcmp(de->d_name, "..") != 0) {
3111 snprintf(filename, sizeof(filename), "%s/%s",
3112 smb_dir, de->d_name);
3113 unlink(filename);
3116 closedir(d);
3117 rmdir(smb_dir);
3120 /* automatic user mode samba server configuration */
3121 void net_slirp_smb(const char *exported_dir)
3123 char smb_conf[1024];
3124 char smb_cmdline[1024];
3125 FILE *f;
3127 if (!slirp_inited) {
3128 slirp_inited = 1;
3129 slirp_init();
3132 /* XXX: better tmp dir construction */
3133 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3134 if (mkdir(smb_dir, 0700) < 0) {
3135 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3136 exit(1);
3138 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3140 f = fopen(smb_conf, "w");
3141 if (!f) {
3142 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3143 exit(1);
3145 fprintf(f,
3146 "[global]\n"
3147 "private dir=%s\n"
3148 "smb ports=0\n"
3149 "socket address=127.0.0.1\n"
3150 "pid directory=%s\n"
3151 "lock directory=%s\n"
3152 "log file=%s/log.smbd\n"
3153 "smb passwd file=%s/smbpasswd\n"
3154 "security = share\n"
3155 "[qemu]\n"
3156 "path=%s\n"
3157 "read only=no\n"
3158 "guest ok=yes\n",
3159 smb_dir,
3160 smb_dir,
3161 smb_dir,
3162 smb_dir,
3163 smb_dir,
3164 exported_dir
3166 fclose(f);
3167 atexit(smb_exit);
3169 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3170 SMBD_COMMAND, smb_conf);
3172 slirp_add_exec(0, smb_cmdline, 4, 139);
3175 #endif /* !defined(_WIN32) */
3177 #endif /* CONFIG_SLIRP */
3179 #if !defined(_WIN32)
3181 typedef struct TAPState {
3182 VLANClientState *vc;
3183 int fd;
3184 } TAPState;
3186 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3188 TAPState *s = opaque;
3189 int ret;
3190 for(;;) {
3191 ret = write(s->fd, buf, size);
3192 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3193 } else {
3194 break;
3199 static void tap_send(void *opaque)
3201 TAPState *s = opaque;
3202 uint8_t buf[4096];
3203 int size;
3205 size = read(s->fd, buf, sizeof(buf));
3206 if (size > 0) {
3207 qemu_send_packet(s->vc, buf, size);
3211 /* fd support */
3213 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3215 TAPState *s;
3217 s = qemu_mallocz(sizeof(TAPState));
3218 if (!s)
3219 return NULL;
3220 s->fd = fd;
3221 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3222 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3223 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3224 return s;
3227 #ifdef _BSD
3228 static int tap_open(char *ifname, int ifname_size)
3230 int fd;
3231 char *dev;
3232 struct stat s;
3234 fd = open("/dev/tap", O_RDWR);
3235 if (fd < 0) {
3236 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3237 return -1;
3240 fstat(fd, &s);
3241 dev = devname(s.st_rdev, S_IFCHR);
3242 pstrcpy(ifname, ifname_size, dev);
3244 fcntl(fd, F_SETFL, O_NONBLOCK);
3245 return fd;
3247 #elif defined(__sun__)
3248 static int tap_open(char *ifname, int ifname_size)
3250 fprintf(stderr, "warning: tap_open not yet implemented\n");
3251 return -1;
3253 #else
3254 static int tap_open(char *ifname, int ifname_size)
3256 struct ifreq ifr;
3257 int fd, ret;
3259 fd = open("/dev/net/tun", O_RDWR);
3260 if (fd < 0) {
3261 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3262 return -1;
3264 memset(&ifr, 0, sizeof(ifr));
3265 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3266 if (ifname[0] != '\0')
3267 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3268 else
3269 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3270 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3271 if (ret != 0) {
3272 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3273 close(fd);
3274 return -1;
3276 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3277 fcntl(fd, F_SETFL, O_NONBLOCK);
3278 return fd;
3280 #endif
3282 static int net_tap_init(VLANState *vlan, const char *ifname1,
3283 const char *setup_script)
3285 TAPState *s;
3286 int pid, status, fd;
3287 char *args[3];
3288 char **parg;
3289 char ifname[128];
3291 if (ifname1 != NULL)
3292 pstrcpy(ifname, sizeof(ifname), ifname1);
3293 else
3294 ifname[0] = '\0';
3295 fd = tap_open(ifname, sizeof(ifname));
3296 if (fd < 0)
3297 return -1;
3299 if (!setup_script || !strcmp(setup_script, "no"))
3300 setup_script = "";
3301 if (setup_script[0] != '\0') {
3302 /* try to launch network init script */
3303 pid = fork();
3304 if (pid >= 0) {
3305 if (pid == 0) {
3306 parg = args;
3307 *parg++ = (char *)setup_script;
3308 *parg++ = ifname;
3309 *parg++ = NULL;
3310 execv(setup_script, args);
3311 _exit(1);
3313 while (waitpid(pid, &status, 0) != pid);
3314 if (!WIFEXITED(status) ||
3315 WEXITSTATUS(status) != 0) {
3316 fprintf(stderr, "%s: could not launch network script\n",
3317 setup_script);
3318 return -1;
3322 s = net_tap_fd_init(vlan, fd);
3323 if (!s)
3324 return -1;
3325 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3326 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3327 return 0;
3330 #endif /* !_WIN32 */
3332 /* network connection */
3333 typedef struct NetSocketState {
3334 VLANClientState *vc;
3335 int fd;
3336 int state; /* 0 = getting length, 1 = getting data */
3337 int index;
3338 int packet_len;
3339 uint8_t buf[4096];
3340 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3341 } NetSocketState;
3343 typedef struct NetSocketListenState {
3344 VLANState *vlan;
3345 int fd;
3346 } NetSocketListenState;
3348 /* XXX: we consider we can send the whole packet without blocking */
3349 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3351 NetSocketState *s = opaque;
3352 uint32_t len;
3353 len = htonl(size);
3355 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3356 send_all(s->fd, buf, size);
3359 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3361 NetSocketState *s = opaque;
3362 sendto(s->fd, buf, size, 0,
3363 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3366 static void net_socket_send(void *opaque)
3368 NetSocketState *s = opaque;
3369 int l, size, err;
3370 uint8_t buf1[4096];
3371 const uint8_t *buf;
3373 size = recv(s->fd, buf1, sizeof(buf1), 0);
3374 if (size < 0) {
3375 err = socket_error();
3376 if (err != EWOULDBLOCK)
3377 goto eoc;
3378 } else if (size == 0) {
3379 /* end of connection */
3380 eoc:
3381 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3382 closesocket(s->fd);
3383 return;
3385 buf = buf1;
3386 while (size > 0) {
3387 /* reassemble a packet from the network */
3388 switch(s->state) {
3389 case 0:
3390 l = 4 - s->index;
3391 if (l > size)
3392 l = size;
3393 memcpy(s->buf + s->index, buf, l);
3394 buf += l;
3395 size -= l;
3396 s->index += l;
3397 if (s->index == 4) {
3398 /* got length */
3399 s->packet_len = ntohl(*(uint32_t *)s->buf);
3400 s->index = 0;
3401 s->state = 1;
3403 break;
3404 case 1:
3405 l = s->packet_len - s->index;
3406 if (l > size)
3407 l = size;
3408 memcpy(s->buf + s->index, buf, l);
3409 s->index += l;
3410 buf += l;
3411 size -= l;
3412 if (s->index >= s->packet_len) {
3413 qemu_send_packet(s->vc, s->buf, s->packet_len);
3414 s->index = 0;
3415 s->state = 0;
3417 break;
3422 static void net_socket_send_dgram(void *opaque)
3424 NetSocketState *s = opaque;
3425 int size;
3427 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3428 if (size < 0)
3429 return;
3430 if (size == 0) {
3431 /* end of connection */
3432 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3433 return;
3435 qemu_send_packet(s->vc, s->buf, size);
3438 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3440 struct ip_mreq imr;
3441 int fd;
3442 int val, ret;
3443 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3444 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3445 inet_ntoa(mcastaddr->sin_addr),
3446 (int)ntohl(mcastaddr->sin_addr.s_addr));
3447 return -1;
3450 fd = socket(PF_INET, SOCK_DGRAM, 0);
3451 if (fd < 0) {
3452 perror("socket(PF_INET, SOCK_DGRAM)");
3453 return -1;
3456 val = 1;
3457 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3458 (const char *)&val, sizeof(val));
3459 if (ret < 0) {
3460 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3461 goto fail;
3464 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3465 if (ret < 0) {
3466 perror("bind");
3467 goto fail;
3470 /* Add host to multicast group */
3471 imr.imr_multiaddr = mcastaddr->sin_addr;
3472 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3474 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3475 (const char *)&imr, sizeof(struct ip_mreq));
3476 if (ret < 0) {
3477 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3478 goto fail;
3481 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3482 val = 1;
3483 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3484 (const char *)&val, sizeof(val));
3485 if (ret < 0) {
3486 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3487 goto fail;
3490 socket_set_nonblock(fd);
3491 return fd;
3492 fail:
3493 if (fd >= 0)
3494 closesocket(fd);
3495 return -1;
3498 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3499 int is_connected)
3501 struct sockaddr_in saddr;
3502 int newfd;
3503 socklen_t saddr_len;
3504 NetSocketState *s;
3506 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3507 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3508 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3511 if (is_connected) {
3512 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3513 /* must be bound */
3514 if (saddr.sin_addr.s_addr==0) {
3515 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3516 fd);
3517 return NULL;
3519 /* clone dgram socket */
3520 newfd = net_socket_mcast_create(&saddr);
3521 if (newfd < 0) {
3522 /* error already reported by net_socket_mcast_create() */
3523 close(fd);
3524 return NULL;
3526 /* clone newfd to fd, close newfd */
3527 dup2(newfd, fd);
3528 close(newfd);
3530 } else {
3531 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3532 fd, strerror(errno));
3533 return NULL;
3537 s = qemu_mallocz(sizeof(NetSocketState));
3538 if (!s)
3539 return NULL;
3540 s->fd = fd;
3542 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3543 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3545 /* mcast: save bound address as dst */
3546 if (is_connected) s->dgram_dst=saddr;
3548 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3549 "socket: fd=%d (%s mcast=%s:%d)",
3550 fd, is_connected? "cloned" : "",
3551 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3552 return s;
3555 static void net_socket_connect(void *opaque)
3557 NetSocketState *s = opaque;
3558 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3561 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3562 int is_connected)
3564 NetSocketState *s;
3565 s = qemu_mallocz(sizeof(NetSocketState));
3566 if (!s)
3567 return NULL;
3568 s->fd = fd;
3569 s->vc = qemu_new_vlan_client(vlan,
3570 net_socket_receive, NULL, s);
3571 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3572 "socket: fd=%d", fd);
3573 if (is_connected) {
3574 net_socket_connect(s);
3575 } else {
3576 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3578 return s;
3581 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3582 int is_connected)
3584 int so_type=-1, optlen=sizeof(so_type);
3586 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3587 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3588 return NULL;
3590 switch(so_type) {
3591 case SOCK_DGRAM:
3592 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3593 case SOCK_STREAM:
3594 return net_socket_fd_init_stream(vlan, fd, is_connected);
3595 default:
3596 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3597 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3598 return net_socket_fd_init_stream(vlan, fd, is_connected);
3600 return NULL;
3603 static void net_socket_accept(void *opaque)
3605 NetSocketListenState *s = opaque;
3606 NetSocketState *s1;
3607 struct sockaddr_in saddr;
3608 socklen_t len;
3609 int fd;
3611 for(;;) {
3612 len = sizeof(saddr);
3613 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3614 if (fd < 0 && errno != EINTR) {
3615 return;
3616 } else if (fd >= 0) {
3617 break;
3620 s1 = net_socket_fd_init(s->vlan, fd, 1);
3621 if (!s1) {
3622 closesocket(fd);
3623 } else {
3624 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3625 "socket: connection from %s:%d",
3626 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3630 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3632 NetSocketListenState *s;
3633 int fd, val, ret;
3634 struct sockaddr_in saddr;
3636 if (parse_host_port(&saddr, host_str) < 0)
3637 return -1;
3639 s = qemu_mallocz(sizeof(NetSocketListenState));
3640 if (!s)
3641 return -1;
3643 fd = socket(PF_INET, SOCK_STREAM, 0);
3644 if (fd < 0) {
3645 perror("socket");
3646 return -1;
3648 socket_set_nonblock(fd);
3650 /* allow fast reuse */
3651 val = 1;
3652 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3654 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3655 if (ret < 0) {
3656 perror("bind");
3657 return -1;
3659 ret = listen(fd, 0);
3660 if (ret < 0) {
3661 perror("listen");
3662 return -1;
3664 s->vlan = vlan;
3665 s->fd = fd;
3666 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3667 return 0;
3670 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3672 NetSocketState *s;
3673 int fd, connected, ret, err;
3674 struct sockaddr_in saddr;
3676 if (parse_host_port(&saddr, host_str) < 0)
3677 return -1;
3679 fd = socket(PF_INET, SOCK_STREAM, 0);
3680 if (fd < 0) {
3681 perror("socket");
3682 return -1;
3684 socket_set_nonblock(fd);
3686 connected = 0;
3687 for(;;) {
3688 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3689 if (ret < 0) {
3690 err = socket_error();
3691 if (err == EINTR || err == EWOULDBLOCK) {
3692 } else if (err == EINPROGRESS) {
3693 break;
3694 } else {
3695 perror("connect");
3696 closesocket(fd);
3697 return -1;
3699 } else {
3700 connected = 1;
3701 break;
3704 s = net_socket_fd_init(vlan, fd, connected);
3705 if (!s)
3706 return -1;
3707 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3708 "socket: connect to %s:%d",
3709 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3710 return 0;
3713 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3715 NetSocketState *s;
3716 int fd;
3717 struct sockaddr_in saddr;
3719 if (parse_host_port(&saddr, host_str) < 0)
3720 return -1;
3723 fd = net_socket_mcast_create(&saddr);
3724 if (fd < 0)
3725 return -1;
3727 s = net_socket_fd_init(vlan, fd, 0);
3728 if (!s)
3729 return -1;
3731 s->dgram_dst = saddr;
3733 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3734 "socket: mcast=%s:%d",
3735 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3736 return 0;
3740 static int get_param_value(char *buf, int buf_size,
3741 const char *tag, const char *str)
3743 const char *p;
3744 char *q;
3745 char option[128];
3747 p = str;
3748 for(;;) {
3749 q = option;
3750 while (*p != '\0' && *p != '=') {
3751 if ((q - option) < sizeof(option) - 1)
3752 *q++ = *p;
3753 p++;
3755 *q = '\0';
3756 if (*p != '=')
3757 break;
3758 p++;
3759 if (!strcmp(tag, option)) {
3760 q = buf;
3761 while (*p != '\0' && *p != ',') {
3762 if ((q - buf) < buf_size - 1)
3763 *q++ = *p;
3764 p++;
3766 *q = '\0';
3767 return q - buf;
3768 } else {
3769 while (*p != '\0' && *p != ',') {
3770 p++;
3773 if (*p != ',')
3774 break;
3775 p++;
3777 return 0;
3780 static int net_client_init(const char *str)
3782 const char *p;
3783 char *q;
3784 char device[64];
3785 char buf[1024];
3786 int vlan_id, ret;
3787 VLANState *vlan;
3789 p = str;
3790 q = device;
3791 while (*p != '\0' && *p != ',') {
3792 if ((q - device) < sizeof(device) - 1)
3793 *q++ = *p;
3794 p++;
3796 *q = '\0';
3797 if (*p == ',')
3798 p++;
3799 vlan_id = 0;
3800 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3801 vlan_id = strtol(buf, NULL, 0);
3803 vlan = qemu_find_vlan(vlan_id);
3804 if (!vlan) {
3805 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3806 return -1;
3808 if (!strcmp(device, "nic")) {
3809 NICInfo *nd;
3810 uint8_t *macaddr;
3812 if (nb_nics >= MAX_NICS) {
3813 fprintf(stderr, "Too Many NICs\n");
3814 return -1;
3816 nd = &nd_table[nb_nics];
3817 macaddr = nd->macaddr;
3818 macaddr[0] = 0x52;
3819 macaddr[1] = 0x54;
3820 macaddr[2] = 0x00;
3821 macaddr[3] = 0x12;
3822 macaddr[4] = 0x34;
3823 macaddr[5] = 0x56 + nb_nics;
3825 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3826 if (parse_macaddr(macaddr, buf) < 0) {
3827 fprintf(stderr, "invalid syntax for ethernet address\n");
3828 return -1;
3831 if (get_param_value(buf, sizeof(buf), "model", p)) {
3832 nd->model = strdup(buf);
3834 nd->vlan = vlan;
3835 nb_nics++;
3836 ret = 0;
3837 } else
3838 if (!strcmp(device, "none")) {
3839 /* does nothing. It is needed to signal that no network cards
3840 are wanted */
3841 ret = 0;
3842 } else
3843 #ifdef CONFIG_SLIRP
3844 if (!strcmp(device, "user")) {
3845 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3846 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3848 ret = net_slirp_init(vlan);
3849 } else
3850 #endif
3851 #ifdef _WIN32
3852 if (!strcmp(device, "tap")) {
3853 char ifname[64];
3854 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3855 fprintf(stderr, "tap: no interface name\n");
3856 return -1;
3858 ret = tap_win32_init(vlan, ifname);
3859 } else
3860 #else
3861 if (!strcmp(device, "tap")) {
3862 char ifname[64];
3863 char setup_script[1024];
3864 int fd;
3865 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3866 fd = strtol(buf, NULL, 0);
3867 ret = -1;
3868 if (net_tap_fd_init(vlan, fd))
3869 ret = 0;
3870 } else {
3871 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3872 ifname[0] = '\0';
3874 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3875 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3877 ret = net_tap_init(vlan, ifname, setup_script);
3879 } else
3880 #endif
3881 if (!strcmp(device, "socket")) {
3882 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3883 int fd;
3884 fd = strtol(buf, NULL, 0);
3885 ret = -1;
3886 if (net_socket_fd_init(vlan, fd, 1))
3887 ret = 0;
3888 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3889 ret = net_socket_listen_init(vlan, buf);
3890 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3891 ret = net_socket_connect_init(vlan, buf);
3892 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3893 ret = net_socket_mcast_init(vlan, buf);
3894 } else {
3895 fprintf(stderr, "Unknown socket options: %s\n", p);
3896 return -1;
3898 } else
3900 fprintf(stderr, "Unknown network device: %s\n", device);
3901 return -1;
3903 if (ret < 0) {
3904 fprintf(stderr, "Could not initialize device '%s'\n", device);
3907 return ret;
3910 void do_info_network(void)
3912 VLANState *vlan;
3913 VLANClientState *vc;
3915 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3916 term_printf("VLAN %d devices:\n", vlan->id);
3917 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3918 term_printf(" %s\n", vc->info_str);
3922 /***********************************************************/
3923 /* USB devices */
3925 static USBPort *used_usb_ports;
3926 static USBPort *free_usb_ports;
3928 /* ??? Maybe change this to register a hub to keep track of the topology. */
3929 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3930 usb_attachfn attach)
3932 port->opaque = opaque;
3933 port->index = index;
3934 port->attach = attach;
3935 port->next = free_usb_ports;
3936 free_usb_ports = port;
3939 static int usb_device_add(const char *devname)
3941 const char *p;
3942 USBDevice *dev;
3943 USBPort *port;
3945 if (!free_usb_ports)
3946 return -1;
3948 if (strstart(devname, "host:", &p)) {
3949 dev = usb_host_device_open(p);
3950 } else if (!strcmp(devname, "mouse")) {
3951 dev = usb_mouse_init();
3952 } else if (!strcmp(devname, "tablet")) {
3953 dev = usb_tablet_init();
3954 } else if (strstart(devname, "disk:", &p)) {
3955 dev = usb_msd_init(p);
3956 } else {
3957 return -1;
3959 if (!dev)
3960 return -1;
3962 /* Find a USB port to add the device to. */
3963 port = free_usb_ports;
3964 if (!port->next) {
3965 USBDevice *hub;
3967 /* Create a new hub and chain it on. */
3968 free_usb_ports = NULL;
3969 port->next = used_usb_ports;
3970 used_usb_ports = port;
3972 hub = usb_hub_init(VM_USB_HUB_SIZE);
3973 usb_attach(port, hub);
3974 port = free_usb_ports;
3977 free_usb_ports = port->next;
3978 port->next = used_usb_ports;
3979 used_usb_ports = port;
3980 usb_attach(port, dev);
3981 return 0;
3984 static int usb_device_del(const char *devname)
3986 USBPort *port;
3987 USBPort **lastp;
3988 USBDevice *dev;
3989 int bus_num, addr;
3990 const char *p;
3992 if (!used_usb_ports)
3993 return -1;
3995 p = strchr(devname, '.');
3996 if (!p)
3997 return -1;
3998 bus_num = strtoul(devname, NULL, 0);
3999 addr = strtoul(p + 1, NULL, 0);
4000 if (bus_num != 0)
4001 return -1;
4003 lastp = &used_usb_ports;
4004 port = used_usb_ports;
4005 while (port && port->dev->addr != addr) {
4006 lastp = &port->next;
4007 port = port->next;
4010 if (!port)
4011 return -1;
4013 dev = port->dev;
4014 *lastp = port->next;
4015 usb_attach(port, NULL);
4016 dev->handle_destroy(dev);
4017 port->next = free_usb_ports;
4018 free_usb_ports = port;
4019 return 0;
4022 void do_usb_add(const char *devname)
4024 int ret;
4025 ret = usb_device_add(devname);
4026 if (ret < 0)
4027 term_printf("Could not add USB device '%s'\n", devname);
4030 void do_usb_del(const char *devname)
4032 int ret;
4033 ret = usb_device_del(devname);
4034 if (ret < 0)
4035 term_printf("Could not remove USB device '%s'\n", devname);
4038 void usb_info(void)
4040 USBDevice *dev;
4041 USBPort *port;
4042 const char *speed_str;
4044 if (!usb_enabled) {
4045 term_printf("USB support not enabled\n");
4046 return;
4049 for (port = used_usb_ports; port; port = port->next) {
4050 dev = port->dev;
4051 if (!dev)
4052 continue;
4053 switch(dev->speed) {
4054 case USB_SPEED_LOW:
4055 speed_str = "1.5";
4056 break;
4057 case USB_SPEED_FULL:
4058 speed_str = "12";
4059 break;
4060 case USB_SPEED_HIGH:
4061 speed_str = "480";
4062 break;
4063 default:
4064 speed_str = "?";
4065 break;
4067 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4068 0, dev->addr, speed_str, dev->devname);
4072 /***********************************************************/
4073 /* pid file */
4075 static char *pid_filename;
4077 /* Remove PID file. Called on normal exit */
4079 static void remove_pidfile(void)
4081 unlink (pid_filename);
4084 static void create_pidfile(const char *filename)
4086 struct stat pidstat;
4087 FILE *f;
4089 /* Try to write our PID to the named file */
4090 if (stat(filename, &pidstat) < 0) {
4091 if (errno == ENOENT) {
4092 if ((f = fopen (filename, "w")) == NULL) {
4093 perror("Opening pidfile");
4094 exit(1);
4096 fprintf(f, "%d\n", getpid());
4097 fclose(f);
4098 pid_filename = qemu_strdup(filename);
4099 if (!pid_filename) {
4100 fprintf(stderr, "Could not save PID filename");
4101 exit(1);
4103 atexit(remove_pidfile);
4105 } else {
4106 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4107 filename);
4108 exit(1);
4112 /***********************************************************/
4113 /* dumb display */
4115 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4119 static void dumb_resize(DisplayState *ds, int w, int h)
4123 static void dumb_refresh(DisplayState *ds)
4125 vga_hw_update();
4128 void dumb_display_init(DisplayState *ds)
4130 ds->data = NULL;
4131 ds->linesize = 0;
4132 ds->depth = 0;
4133 ds->dpy_update = dumb_update;
4134 ds->dpy_resize = dumb_resize;
4135 ds->dpy_refresh = dumb_refresh;
4138 /***********************************************************/
4139 /* I/O handling */
4141 #define MAX_IO_HANDLERS 64
4143 typedef struct IOHandlerRecord {
4144 int fd;
4145 IOCanRWHandler *fd_read_poll;
4146 IOHandler *fd_read;
4147 IOHandler *fd_write;
4148 void *opaque;
4149 /* temporary data */
4150 struct pollfd *ufd;
4151 struct IOHandlerRecord *next;
4152 } IOHandlerRecord;
4154 static IOHandlerRecord *first_io_handler;
4156 /* XXX: fd_read_poll should be suppressed, but an API change is
4157 necessary in the character devices to suppress fd_can_read(). */
4158 int qemu_set_fd_handler2(int fd,
4159 IOCanRWHandler *fd_read_poll,
4160 IOHandler *fd_read,
4161 IOHandler *fd_write,
4162 void *opaque)
4164 IOHandlerRecord **pioh, *ioh;
4166 if (!fd_read && !fd_write) {
4167 pioh = &first_io_handler;
4168 for(;;) {
4169 ioh = *pioh;
4170 if (ioh == NULL)
4171 break;
4172 if (ioh->fd == fd) {
4173 *pioh = ioh->next;
4174 qemu_free(ioh);
4175 break;
4177 pioh = &ioh->next;
4179 } else {
4180 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4181 if (ioh->fd == fd)
4182 goto found;
4184 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4185 if (!ioh)
4186 return -1;
4187 ioh->next = first_io_handler;
4188 first_io_handler = ioh;
4189 found:
4190 ioh->fd = fd;
4191 ioh->fd_read_poll = fd_read_poll;
4192 ioh->fd_read = fd_read;
4193 ioh->fd_write = fd_write;
4194 ioh->opaque = opaque;
4196 return 0;
4199 int qemu_set_fd_handler(int fd,
4200 IOHandler *fd_read,
4201 IOHandler *fd_write,
4202 void *opaque)
4204 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4207 /***********************************************************/
4208 /* Polling handling */
4210 typedef struct PollingEntry {
4211 PollingFunc *func;
4212 void *opaque;
4213 struct PollingEntry *next;
4214 } PollingEntry;
4216 static PollingEntry *first_polling_entry;
4218 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4220 PollingEntry **ppe, *pe;
4221 pe = qemu_mallocz(sizeof(PollingEntry));
4222 if (!pe)
4223 return -1;
4224 pe->func = func;
4225 pe->opaque = opaque;
4226 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4227 *ppe = pe;
4228 return 0;
4231 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4233 PollingEntry **ppe, *pe;
4234 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4235 pe = *ppe;
4236 if (pe->func == func && pe->opaque == opaque) {
4237 *ppe = pe->next;
4238 qemu_free(pe);
4239 break;
4244 #ifdef _WIN32
4245 /***********************************************************/
4246 /* Wait objects support */
4247 typedef struct WaitObjects {
4248 int num;
4249 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4250 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4251 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4252 } WaitObjects;
4254 static WaitObjects wait_objects = {0};
4256 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4258 WaitObjects *w = &wait_objects;
4260 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4261 return -1;
4262 w->events[w->num] = handle;
4263 w->func[w->num] = func;
4264 w->opaque[w->num] = opaque;
4265 w->num++;
4266 return 0;
4269 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4271 int i, found;
4272 WaitObjects *w = &wait_objects;
4274 found = 0;
4275 for (i = 0; i < w->num; i++) {
4276 if (w->events[i] == handle)
4277 found = 1;
4278 if (found) {
4279 w->events[i] = w->events[i + 1];
4280 w->func[i] = w->func[i + 1];
4281 w->opaque[i] = w->opaque[i + 1];
4284 if (found)
4285 w->num--;
4287 #endif
4289 #define SELF_ANNOUNCE_ROUNDS 5
4290 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4291 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4292 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4294 static int announce_self_create(uint8_t *buf,
4295 uint8_t *mac_addr)
4297 uint32_t magic = EXPERIMENTAL_MAGIC;
4298 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
4300 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4302 memset(buf, 0xff, 6); /* h_dst */
4303 memcpy(buf + 6, mac_addr, 6); /* h_src */
4304 memcpy(buf + 12, &proto, 2); /* h_proto */
4305 memcpy(buf + 14, &magic, 4); /* magic */
4307 return 18; /* len */
4310 static void qemu_announce_self(void)
4312 int i, j, len;
4313 VLANState *vlan;
4314 VLANClientState *vc;
4315 uint8_t buf[256];
4317 for (i = 0; i < nb_nics; i++) {
4318 len = announce_self_create(buf, nd_table[i].macaddr);
4319 vlan = nd_table[i].vlan;
4320 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4321 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
4322 vc->fd_read(vc->opaque, buf, len);
4327 /***********************************************************/
4328 /* savevm/loadvm support */
4330 #define IO_BUF_SIZE 32768
4332 struct QEMUFile {
4333 QEMUFilePutBufferFunc *put_buffer;
4334 QEMUFileGetBufferFunc *get_buffer;
4335 QEMUFileCloseFunc *close;
4336 void *opaque;
4338 int64_t buf_offset; /* start of buffer when writing, end of buffer
4339 when reading */
4340 int buf_index;
4341 int buf_size; /* 0 when writing */
4342 uint8_t buf[IO_BUF_SIZE];
4345 typedef struct QEMUFileFD
4347 int fd;
4348 } QEMUFileFD;
4350 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4352 QEMUFileFD *s = opaque;
4353 int offset = 0;
4354 ssize_t len;
4356 again:
4357 len = read(s->fd, buf + offset, size - offset);
4358 if (len == -1) {
4359 if (errno == EINTR || errno == EAGAIN)
4360 goto again;
4363 return len;
4366 QEMUFile *qemu_fopen_fd(int fd)
4368 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
4369 s->fd = fd;
4370 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
4373 typedef struct QEMUFileUnix
4375 FILE *outfile;
4376 } QEMUFileUnix;
4378 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4380 QEMUFileUnix *s = opaque;
4381 fseek(s->outfile, pos, SEEK_SET);
4382 fwrite(buf, 1, size, s->outfile);
4385 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4387 QEMUFileUnix *s = opaque;
4388 fseek(s->outfile, pos, SEEK_SET);
4389 return fread(buf, 1, size, s->outfile);
4392 static void file_close(void *opaque)
4394 QEMUFileUnix *s = opaque;
4395 fclose(s->outfile);
4396 qemu_free(s);
4399 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
4401 QEMUFileUnix *s;
4403 s = qemu_mallocz(sizeof(QEMUFileUnix));
4404 if (!s)
4405 return NULL;
4407 s->outfile = fopen(filename, mode);
4408 if (!s->outfile)
4409 goto fail;
4411 if (!strcmp(mode, "wb"))
4412 return qemu_fopen(s, file_put_buffer, NULL, file_close);
4413 else if (!strcmp(mode, "rb"))
4414 return qemu_fopen(s, NULL, file_get_buffer, file_close);
4416 fail:
4417 if (s->outfile)
4418 fclose(s->outfile);
4419 qemu_free(s);
4420 return NULL;
4423 typedef struct QEMUFileBdrv
4425 BlockDriverState *bs;
4426 int64_t base_offset;
4427 } QEMUFileBdrv;
4429 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4431 QEMUFileBdrv *s = opaque;
4432 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
4435 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4437 QEMUFileBdrv *s = opaque;
4438 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
4441 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4443 QEMUFileBdrv *s;
4445 s = qemu_mallocz(sizeof(QEMUFileBdrv));
4446 if (!s)
4447 return NULL;
4449 s->bs = bs;
4450 s->base_offset = offset;
4452 if (is_writable)
4453 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
4455 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
4458 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
4459 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
4461 QEMUFile *f;
4463 f = qemu_mallocz(sizeof(QEMUFile));
4464 if (!f)
4465 return NULL;
4467 f->opaque = opaque;
4468 f->put_buffer = put_buffer;
4469 f->get_buffer = get_buffer;
4470 f->close = close;
4472 return f;
4475 void qemu_fflush(QEMUFile *f)
4477 if (!f->put_buffer)
4478 return;
4480 if (f->buf_index > 0) {
4481 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
4482 f->buf_offset += f->buf_index;
4483 f->buf_index = 0;
4487 static void qemu_fill_buffer(QEMUFile *f)
4489 int len;
4491 if (!f->get_buffer)
4492 return;
4494 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
4495 if (len < 0)
4496 len = 0;
4498 f->buf_index = 0;
4499 f->buf_size = len;
4500 f->buf_offset += len;
4503 void qemu_fclose(QEMUFile *f)
4505 qemu_fflush(f);
4506 if (f->close)
4507 f->close(f->opaque);
4508 qemu_free(f);
4511 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4513 int l;
4514 while (size > 0) {
4515 l = IO_BUF_SIZE - f->buf_index;
4516 if (l > size)
4517 l = size;
4518 memcpy(f->buf + f->buf_index, buf, l);
4519 f->buf_index += l;
4520 buf += l;
4521 size -= l;
4522 if (f->buf_index >= IO_BUF_SIZE)
4523 qemu_fflush(f);
4527 void qemu_put_byte(QEMUFile *f, int v)
4529 f->buf[f->buf_index++] = v;
4530 if (f->buf_index >= IO_BUF_SIZE)
4531 qemu_fflush(f);
4534 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4536 int size, l;
4538 size = size1;
4539 while (size > 0) {
4540 l = f->buf_size - f->buf_index;
4541 if (l == 0) {
4542 qemu_fill_buffer(f);
4543 l = f->buf_size - f->buf_index;
4544 if (l == 0)
4545 break;
4547 if (l > size)
4548 l = size;
4549 memcpy(buf, f->buf + f->buf_index, l);
4550 f->buf_index += l;
4551 buf += l;
4552 size -= l;
4554 return size1 - size;
4557 int qemu_get_byte(QEMUFile *f)
4559 if (f->buf_index >= f->buf_size) {
4560 qemu_fill_buffer(f);
4561 if (f->buf_index >= f->buf_size)
4562 return 0;
4564 return f->buf[f->buf_index++];
4567 int64_t qemu_ftell(QEMUFile *f)
4569 return f->buf_offset - f->buf_size + f->buf_index;
4572 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4574 if (whence == SEEK_SET) {
4575 /* nothing to do */
4576 } else if (whence == SEEK_CUR) {
4577 pos += qemu_ftell(f);
4578 } else {
4579 /* SEEK_END not supported */
4580 return -1;
4582 if (f->put_buffer) {
4583 qemu_fflush(f);
4584 f->buf_offset = pos;
4585 } else {
4586 f->buf_offset = pos;
4587 f->buf_index = 0;
4588 f->buf_size = 0;
4590 return pos;
4593 void qemu_put_be16(QEMUFile *f, unsigned int v)
4595 qemu_put_byte(f, v >> 8);
4596 qemu_put_byte(f, v);
4599 void qemu_put_be32(QEMUFile *f, unsigned int v)
4601 qemu_put_byte(f, v >> 24);
4602 qemu_put_byte(f, v >> 16);
4603 qemu_put_byte(f, v >> 8);
4604 qemu_put_byte(f, v);
4607 void qemu_put_be64(QEMUFile *f, uint64_t v)
4609 qemu_put_be32(f, v >> 32);
4610 qemu_put_be32(f, v);
4613 unsigned int qemu_get_be16(QEMUFile *f)
4615 unsigned int v;
4616 v = qemu_get_byte(f) << 8;
4617 v |= qemu_get_byte(f);
4618 return v;
4621 unsigned int qemu_get_be32(QEMUFile *f)
4623 unsigned int v;
4624 v = qemu_get_byte(f) << 24;
4625 v |= qemu_get_byte(f) << 16;
4626 v |= qemu_get_byte(f) << 8;
4627 v |= qemu_get_byte(f);
4628 return v;
4631 uint64_t qemu_get_be64(QEMUFile *f)
4633 uint64_t v;
4634 v = (uint64_t)qemu_get_be32(f) << 32;
4635 v |= qemu_get_be32(f);
4636 return v;
4639 typedef struct SaveStateEntry {
4640 char idstr[256];
4641 int instance_id;
4642 int version_id;
4643 SaveStateHandler *save_state;
4644 LoadStateHandler *load_state;
4645 void *opaque;
4646 struct SaveStateEntry *next;
4647 } SaveStateEntry;
4649 static SaveStateEntry *first_se;
4651 int register_savevm(const char *idstr,
4652 int instance_id,
4653 int version_id,
4654 SaveStateHandler *save_state,
4655 LoadStateHandler *load_state,
4656 void *opaque)
4658 SaveStateEntry *se, **pse;
4660 se = qemu_malloc(sizeof(SaveStateEntry));
4661 if (!se)
4662 return -1;
4663 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4664 se->instance_id = instance_id;
4665 se->version_id = version_id;
4666 se->save_state = save_state;
4667 se->load_state = load_state;
4668 se->opaque = opaque;
4669 se->next = NULL;
4671 /* add at the end of list */
4672 pse = &first_se;
4673 while (*pse != NULL)
4674 pse = &(*pse)->next;
4675 *pse = se;
4676 return 0;
4679 #define QEMU_VM_FILE_MAGIC 0x5145564d
4680 #define QEMU_VM_FILE_VERSION 0x00000002
4682 int qemu_savevm_state(QEMUFile *f)
4684 SaveStateEntry *se;
4685 int len, ret;
4686 int64_t cur_pos, len_pos, total_len_pos;
4688 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4689 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4690 total_len_pos = qemu_ftell(f);
4691 qemu_put_be64(f, 0); /* total size */
4693 for(se = first_se; se != NULL; se = se->next) {
4694 /* ID string */
4695 len = strlen(se->idstr);
4696 qemu_put_byte(f, len);
4697 qemu_put_buffer(f, se->idstr, len);
4699 qemu_put_be32(f, se->instance_id);
4700 qemu_put_be32(f, se->version_id);
4702 /* record size: filled later */
4703 len_pos = qemu_ftell(f);
4704 qemu_put_be32(f, 0);
4706 se->save_state(f, se->opaque);
4708 /* fill record size */
4709 cur_pos = qemu_ftell(f);
4710 len = cur_pos - len_pos - 4;
4711 qemu_fseek(f, len_pos, SEEK_SET);
4712 qemu_put_be32(f, len);
4713 qemu_fseek(f, cur_pos, SEEK_SET);
4715 cur_pos = qemu_ftell(f);
4716 qemu_fseek(f, total_len_pos, SEEK_SET);
4717 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4718 qemu_fseek(f, cur_pos, SEEK_SET);
4720 ret = 0;
4721 return ret;
4724 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4726 SaveStateEntry *se;
4728 for(se = first_se; se != NULL; se = se->next) {
4729 if (!strcmp(se->idstr, idstr) &&
4730 instance_id == se->instance_id)
4731 return se;
4733 return NULL;
4736 int qemu_loadvm_state(QEMUFile *f)
4738 SaveStateEntry *se;
4739 int len, ret, instance_id, record_len, version_id;
4740 int64_t total_len, end_pos, cur_pos;
4741 unsigned int v;
4742 char idstr[256];
4744 v = qemu_get_be32(f);
4745 if (v != QEMU_VM_FILE_MAGIC)
4746 goto fail;
4747 v = qemu_get_be32(f);
4748 if (v != QEMU_VM_FILE_VERSION) {
4749 fail:
4750 ret = -1;
4751 goto the_end;
4753 total_len = qemu_get_be64(f);
4754 end_pos = total_len + qemu_ftell(f);
4755 for(;;) {
4756 if (qemu_ftell(f) >= end_pos)
4757 break;
4758 len = qemu_get_byte(f);
4759 qemu_get_buffer(f, idstr, len);
4760 idstr[len] = '\0';
4761 instance_id = qemu_get_be32(f);
4762 version_id = qemu_get_be32(f);
4763 record_len = qemu_get_be32(f);
4764 #if 0
4765 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4766 idstr, instance_id, version_id, record_len);
4767 #endif
4768 cur_pos = qemu_ftell(f);
4769 se = find_se(idstr, instance_id);
4770 if (!se) {
4771 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4772 instance_id, idstr);
4773 } else {
4774 ret = se->load_state(f, se->opaque, version_id);
4775 if (ret < 0) {
4776 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4777 instance_id, idstr);
4780 /* always seek to exact end of record */
4781 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4783 ret = 0;
4784 the_end:
4785 return ret;
4788 int qemu_live_savevm_state(QEMUFile *f)
4790 SaveStateEntry *se;
4791 int len, ret;
4793 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4794 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4796 for(se = first_se; se != NULL; se = se->next) {
4797 len = strlen(se->idstr);
4799 qemu_put_byte(f, len);
4800 qemu_put_buffer(f, se->idstr, len);
4801 qemu_put_be32(f, se->instance_id);
4802 qemu_put_be32(f, se->version_id);
4804 se->save_state(f, se->opaque);
4807 qemu_put_byte(f, 0);
4809 ret = 0;
4810 return ret;
4813 int qemu_live_loadvm_state(QEMUFile *f)
4815 SaveStateEntry *se;
4816 int len, ret, instance_id, version_id;
4817 unsigned int v;
4818 char idstr[256];
4820 v = qemu_get_be32(f);
4821 if (v != QEMU_VM_FILE_MAGIC)
4822 goto fail;
4823 v = qemu_get_be32(f);
4824 if (v != QEMU_VM_FILE_VERSION) {
4825 fail:
4826 ret = -1;
4827 goto the_end;
4830 for(;;) {
4831 len = qemu_get_byte(f);
4832 if (len == 0)
4833 break;
4834 qemu_get_buffer(f, idstr, len);
4835 idstr[len] = '\0';
4836 instance_id = qemu_get_be32(f);
4837 version_id = qemu_get_be32(f);
4838 se = find_se(idstr, instance_id);
4839 if (!se) {
4840 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4841 instance_id, idstr);
4842 } else {
4843 ret = se->load_state(f, se->opaque, version_id);
4844 if (ret < 0) {
4845 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4846 instance_id, idstr);
4850 ret = 0;
4852 qemu_announce_self();
4854 the_end:
4855 return ret;
4858 /* device can contain snapshots */
4859 static int bdrv_can_snapshot(BlockDriverState *bs)
4861 return (bs &&
4862 !bdrv_is_removable(bs) &&
4863 !bdrv_is_read_only(bs));
4866 /* device must be snapshots in order to have a reliable snapshot */
4867 static int bdrv_has_snapshot(BlockDriverState *bs)
4869 return (bs &&
4870 !bdrv_is_removable(bs) &&
4871 !bdrv_is_read_only(bs));
4874 static BlockDriverState *get_bs_snapshots(void)
4876 BlockDriverState *bs;
4877 int i;
4879 if (bs_snapshots)
4880 return bs_snapshots;
4881 for(i = 0; i <= MAX_DISKS; i++) {
4882 bs = bs_table[i];
4883 if (bdrv_can_snapshot(bs))
4884 goto ok;
4886 return NULL;
4888 bs_snapshots = bs;
4889 return bs;
4892 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4893 const char *name)
4895 QEMUSnapshotInfo *sn_tab, *sn;
4896 int nb_sns, i, ret;
4898 ret = -ENOENT;
4899 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4900 if (nb_sns < 0)
4901 return ret;
4902 for(i = 0; i < nb_sns; i++) {
4903 sn = &sn_tab[i];
4904 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4905 *sn_info = *sn;
4906 ret = 0;
4907 break;
4910 qemu_free(sn_tab);
4911 return ret;
4914 void do_savevm(const char *name)
4916 BlockDriverState *bs, *bs1;
4917 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4918 int must_delete, ret, i;
4919 BlockDriverInfo bdi1, *bdi = &bdi1;
4920 QEMUFile *f;
4921 int saved_vm_running;
4922 #ifdef _WIN32
4923 struct _timeb tb;
4924 #else
4925 struct timeval tv;
4926 #endif
4928 bs = get_bs_snapshots();
4929 if (!bs) {
4930 term_printf("No block device can accept snapshots\n");
4931 return;
4934 /* ??? Should this occur after vm_stop? */
4935 qemu_aio_flush();
4937 saved_vm_running = vm_running;
4938 vm_stop(0);
4940 must_delete = 0;
4941 if (name) {
4942 ret = bdrv_snapshot_find(bs, old_sn, name);
4943 if (ret >= 0) {
4944 must_delete = 1;
4947 memset(sn, 0, sizeof(*sn));
4948 if (must_delete) {
4949 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4950 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4951 } else {
4952 if (name)
4953 pstrcpy(sn->name, sizeof(sn->name), name);
4956 /* fill auxiliary fields */
4957 #ifdef _WIN32
4958 _ftime(&tb);
4959 sn->date_sec = tb.time;
4960 sn->date_nsec = tb.millitm * 1000000;
4961 #else
4962 gettimeofday(&tv, NULL);
4963 sn->date_sec = tv.tv_sec;
4964 sn->date_nsec = tv.tv_usec * 1000;
4965 #endif
4966 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4968 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4969 term_printf("Device %s does not support VM state snapshots\n",
4970 bdrv_get_device_name(bs));
4971 goto the_end;
4974 /* save the VM state */
4975 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4976 if (!f) {
4977 term_printf("Could not open VM state file\n");
4978 goto the_end;
4980 ret = qemu_savevm_state(f);
4981 sn->vm_state_size = qemu_ftell(f);
4982 qemu_fclose(f);
4983 if (ret < 0) {
4984 term_printf("Error %d while writing VM\n", ret);
4985 goto the_end;
4988 /* create the snapshots */
4990 for(i = 0; i < MAX_DISKS; i++) {
4991 bs1 = bs_table[i];
4992 if (bdrv_has_snapshot(bs1)) {
4993 if (must_delete) {
4994 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4995 if (ret < 0) {
4996 term_printf("Error while deleting snapshot on '%s'\n",
4997 bdrv_get_device_name(bs1));
5000 ret = bdrv_snapshot_create(bs1, sn);
5001 if (ret < 0) {
5002 term_printf("Error while creating snapshot on '%s'\n",
5003 bdrv_get_device_name(bs1));
5008 the_end:
5009 if (saved_vm_running)
5010 vm_start();
5013 void do_loadvm(const char *name)
5015 BlockDriverState *bs, *bs1;
5016 BlockDriverInfo bdi1, *bdi = &bdi1;
5017 QEMUFile *f;
5018 int i, ret;
5019 int saved_vm_running;
5021 bs = get_bs_snapshots();
5022 if (!bs) {
5023 term_printf("No block device supports snapshots\n");
5024 return;
5027 /* Flush all IO requests so they don't interfere with the new state. */
5028 qemu_aio_flush();
5030 saved_vm_running = vm_running;
5031 vm_stop(0);
5033 for(i = 0; i <= MAX_DISKS; i++) {
5034 bs1 = bs_table[i];
5035 if (bdrv_has_snapshot(bs1)) {
5036 ret = bdrv_snapshot_goto(bs1, name);
5037 if (ret < 0) {
5038 if (bs != bs1)
5039 term_printf("Warning: ");
5040 switch(ret) {
5041 case -ENOTSUP:
5042 term_printf("Snapshots not supported on device '%s'\n",
5043 bdrv_get_device_name(bs1));
5044 break;
5045 case -ENOENT:
5046 term_printf("Could not find snapshot '%s' on device '%s'\n",
5047 name, bdrv_get_device_name(bs1));
5048 break;
5049 default:
5050 term_printf("Error %d while activating snapshot on '%s'\n",
5051 ret, bdrv_get_device_name(bs1));
5052 break;
5054 /* fatal on snapshot block device */
5055 if (bs == bs1)
5056 goto the_end;
5061 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5062 term_printf("Device %s does not support VM state snapshots\n",
5063 bdrv_get_device_name(bs));
5064 return;
5067 /* restore the VM state */
5068 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5069 if (!f) {
5070 term_printf("Could not open VM state file\n");
5071 goto the_end;
5073 ret = qemu_loadvm_state(f);
5074 qemu_fclose(f);
5075 if (ret < 0) {
5076 term_printf("Error %d while loading VM state\n", ret);
5078 the_end:
5079 if (saved_vm_running)
5080 vm_start();
5083 void do_delvm(const char *name)
5085 BlockDriverState *bs, *bs1;
5086 int i, ret;
5088 bs = get_bs_snapshots();
5089 if (!bs) {
5090 term_printf("No block device supports snapshots\n");
5091 return;
5094 for(i = 0; i <= MAX_DISKS; i++) {
5095 bs1 = bs_table[i];
5096 if (bdrv_has_snapshot(bs1)) {
5097 ret = bdrv_snapshot_delete(bs1, name);
5098 if (ret < 0) {
5099 if (ret == -ENOTSUP)
5100 term_printf("Snapshots not supported on device '%s'\n",
5101 bdrv_get_device_name(bs1));
5102 else
5103 term_printf("Error %d while deleting snapshot on '%s'\n",
5104 ret, bdrv_get_device_name(bs1));
5110 void do_info_snapshots(void)
5112 BlockDriverState *bs, *bs1;
5113 QEMUSnapshotInfo *sn_tab, *sn;
5114 int nb_sns, i;
5115 char buf[256];
5117 bs = get_bs_snapshots();
5118 if (!bs) {
5119 term_printf("No available block device supports snapshots\n");
5120 return;
5122 term_printf("Snapshot devices:");
5123 for(i = 0; i <= MAX_DISKS; i++) {
5124 bs1 = bs_table[i];
5125 if (bdrv_has_snapshot(bs1)) {
5126 if (bs == bs1)
5127 term_printf(" %s", bdrv_get_device_name(bs1));
5130 term_printf("\n");
5132 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5133 if (nb_sns < 0) {
5134 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5135 return;
5137 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5138 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5139 for(i = 0; i < nb_sns; i++) {
5140 sn = &sn_tab[i];
5141 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5143 qemu_free(sn_tab);
5146 /***********************************************************/
5147 /* cpu save/restore */
5149 #if defined(TARGET_I386)
5151 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5153 qemu_put_be32(f, dt->selector);
5154 qemu_put_betl(f, dt->base);
5155 qemu_put_be32(f, dt->limit);
5156 qemu_put_be32(f, dt->flags);
5159 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5161 dt->selector = qemu_get_be32(f);
5162 dt->base = qemu_get_betl(f);
5163 dt->limit = qemu_get_be32(f);
5164 dt->flags = qemu_get_be32(f);
5167 void cpu_save(QEMUFile *f, void *opaque)
5169 CPUState *env = opaque;
5170 uint16_t fptag, fpus, fpuc, fpregs_format;
5171 uint32_t hflags;
5172 int i;
5174 #ifdef USE_KVM
5175 if (kvm_allowed)
5176 kvm_save_registers(env);
5177 #endif
5179 for(i = 0; i < CPU_NB_REGS; i++)
5180 qemu_put_betls(f, &env->regs[i]);
5181 qemu_put_betls(f, &env->eip);
5182 qemu_put_betls(f, &env->eflags);
5183 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5184 qemu_put_be32s(f, &hflags);
5186 /* FPU */
5187 fpuc = env->fpuc;
5188 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5189 fptag = 0;
5190 for(i = 0; i < 8; i++) {
5191 fptag |= ((!env->fptags[i]) << i);
5194 qemu_put_be16s(f, &fpuc);
5195 qemu_put_be16s(f, &fpus);
5196 qemu_put_be16s(f, &fptag);
5198 #ifdef USE_X86LDOUBLE
5199 fpregs_format = 0;
5200 #else
5201 fpregs_format = 1;
5202 #endif
5203 qemu_put_be16s(f, &fpregs_format);
5205 for(i = 0; i < 8; i++) {
5206 #ifdef USE_X86LDOUBLE
5208 uint64_t mant;
5209 uint16_t exp;
5210 /* we save the real CPU data (in case of MMX usage only 'mant'
5211 contains the MMX register */
5212 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5213 qemu_put_be64(f, mant);
5214 qemu_put_be16(f, exp);
5216 #else
5217 /* if we use doubles for float emulation, we save the doubles to
5218 avoid losing information in case of MMX usage. It can give
5219 problems if the image is restored on a CPU where long
5220 doubles are used instead. */
5221 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5222 #endif
5225 for(i = 0; i < 6; i++)
5226 cpu_put_seg(f, &env->segs[i]);
5227 cpu_put_seg(f, &env->ldt);
5228 cpu_put_seg(f, &env->tr);
5229 cpu_put_seg(f, &env->gdt);
5230 cpu_put_seg(f, &env->idt);
5232 qemu_put_be32s(f, &env->sysenter_cs);
5233 qemu_put_be32s(f, &env->sysenter_esp);
5234 qemu_put_be32s(f, &env->sysenter_eip);
5236 qemu_put_betls(f, &env->cr[0]);
5237 qemu_put_betls(f, &env->cr[2]);
5238 qemu_put_betls(f, &env->cr[3]);
5239 qemu_put_betls(f, &env->cr[4]);
5241 for(i = 0; i < 8; i++)
5242 qemu_put_betls(f, &env->dr[i]);
5244 /* MMU */
5245 qemu_put_be32s(f, &env->a20_mask);
5247 /* XMM */
5248 qemu_put_be32s(f, &env->mxcsr);
5249 for(i = 0; i < CPU_NB_REGS; i++) {
5250 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5251 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5254 #ifdef TARGET_X86_64
5255 qemu_put_be64s(f, &env->efer);
5256 qemu_put_be64s(f, &env->star);
5257 qemu_put_be64s(f, &env->lstar);
5258 qemu_put_be64s(f, &env->cstar);
5259 qemu_put_be64s(f, &env->fmask);
5260 qemu_put_be64s(f, &env->kernelgsbase);
5261 #endif
5262 qemu_put_be32s(f, &env->smbase);
5264 #ifdef USE_KVM
5265 if (kvm_allowed) {
5266 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5267 qemu_put_betls(f, &env->kvm_interrupt_bitmap[i]);
5269 qemu_put_be64s(f, &env->tsc);
5271 #endif
5275 #ifdef USE_X86LDOUBLE
5276 /* XXX: add that in a FPU generic layer */
5277 union x86_longdouble {
5278 uint64_t mant;
5279 uint16_t exp;
5282 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5283 #define EXPBIAS1 1023
5284 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5285 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5287 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5289 int e;
5290 /* mantissa */
5291 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5292 /* exponent + sign */
5293 e = EXPD1(temp) - EXPBIAS1 + 16383;
5294 e |= SIGND1(temp) >> 16;
5295 p->exp = e;
5297 #endif
5299 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5301 CPUState *env = opaque;
5302 int i, guess_mmx;
5303 uint32_t hflags;
5304 uint16_t fpus, fpuc, fptag, fpregs_format;
5306 if (version_id != 3 && version_id != 4)
5307 return -EINVAL;
5308 for(i = 0; i < CPU_NB_REGS; i++)
5309 qemu_get_betls(f, &env->regs[i]);
5310 qemu_get_betls(f, &env->eip);
5311 qemu_get_betls(f, &env->eflags);
5312 qemu_get_be32s(f, &hflags);
5314 qemu_get_be16s(f, &fpuc);
5315 qemu_get_be16s(f, &fpus);
5316 qemu_get_be16s(f, &fptag);
5317 qemu_get_be16s(f, &fpregs_format);
5319 /* NOTE: we cannot always restore the FPU state if the image come
5320 from a host with a different 'USE_X86LDOUBLE' define. We guess
5321 if we are in an MMX state to restore correctly in that case. */
5322 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5323 for(i = 0; i < 8; i++) {
5324 uint64_t mant;
5325 uint16_t exp;
5327 switch(fpregs_format) {
5328 case 0:
5329 mant = qemu_get_be64(f);
5330 exp = qemu_get_be16(f);
5331 #ifdef USE_X86LDOUBLE
5332 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5333 #else
5334 /* difficult case */
5335 if (guess_mmx)
5336 env->fpregs[i].mmx.MMX_Q(0) = mant;
5337 else
5338 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5339 #endif
5340 break;
5341 case 1:
5342 mant = qemu_get_be64(f);
5343 #ifdef USE_X86LDOUBLE
5345 union x86_longdouble *p;
5346 /* difficult case */
5347 p = (void *)&env->fpregs[i];
5348 if (guess_mmx) {
5349 p->mant = mant;
5350 p->exp = 0xffff;
5351 } else {
5352 fp64_to_fp80(p, mant);
5355 #else
5356 env->fpregs[i].mmx.MMX_Q(0) = mant;
5357 #endif
5358 break;
5359 default:
5360 return -EINVAL;
5364 env->fpuc = fpuc;
5365 /* XXX: restore FPU round state */
5366 env->fpstt = (fpus >> 11) & 7;
5367 env->fpus = fpus & ~0x3800;
5368 fptag ^= 0xff;
5369 for(i = 0; i < 8; i++) {
5370 env->fptags[i] = (fptag >> i) & 1;
5373 for(i = 0; i < 6; i++)
5374 cpu_get_seg(f, &env->segs[i]);
5375 cpu_get_seg(f, &env->ldt);
5376 cpu_get_seg(f, &env->tr);
5377 cpu_get_seg(f, &env->gdt);
5378 cpu_get_seg(f, &env->idt);
5380 qemu_get_be32s(f, &env->sysenter_cs);
5381 qemu_get_be32s(f, &env->sysenter_esp);
5382 qemu_get_be32s(f, &env->sysenter_eip);
5384 qemu_get_betls(f, &env->cr[0]);
5385 qemu_get_betls(f, &env->cr[2]);
5386 qemu_get_betls(f, &env->cr[3]);
5387 qemu_get_betls(f, &env->cr[4]);
5389 for(i = 0; i < 8; i++)
5390 qemu_get_betls(f, &env->dr[i]);
5392 /* MMU */
5393 qemu_get_be32s(f, &env->a20_mask);
5395 qemu_get_be32s(f, &env->mxcsr);
5396 for(i = 0; i < CPU_NB_REGS; i++) {
5397 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5398 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5401 #ifdef TARGET_X86_64
5402 qemu_get_be64s(f, &env->efer);
5403 qemu_get_be64s(f, &env->star);
5404 qemu_get_be64s(f, &env->lstar);
5405 qemu_get_be64s(f, &env->cstar);
5406 qemu_get_be64s(f, &env->fmask);
5407 qemu_get_be64s(f, &env->kernelgsbase);
5408 #endif
5409 if (version_id >= 4)
5410 qemu_get_be32s(f, &env->smbase);
5412 /* XXX: compute hflags from scratch, except for CPL and IIF */
5413 env->hflags = hflags;
5414 tlb_flush(env, 1);
5415 #ifdef USE_KVM
5416 if (kvm_allowed) {
5417 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5418 qemu_get_betls(f, &env->kvm_interrupt_bitmap[i]);
5420 qemu_get_be64s(f, &env->tsc);
5421 kvm_load_registers(env);
5423 #endif
5424 return 0;
5427 #elif defined(TARGET_PPC)
5428 void cpu_save(QEMUFile *f, void *opaque)
5432 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5434 return 0;
5437 #elif defined(TARGET_MIPS)
5438 void cpu_save(QEMUFile *f, void *opaque)
5442 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5444 return 0;
5447 #elif defined(TARGET_SPARC)
5448 void cpu_save(QEMUFile *f, void *opaque)
5450 CPUState *env = opaque;
5451 int i;
5452 uint32_t tmp;
5454 for(i = 0; i < 8; i++)
5455 qemu_put_betls(f, &env->gregs[i]);
5456 for(i = 0; i < NWINDOWS * 16; i++)
5457 qemu_put_betls(f, &env->regbase[i]);
5459 /* FPU */
5460 for(i = 0; i < TARGET_FPREGS; i++) {
5461 union {
5462 float32 f;
5463 uint32_t i;
5464 } u;
5465 u.f = env->fpr[i];
5466 qemu_put_be32(f, u.i);
5469 qemu_put_betls(f, &env->pc);
5470 qemu_put_betls(f, &env->npc);
5471 qemu_put_betls(f, &env->y);
5472 tmp = GET_PSR(env);
5473 qemu_put_be32(f, tmp);
5474 qemu_put_betls(f, &env->fsr);
5475 qemu_put_betls(f, &env->tbr);
5476 #ifndef TARGET_SPARC64
5477 qemu_put_be32s(f, &env->wim);
5478 /* MMU */
5479 for(i = 0; i < 16; i++)
5480 qemu_put_be32s(f, &env->mmuregs[i]);
5481 #endif
5484 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5486 CPUState *env = opaque;
5487 int i;
5488 uint32_t tmp;
5490 for(i = 0; i < 8; i++)
5491 qemu_get_betls(f, &env->gregs[i]);
5492 for(i = 0; i < NWINDOWS * 16; i++)
5493 qemu_get_betls(f, &env->regbase[i]);
5495 /* FPU */
5496 for(i = 0; i < TARGET_FPREGS; i++) {
5497 union {
5498 float32 f;
5499 uint32_t i;
5500 } u;
5501 u.i = qemu_get_be32(f);
5502 env->fpr[i] = u.f;
5505 qemu_get_betls(f, &env->pc);
5506 qemu_get_betls(f, &env->npc);
5507 qemu_get_betls(f, &env->y);
5508 tmp = qemu_get_be32(f);
5509 env->cwp = 0; /* needed to ensure that the wrapping registers are
5510 correctly updated */
5511 PUT_PSR(env, tmp);
5512 qemu_get_betls(f, &env->fsr);
5513 qemu_get_betls(f, &env->tbr);
5514 #ifndef TARGET_SPARC64
5515 qemu_get_be32s(f, &env->wim);
5516 /* MMU */
5517 for(i = 0; i < 16; i++)
5518 qemu_get_be32s(f, &env->mmuregs[i]);
5519 #endif
5520 tlb_flush(env, 1);
5521 return 0;
5524 #elif defined(TARGET_ARM)
5526 /* ??? Need to implement these. */
5527 void cpu_save(QEMUFile *f, void *opaque)
5531 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5533 return 0;
5536 #else
5538 #warning No CPU save/restore functions
5540 #endif
5542 /***********************************************************/
5543 /* ram save/restore */
5545 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5547 int v;
5549 v = qemu_get_byte(f);
5550 switch(v) {
5551 case 0:
5552 if (qemu_get_buffer(f, buf, len) != len)
5553 return -EIO;
5554 break;
5555 case 1:
5556 v = qemu_get_byte(f);
5557 memset(buf, v, len);
5558 break;
5559 default:
5560 return -EINVAL;
5562 return 0;
5565 static int ram_load_v1(QEMUFile *f, void *opaque)
5567 int i, ret;
5569 if (qemu_get_be32(f) != phys_ram_size)
5570 return -EINVAL;
5571 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5572 #ifdef USE_KVM
5573 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5574 continue;
5575 #endif
5576 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5577 if (ret)
5578 return ret;
5580 return 0;
5583 #define BDRV_HASH_BLOCK_SIZE 1024
5584 #define IOBUF_SIZE 4096
5585 #define RAM_CBLOCK_MAGIC 0xfabe
5587 typedef struct RamCompressState {
5588 z_stream zstream;
5589 QEMUFile *f;
5590 uint8_t buf[IOBUF_SIZE];
5591 } RamCompressState;
5593 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5595 int ret;
5596 memset(s, 0, sizeof(*s));
5597 s->f = f;
5598 ret = deflateInit2(&s->zstream, 1,
5599 Z_DEFLATED, 15,
5600 9, Z_DEFAULT_STRATEGY);
5601 if (ret != Z_OK)
5602 return -1;
5603 s->zstream.avail_out = IOBUF_SIZE;
5604 s->zstream.next_out = s->buf;
5605 return 0;
5608 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5610 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5611 qemu_put_be16(s->f, len);
5612 qemu_put_buffer(s->f, buf, len);
5615 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5617 int ret;
5619 s->zstream.avail_in = len;
5620 s->zstream.next_in = (uint8_t *)buf;
5621 while (s->zstream.avail_in > 0) {
5622 ret = deflate(&s->zstream, Z_NO_FLUSH);
5623 if (ret != Z_OK)
5624 return -1;
5625 if (s->zstream.avail_out == 0) {
5626 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5627 s->zstream.avail_out = IOBUF_SIZE;
5628 s->zstream.next_out = s->buf;
5631 return 0;
5634 static void ram_compress_close(RamCompressState *s)
5636 int len, ret;
5638 /* compress last bytes */
5639 for(;;) {
5640 ret = deflate(&s->zstream, Z_FINISH);
5641 if (ret == Z_OK || ret == Z_STREAM_END) {
5642 len = IOBUF_SIZE - s->zstream.avail_out;
5643 if (len > 0) {
5644 ram_put_cblock(s, s->buf, len);
5646 s->zstream.avail_out = IOBUF_SIZE;
5647 s->zstream.next_out = s->buf;
5648 if (ret == Z_STREAM_END)
5649 break;
5650 } else {
5651 goto fail;
5654 fail:
5655 deflateEnd(&s->zstream);
5658 typedef struct RamDecompressState {
5659 z_stream zstream;
5660 QEMUFile *f;
5661 uint8_t buf[IOBUF_SIZE];
5662 } RamDecompressState;
5664 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5666 int ret;
5667 memset(s, 0, sizeof(*s));
5668 s->f = f;
5669 ret = inflateInit(&s->zstream);
5670 if (ret != Z_OK)
5671 return -1;
5672 return 0;
5675 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5677 int ret, clen;
5679 s->zstream.avail_out = len;
5680 s->zstream.next_out = buf;
5681 while (s->zstream.avail_out > 0) {
5682 if (s->zstream.avail_in == 0) {
5683 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5684 return -1;
5685 clen = qemu_get_be16(s->f);
5686 if (clen > IOBUF_SIZE)
5687 return -1;
5688 qemu_get_buffer(s->f, s->buf, clen);
5689 s->zstream.avail_in = clen;
5690 s->zstream.next_in = s->buf;
5692 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5693 if (ret != Z_OK && ret != Z_STREAM_END) {
5694 return -1;
5697 return 0;
5700 static void ram_decompress_close(RamDecompressState *s)
5702 inflateEnd(&s->zstream);
5705 static void ram_save_live(QEMUFile *f, void *opaque)
5707 target_ulong addr;
5709 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
5710 #ifdef USE_KVM
5711 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
5712 continue;
5713 #endif
5714 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
5715 qemu_put_be32(f, addr);
5716 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5719 qemu_put_be32(f, 1);
5722 static void ram_save_static(QEMUFile *f, void *opaque)
5724 int i;
5725 RamCompressState s1, *s = &s1;
5726 uint8_t buf[10];
5728 qemu_put_be32(f, phys_ram_size);
5729 if (ram_compress_open(s, f) < 0)
5730 return;
5731 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5732 #if 0
5733 if (tight_savevm_enabled) {
5734 int64_t sector_num;
5735 int j;
5737 /* find if the memory block is available on a virtual
5738 block device */
5739 sector_num = -1;
5740 for(j = 0; j < MAX_DISKS; j++) {
5741 if (bs_table[j]) {
5742 sector_num = bdrv_hash_find(bs_table[j],
5743 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5744 if (sector_num >= 0)
5745 break;
5748 if (j == MAX_DISKS)
5749 goto normal_compress;
5750 buf[0] = 1;
5751 buf[1] = j;
5752 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5753 ram_compress_buf(s, buf, 10);
5754 } else
5755 #endif
5757 // normal_compress:
5758 buf[0] = 0;
5759 ram_compress_buf(s, buf, 1);
5760 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5763 ram_compress_close(s);
5766 static void ram_save(QEMUFile *f, void *opaque)
5768 int in_migration = cpu_physical_memory_get_dirty_tracking();
5770 qemu_put_byte(f, in_migration);
5772 if (in_migration)
5773 ram_save_live(f, opaque);
5774 else
5775 ram_save_static(f, opaque);
5778 static int ram_load_live(QEMUFile *f, void *opaque)
5780 target_ulong addr;
5782 do {
5783 addr = qemu_get_be32(f);
5784 if (addr == 1)
5785 break;
5787 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5788 } while (1);
5790 return 0;
5793 static int ram_load_static(QEMUFile *f, void *opaque)
5795 RamDecompressState s1, *s = &s1;
5796 uint8_t buf[10];
5797 int i;
5799 if (qemu_get_be32(f) != phys_ram_size)
5800 return -EINVAL;
5801 if (ram_decompress_open(s, f) < 0)
5802 return -EINVAL;
5803 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5804 if (ram_decompress_buf(s, buf, 1) < 0) {
5805 fprintf(stderr, "Error while reading ram block header\n");
5806 goto error;
5808 if (buf[0] == 0) {
5809 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5810 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5811 goto error;
5813 } else
5814 #if 0
5815 if (buf[0] == 1) {
5816 int bs_index;
5817 int64_t sector_num;
5819 ram_decompress_buf(s, buf + 1, 9);
5820 bs_index = buf[1];
5821 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5822 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5823 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5824 goto error;
5826 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5827 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5828 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5829 bs_index, sector_num);
5830 goto error;
5832 } else
5833 #endif
5835 error:
5836 printf("Error block header\n");
5837 return -EINVAL;
5840 ram_decompress_close(s);
5841 return 0;
5844 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5846 int ret;
5848 switch (version_id) {
5849 case 1:
5850 ret = ram_load_v1(f, opaque);
5851 break;
5852 case 3:
5853 if (qemu_get_byte(f)) {
5854 ret = ram_load_live(f, opaque);
5855 break;
5857 case 2:
5858 ret = ram_load_static(f, opaque);
5859 break;
5860 default:
5861 ret = -EINVAL;
5862 break;
5865 return ret;
5868 /***********************************************************/
5869 /* bottom halves (can be seen as timers which expire ASAP) */
5871 struct QEMUBH {
5872 QEMUBHFunc *cb;
5873 void *opaque;
5874 int scheduled;
5875 QEMUBH *next;
5878 static QEMUBH *first_bh = NULL;
5880 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5882 QEMUBH *bh;
5883 bh = qemu_mallocz(sizeof(QEMUBH));
5884 if (!bh)
5885 return NULL;
5886 bh->cb = cb;
5887 bh->opaque = opaque;
5888 return bh;
5891 int qemu_bh_poll(void)
5893 QEMUBH *bh, **pbh;
5894 int ret;
5896 ret = 0;
5897 for(;;) {
5898 pbh = &first_bh;
5899 bh = *pbh;
5900 if (!bh)
5901 break;
5902 ret = 1;
5903 *pbh = bh->next;
5904 bh->scheduled = 0;
5905 bh->cb(bh->opaque);
5907 return ret;
5910 void qemu_bh_schedule(QEMUBH *bh)
5912 CPUState *env = cpu_single_env;
5913 if (bh->scheduled)
5914 return;
5915 bh->scheduled = 1;
5916 bh->next = first_bh;
5917 first_bh = bh;
5919 /* stop the currently executing CPU to execute the BH ASAP */
5920 if (env) {
5921 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5925 void qemu_bh_cancel(QEMUBH *bh)
5927 QEMUBH **pbh;
5928 if (bh->scheduled) {
5929 pbh = &first_bh;
5930 while (*pbh != bh)
5931 pbh = &(*pbh)->next;
5932 *pbh = bh->next;
5933 bh->scheduled = 0;
5937 void qemu_bh_delete(QEMUBH *bh)
5939 qemu_bh_cancel(bh);
5940 qemu_free(bh);
5943 /***********************************************************/
5944 /* machine registration */
5946 QEMUMachine *first_machine = NULL;
5948 int qemu_register_machine(QEMUMachine *m)
5950 QEMUMachine **pm;
5951 pm = &first_machine;
5952 while (*pm != NULL)
5953 pm = &(*pm)->next;
5954 m->next = NULL;
5955 *pm = m;
5956 return 0;
5959 QEMUMachine *find_machine(const char *name)
5961 QEMUMachine *m;
5963 for(m = first_machine; m != NULL; m = m->next) {
5964 if (!strcmp(m->name, name))
5965 return m;
5967 return NULL;
5970 /***********************************************************/
5971 /* main execution loop */
5973 void gui_update(void *opaque)
5975 display_state.dpy_refresh(&display_state);
5976 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5979 struct vm_change_state_entry {
5980 VMChangeStateHandler *cb;
5981 void *opaque;
5982 LIST_ENTRY (vm_change_state_entry) entries;
5985 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5987 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5988 void *opaque)
5990 VMChangeStateEntry *e;
5992 e = qemu_mallocz(sizeof (*e));
5993 if (!e)
5994 return NULL;
5996 e->cb = cb;
5997 e->opaque = opaque;
5998 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5999 return e;
6002 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6004 LIST_REMOVE (e, entries);
6005 qemu_free (e);
6008 static void vm_state_notify(int running)
6010 VMChangeStateEntry *e;
6012 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6013 e->cb(e->opaque, running);
6017 /* XXX: support several handlers */
6018 static VMStopHandler *vm_stop_cb;
6019 static void *vm_stop_opaque;
6021 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6023 vm_stop_cb = cb;
6024 vm_stop_opaque = opaque;
6025 return 0;
6028 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6030 vm_stop_cb = NULL;
6033 void vm_start(void)
6035 if (!vm_running) {
6036 cpu_enable_ticks();
6037 vm_running = 1;
6038 vm_state_notify(1);
6042 void vm_stop(int reason)
6044 if (vm_running) {
6045 cpu_disable_ticks();
6046 vm_running = 0;
6047 if (reason != 0) {
6048 if (vm_stop_cb) {
6049 vm_stop_cb(vm_stop_opaque, reason);
6052 vm_state_notify(0);
6056 /* reset/shutdown handler */
6058 typedef struct QEMUResetEntry {
6059 QEMUResetHandler *func;
6060 void *opaque;
6061 struct QEMUResetEntry *next;
6062 } QEMUResetEntry;
6064 static QEMUResetEntry *first_reset_entry;
6065 static int reset_requested;
6066 static int shutdown_requested;
6067 static int powerdown_requested;
6069 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6071 QEMUResetEntry **pre, *re;
6073 pre = &first_reset_entry;
6074 while (*pre != NULL)
6075 pre = &(*pre)->next;
6076 re = qemu_mallocz(sizeof(QEMUResetEntry));
6077 re->func = func;
6078 re->opaque = opaque;
6079 re->next = NULL;
6080 *pre = re;
6083 static void qemu_system_reset(void)
6085 QEMUResetEntry *re;
6087 /* reset all devices */
6088 for(re = first_reset_entry; re != NULL; re = re->next) {
6089 re->func(re->opaque);
6093 void qemu_system_reset_request(void)
6095 if (no_reboot) {
6096 shutdown_requested = 1;
6097 } else {
6098 reset_requested = 1;
6100 if (cpu_single_env)
6101 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6104 void qemu_system_shutdown_request(void)
6106 shutdown_requested = 1;
6107 if (cpu_single_env)
6108 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6111 void qemu_system_powerdown_request(void)
6113 powerdown_requested = 1;
6114 if (cpu_single_env)
6115 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6118 void main_loop_wait(int timeout)
6120 IOHandlerRecord *ioh, *ioh_next;
6121 fd_set rfds, wfds, xfds;
6122 int ret, nfds;
6123 struct timeval tv;
6124 PollingEntry *pe;
6127 /* XXX: need to suppress polling by better using win32 events */
6128 ret = 0;
6129 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6130 ret |= pe->func(pe->opaque);
6132 #ifdef _WIN32
6133 if (ret == 0 && timeout > 0) {
6134 int err;
6135 WaitObjects *w = &wait_objects;
6137 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6138 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6139 if (w->func[ret - WAIT_OBJECT_0])
6140 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6141 } else if (ret == WAIT_TIMEOUT) {
6142 } else {
6143 err = GetLastError();
6144 fprintf(stderr, "Wait error %d %d\n", ret, err);
6147 #endif
6148 /* poll any events */
6149 /* XXX: separate device handlers from system ones */
6150 nfds = -1;
6151 FD_ZERO(&rfds);
6152 FD_ZERO(&wfds);
6153 FD_ZERO(&xfds);
6154 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6155 if (ioh->fd_read &&
6156 (!ioh->fd_read_poll ||
6157 ioh->fd_read_poll(ioh->opaque) != 0)) {
6158 FD_SET(ioh->fd, &rfds);
6159 if (ioh->fd > nfds)
6160 nfds = ioh->fd;
6162 if (ioh->fd_write) {
6163 FD_SET(ioh->fd, &wfds);
6164 if (ioh->fd > nfds)
6165 nfds = ioh->fd;
6169 tv.tv_sec = 0;
6170 #ifdef _WIN32
6171 tv.tv_usec = 0;
6172 #else
6173 tv.tv_usec = timeout * 1000;
6174 #endif
6175 #if defined(CONFIG_SLIRP)
6176 if (slirp_inited) {
6177 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6179 #endif
6180 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6181 if (ret > 0) {
6182 /* XXX: better handling of removal */
6183 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
6184 ioh_next = ioh->next;
6185 if (FD_ISSET(ioh->fd, &rfds)) {
6186 ioh->fd_read(ioh->opaque);
6188 if (FD_ISSET(ioh->fd, &wfds)) {
6189 ioh->fd_write(ioh->opaque);
6193 #if defined(CONFIG_SLIRP)
6194 if (slirp_inited) {
6195 if (ret < 0) {
6196 FD_ZERO(&rfds);
6197 FD_ZERO(&wfds);
6198 FD_ZERO(&xfds);
6200 slirp_select_poll(&rfds, &wfds, &xfds);
6202 #endif
6203 qemu_aio_poll();
6204 qemu_bh_poll();
6206 if (vm_running) {
6207 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6208 qemu_get_clock(vm_clock));
6209 /* run dma transfers, if any */
6210 DMA_run();
6213 /* real time timers */
6214 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6215 qemu_get_clock(rt_clock));
6218 static CPUState *cur_cpu;
6220 int main_loop(void)
6222 int ret, timeout;
6223 #ifdef CONFIG_PROFILER
6224 int64_t ti;
6225 #endif
6226 CPUState *env;
6228 cur_cpu = first_cpu;
6229 for(;;) {
6230 if (vm_running) {
6232 env = cur_cpu;
6233 for(;;) {
6234 /* get next cpu */
6235 env = env->next_cpu;
6236 if (!env)
6237 env = first_cpu;
6238 #ifdef CONFIG_PROFILER
6239 ti = profile_getclock();
6240 #endif
6241 ret = cpu_exec(env);
6242 #ifdef CONFIG_PROFILER
6243 qemu_time += profile_getclock() - ti;
6244 #endif
6245 if (ret != EXCP_HALTED)
6246 break;
6247 /* all CPUs are halted ? */
6248 if (env == cur_cpu) {
6249 ret = EXCP_HLT;
6250 break;
6253 cur_cpu = env;
6255 if (shutdown_requested) {
6256 ret = EXCP_INTERRUPT;
6257 break;
6259 if (reset_requested) {
6260 reset_requested = 0;
6261 qemu_system_reset();
6262 #ifdef USE_KVM
6263 if (kvm_allowed)
6264 kvm_load_registers(env);
6265 #endif
6266 ret = EXCP_INTERRUPT;
6268 if (powerdown_requested) {
6269 powerdown_requested = 0;
6270 qemu_system_powerdown();
6271 ret = EXCP_INTERRUPT;
6273 if (ret == EXCP_DEBUG) {
6274 vm_stop(EXCP_DEBUG);
6276 /* if hlt instruction, we wait until the next IRQ */
6277 /* XXX: use timeout computed from timers */
6278 if (ret == EXCP_HLT)
6279 timeout = 10;
6280 else
6281 timeout = 0;
6282 } else {
6283 timeout = 10;
6285 #ifdef CONFIG_PROFILER
6286 ti = profile_getclock();
6287 #endif
6288 main_loop_wait(timeout);
6289 #ifdef CONFIG_PROFILER
6290 dev_time += profile_getclock() - ti;
6291 #endif
6293 cpu_disable_ticks();
6294 return ret;
6297 void help(void)
6299 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6300 "usage: %s [options] [disk_image]\n"
6301 "\n"
6302 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6303 "\n"
6304 "Standard options:\n"
6305 "-M machine select emulated machine (-M ? for list)\n"
6306 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6307 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6308 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6309 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6310 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6311 "-snapshot write to temporary files instead of disk image files\n"
6312 #ifdef CONFIG_SDL
6313 "-no-quit disable SDL window close capability\n"
6314 #endif
6315 #ifdef TARGET_I386
6316 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6317 #endif
6318 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6319 "-smp n set the number of CPUs to 'n' [default=1]\n"
6320 "-nographic disable graphical output and redirect serial I/Os to console\n"
6321 #ifndef _WIN32
6322 "-k language use keyboard layout (for example \"fr\" for French)\n"
6323 #endif
6324 #ifdef HAS_AUDIO
6325 "-audio-help print list of audio drivers and their options\n"
6326 "-soundhw c1,... enable audio support\n"
6327 " and only specified sound cards (comma separated list)\n"
6328 " use -soundhw ? to get the list of supported cards\n"
6329 " use -soundhw all to enable all of them\n"
6330 #endif
6331 "-localtime set the real time clock to local time [default=utc]\n"
6332 "-full-screen start in full screen\n"
6333 #ifdef TARGET_I386
6334 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6335 #endif
6336 "-usb enable the USB driver (will be the default soon)\n"
6337 "-usbdevice name add the host or guest USB device 'name'\n"
6338 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6339 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6340 #endif
6341 "\n"
6342 "Network options:\n"
6343 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6344 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6345 #ifdef CONFIG_SLIRP
6346 "-net user[,vlan=n][,hostname=host]\n"
6347 " connect the user mode network stack to VLAN 'n' and send\n"
6348 " hostname 'host' to DHCP clients\n"
6349 #endif
6350 #ifdef _WIN32
6351 "-net tap[,vlan=n],ifname=name\n"
6352 " connect the host TAP network interface to VLAN 'n'\n"
6353 #else
6354 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6355 " connect the host TAP network interface to VLAN 'n' and use\n"
6356 " the network script 'file' (default=%s);\n"
6357 " use 'script=no' to disable script execution;\n"
6358 " use 'fd=h' to connect to an already opened TAP interface\n"
6359 #endif
6360 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6361 " connect the vlan 'n' to another VLAN using a socket connection\n"
6362 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6363 " connect the vlan 'n' to multicast maddr and port\n"
6364 "-net none use it alone to have zero network devices; if no -net option\n"
6365 " is provided, the default is '-net nic -net user'\n"
6366 "\n"
6367 #ifdef CONFIG_SLIRP
6368 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6369 #ifndef _WIN32
6370 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6371 #endif
6372 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6373 " redirect TCP or UDP connections from host to guest [-net user]\n"
6374 #endif
6375 "\n"
6376 "Linux boot specific:\n"
6377 "-kernel bzImage use 'bzImage' as kernel image\n"
6378 "-append cmdline use 'cmdline' as kernel command line\n"
6379 "-initrd file use 'file' as initial ram disk\n"
6380 "\n"
6381 "Debug/Expert options:\n"
6382 "-monitor dev redirect the monitor to char device 'dev'\n"
6383 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6384 "-serial dev redirect the serial port to char device 'dev'\n"
6385 "-parallel dev redirect the parallel port to char device 'dev'\n"
6386 "-pidfile file Write PID to 'file'\n"
6387 "-S freeze CPU at startup (use 'c' to start execution)\n"
6388 "-s wait gdb connection to port %d\n"
6389 "-p port change gdb connection port\n"
6390 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6391 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6392 " translation (t=none or lba) (usually qemu can guess them)\n"
6393 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6394 #ifdef USE_KQEMU
6395 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6396 "-no-kqemu disable KQEMU kernel module usage\n"
6397 #endif
6398 #ifdef USE_KVM
6399 "-no-kvm disable KVM hardware virtualization\n"
6400 #endif
6401 #ifdef USE_CODE_COPY
6402 "-no-code-copy disable code copy acceleration\n"
6403 #endif
6404 #ifdef TARGET_I386
6405 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6406 " (default is CL-GD5446 PCI VGA)\n"
6407 "-no-acpi disable ACPI\n"
6408 #endif
6409 "-no-reboot exit instead of rebooting\n"
6410 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6411 "-vnc display start a VNC server on display\n"
6412 #ifndef _WIN32
6413 "-daemonize daemonize QEMU after initializing\n"
6414 #endif
6415 "-option-rom rom load a file, rom, into the option ROM space\n"
6416 "\n"
6417 "During emulation, the following keys are useful:\n"
6418 "ctrl-alt-f toggle full screen\n"
6419 "ctrl-alt-n switch to virtual console 'n'\n"
6420 "ctrl-alt toggle mouse and keyboard grab\n"
6421 "\n"
6422 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6424 "qemu",
6425 DEFAULT_RAM_SIZE,
6426 #ifndef _WIN32
6427 DEFAULT_NETWORK_SCRIPT,
6428 #endif
6429 DEFAULT_GDBSTUB_PORT,
6430 "/tmp/qemu.log");
6431 exit(1);
6434 #define HAS_ARG 0x0001
6436 enum {
6437 QEMU_OPTION_h,
6439 QEMU_OPTION_M,
6440 QEMU_OPTION_fda,
6441 QEMU_OPTION_fdb,
6442 QEMU_OPTION_hda,
6443 QEMU_OPTION_hdb,
6444 QEMU_OPTION_hdc,
6445 QEMU_OPTION_hdd,
6446 QEMU_OPTION_cdrom,
6447 QEMU_OPTION_boot,
6448 QEMU_OPTION_snapshot,
6449 #ifdef TARGET_I386
6450 QEMU_OPTION_no_fd_bootchk,
6451 #endif
6452 QEMU_OPTION_m,
6453 QEMU_OPTION_nographic,
6454 #ifdef HAS_AUDIO
6455 QEMU_OPTION_audio_help,
6456 QEMU_OPTION_soundhw,
6457 #endif
6459 QEMU_OPTION_net,
6460 QEMU_OPTION_tftp,
6461 QEMU_OPTION_smb,
6462 QEMU_OPTION_redir,
6464 QEMU_OPTION_kernel,
6465 QEMU_OPTION_append,
6466 QEMU_OPTION_initrd,
6468 QEMU_OPTION_S,
6469 QEMU_OPTION_s,
6470 QEMU_OPTION_p,
6471 QEMU_OPTION_d,
6472 QEMU_OPTION_hdachs,
6473 QEMU_OPTION_L,
6474 QEMU_OPTION_no_code_copy,
6475 QEMU_OPTION_k,
6476 QEMU_OPTION_localtime,
6477 QEMU_OPTION_cirrusvga,
6478 QEMU_OPTION_g,
6479 QEMU_OPTION_std_vga,
6480 QEMU_OPTION_monitor,
6481 QEMU_OPTION_vmchannel,
6482 QEMU_OPTION_serial,
6483 QEMU_OPTION_parallel,
6484 QEMU_OPTION_loadvm,
6485 QEMU_OPTION_full_screen,
6486 QEMU_OPTION_no_quit,
6487 QEMU_OPTION_pidfile,
6488 QEMU_OPTION_no_kqemu,
6489 QEMU_OPTION_kernel_kqemu,
6490 QEMU_OPTION_win2k_hack,
6491 QEMU_OPTION_usb,
6492 QEMU_OPTION_usbdevice,
6493 QEMU_OPTION_smp,
6494 QEMU_OPTION_vnc,
6495 QEMU_OPTION_no_acpi,
6496 QEMU_OPTION_no_kvm,
6497 QEMU_OPTION_no_reboot,
6498 QEMU_OPTION_daemonize,
6499 QEMU_OPTION_option_rom,
6500 QEMU_OPTION_semihosting,
6501 QEMU_OPTION_incoming,
6504 typedef struct QEMUOption {
6505 const char *name;
6506 int flags;
6507 int index;
6508 } QEMUOption;
6510 const QEMUOption qemu_options[] = {
6511 { "h", 0, QEMU_OPTION_h },
6512 { "help", 0, QEMU_OPTION_h },
6514 { "M", HAS_ARG, QEMU_OPTION_M },
6515 { "fda", HAS_ARG, QEMU_OPTION_fda },
6516 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6517 { "hda", HAS_ARG, QEMU_OPTION_hda },
6518 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6519 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6520 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6521 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6522 { "boot", HAS_ARG, QEMU_OPTION_boot },
6523 { "snapshot", 0, QEMU_OPTION_snapshot },
6524 #ifdef TARGET_I386
6525 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6526 #endif
6527 { "m", HAS_ARG, QEMU_OPTION_m },
6528 { "nographic", 0, QEMU_OPTION_nographic },
6529 { "k", HAS_ARG, QEMU_OPTION_k },
6530 #ifdef HAS_AUDIO
6531 { "audio-help", 0, QEMU_OPTION_audio_help },
6532 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6533 #endif
6535 { "net", HAS_ARG, QEMU_OPTION_net},
6536 #ifdef CONFIG_SLIRP
6537 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6538 #ifndef _WIN32
6539 { "smb", HAS_ARG, QEMU_OPTION_smb },
6540 #endif
6541 { "redir", HAS_ARG, QEMU_OPTION_redir },
6542 #endif
6544 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6545 { "append", HAS_ARG, QEMU_OPTION_append },
6546 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6548 { "S", 0, QEMU_OPTION_S },
6549 { "s", 0, QEMU_OPTION_s },
6550 { "p", HAS_ARG, QEMU_OPTION_p },
6551 { "d", HAS_ARG, QEMU_OPTION_d },
6552 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6553 { "L", HAS_ARG, QEMU_OPTION_L },
6554 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6555 #ifdef USE_KQEMU
6556 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6557 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6558 #endif
6559 #ifdef USE_KVM
6560 { "no-kvm", 0, QEMU_OPTION_no_kvm },
6561 #endif
6562 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6563 { "g", 1, QEMU_OPTION_g },
6564 #endif
6565 { "localtime", 0, QEMU_OPTION_localtime },
6566 { "std-vga", 0, QEMU_OPTION_std_vga },
6567 { "monitor", 1, QEMU_OPTION_monitor },
6568 { "vmchannel", 1, QEMU_OPTION_vmchannel },
6569 { "serial", 1, QEMU_OPTION_serial },
6570 { "parallel", 1, QEMU_OPTION_parallel },
6571 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6572 { "incoming", 1, QEMU_OPTION_incoming },
6573 { "full-screen", 0, QEMU_OPTION_full_screen },
6574 #ifdef CONFIG_SDL
6575 { "no-quit", 0, QEMU_OPTION_no_quit },
6576 #endif
6577 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6578 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6579 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6580 { "smp", HAS_ARG, QEMU_OPTION_smp },
6581 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6583 /* temporary options */
6584 { "usb", 0, QEMU_OPTION_usb },
6585 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6586 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6587 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6588 { "daemonize", 0, QEMU_OPTION_daemonize },
6589 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6590 #if defined(TARGET_ARM)
6591 { "semihosting", 0, QEMU_OPTION_semihosting },
6592 #endif
6593 { NULL },
6596 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6598 /* this stack is only used during signal handling */
6599 #define SIGNAL_STACK_SIZE 32768
6601 static uint8_t *signal_stack;
6603 #endif
6605 /* password input */
6607 static BlockDriverState *get_bdrv(int index)
6609 BlockDriverState *bs;
6611 if (index < 4) {
6612 bs = bs_table[index];
6613 } else if (index < 6) {
6614 bs = fd_table[index - 4];
6615 } else {
6616 bs = NULL;
6618 return bs;
6621 static void read_passwords(void)
6623 BlockDriverState *bs;
6624 int i, j;
6625 char password[256];
6627 for(i = 0; i < 6; i++) {
6628 bs = get_bdrv(i);
6629 if (bs && bdrv_is_encrypted(bs)) {
6630 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6631 for(j = 0; j < 3; j++) {
6632 monitor_readline("Password: ",
6633 1, password, sizeof(password));
6634 if (bdrv_set_key(bs, password) == 0)
6635 break;
6636 term_printf("invalid password\n");
6642 /* XXX: currently we cannot use simultaneously different CPUs */
6643 void register_machines(void)
6645 #if defined(TARGET_I386)
6646 qemu_register_machine(&pc_machine);
6647 qemu_register_machine(&isapc_machine);
6648 #elif defined(TARGET_PPC)
6649 qemu_register_machine(&heathrow_machine);
6650 qemu_register_machine(&core99_machine);
6651 qemu_register_machine(&prep_machine);
6652 #elif defined(TARGET_MIPS)
6653 qemu_register_machine(&mips_machine);
6654 qemu_register_machine(&mips_malta_machine);
6655 #elif defined(TARGET_SPARC)
6656 #ifdef TARGET_SPARC64
6657 qemu_register_machine(&sun4u_machine);
6658 #else
6659 qemu_register_machine(&sun4m_machine);
6660 #endif
6661 #elif defined(TARGET_ARM)
6662 qemu_register_machine(&integratorcp926_machine);
6663 qemu_register_machine(&integratorcp1026_machine);
6664 qemu_register_machine(&versatilepb_machine);
6665 qemu_register_machine(&versatileab_machine);
6666 qemu_register_machine(&realview_machine);
6667 #elif defined(TARGET_SH4)
6668 qemu_register_machine(&shix_machine);
6669 #else
6670 #error unsupported CPU
6671 #endif
6674 #ifdef HAS_AUDIO
6675 struct soundhw soundhw[] = {
6676 #ifdef TARGET_I386
6678 "pcspk",
6679 "PC speaker",
6682 { .init_isa = pcspk_audio_init }
6684 #endif
6686 "sb16",
6687 "Creative Sound Blaster 16",
6690 { .init_isa = SB16_init }
6693 #ifdef CONFIG_ADLIB
6695 "adlib",
6696 #ifdef HAS_YMF262
6697 "Yamaha YMF262 (OPL3)",
6698 #else
6699 "Yamaha YM3812 (OPL2)",
6700 #endif
6703 { .init_isa = Adlib_init }
6705 #endif
6707 #ifdef CONFIG_GUS
6709 "gus",
6710 "Gravis Ultrasound GF1",
6713 { .init_isa = GUS_init }
6715 #endif
6718 "es1370",
6719 "ENSONIQ AudioPCI ES1370",
6722 { .init_pci = es1370_init }
6725 { NULL, NULL, 0, 0, { NULL } }
6728 static void select_soundhw (const char *optarg)
6730 struct soundhw *c;
6732 if (*optarg == '?') {
6733 show_valid_cards:
6735 printf ("Valid sound card names (comma separated):\n");
6736 for (c = soundhw; c->name; ++c) {
6737 printf ("%-11s %s\n", c->name, c->descr);
6739 printf ("\n-soundhw all will enable all of the above\n");
6740 exit (*optarg != '?');
6742 else {
6743 size_t l;
6744 const char *p;
6745 char *e;
6746 int bad_card = 0;
6748 if (!strcmp (optarg, "all")) {
6749 for (c = soundhw; c->name; ++c) {
6750 c->enabled = 1;
6752 return;
6755 p = optarg;
6756 while (*p) {
6757 e = strchr (p, ',');
6758 l = !e ? strlen (p) : (size_t) (e - p);
6760 for (c = soundhw; c->name; ++c) {
6761 if (!strncmp (c->name, p, l)) {
6762 c->enabled = 1;
6763 break;
6767 if (!c->name) {
6768 if (l > 80) {
6769 fprintf (stderr,
6770 "Unknown sound card name (too big to show)\n");
6772 else {
6773 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6774 (int) l, p);
6776 bad_card = 1;
6778 p += l + (e != NULL);
6781 if (bad_card)
6782 goto show_valid_cards;
6785 #endif
6787 #ifdef _WIN32
6788 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6790 exit(STATUS_CONTROL_C_EXIT);
6791 return TRUE;
6793 #endif
6795 #define MAX_NET_CLIENTS 32
6797 static int saved_argc;
6798 static char **saved_argv;
6800 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
6802 *argc = saved_argc;
6803 *argv = saved_argv;
6804 *opt_daemonize = daemonize;
6805 *opt_incoming = incoming;
6808 int main(int argc, char **argv)
6810 #ifdef CONFIG_GDBSTUB
6811 int use_gdbstub, gdbstub_port;
6812 #endif
6813 int i, cdrom_index;
6814 int snapshot, linux_boot;
6815 const char *initrd_filename;
6816 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6817 const char *kernel_filename, *kernel_cmdline;
6818 DisplayState *ds = &display_state;
6819 int cyls, heads, secs, translation;
6820 char net_clients[MAX_NET_CLIENTS][256];
6821 int nb_net_clients;
6822 int optind;
6823 const char *r, *optarg;
6824 CharDriverState *monitor_hd;
6825 char monitor_device[128];
6826 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
6827 int vmchannel_device_index;
6828 char serial_devices[MAX_SERIAL_PORTS][128];
6829 int serial_device_index;
6830 char parallel_devices[MAX_PARALLEL_PORTS][128];
6831 int parallel_device_index;
6832 const char *loadvm = NULL;
6833 QEMUMachine *machine;
6834 char usb_devices[MAX_USB_CMDLINE][128];
6835 int usb_devices_index;
6836 int fds[2];
6838 saved_argc = argc;
6839 saved_argv = argv;
6841 LIST_INIT (&vm_change_state_head);
6842 #ifndef _WIN32
6844 struct sigaction act;
6845 sigfillset(&act.sa_mask);
6846 act.sa_flags = 0;
6847 act.sa_handler = SIG_IGN;
6848 sigaction(SIGPIPE, &act, NULL);
6850 #else
6851 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6852 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6853 QEMU to run on a single CPU */
6855 HANDLE h;
6856 DWORD mask, smask;
6857 int i;
6858 h = GetCurrentProcess();
6859 if (GetProcessAffinityMask(h, &mask, &smask)) {
6860 for(i = 0; i < 32; i++) {
6861 if (mask & (1 << i))
6862 break;
6864 if (i != 32) {
6865 mask = 1 << i;
6866 SetProcessAffinityMask(h, mask);
6870 #endif
6872 register_machines();
6873 machine = first_machine;
6874 initrd_filename = NULL;
6875 for(i = 0; i < MAX_FD; i++)
6876 fd_filename[i] = NULL;
6877 for(i = 0; i < MAX_DISKS; i++)
6878 hd_filename[i] = NULL;
6879 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6880 vga_ram_size = VGA_RAM_SIZE;
6881 bios_size = BIOS_SIZE;
6882 #ifdef CONFIG_GDBSTUB
6883 use_gdbstub = 0;
6884 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6885 #endif
6886 snapshot = 0;
6887 nographic = 0;
6888 kernel_filename = NULL;
6889 kernel_cmdline = "";
6890 #ifdef TARGET_PPC
6891 cdrom_index = 1;
6892 #else
6893 cdrom_index = 2;
6894 #endif
6895 cyls = heads = secs = 0;
6896 translation = BIOS_ATA_TRANSLATION_AUTO;
6897 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6899 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
6900 vmchannel_devices[i][0] = '\0';
6901 vmchannel_device_index = 0;
6903 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6904 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6905 serial_devices[i][0] = '\0';
6906 serial_device_index = 0;
6908 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6909 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6910 parallel_devices[i][0] = '\0';
6911 parallel_device_index = 0;
6913 usb_devices_index = 0;
6915 nb_net_clients = 0;
6917 nb_nics = 0;
6918 /* default mac address of the first network interface */
6920 optind = 1;
6921 for(;;) {
6922 if (optind >= argc)
6923 break;
6924 r = argv[optind];
6925 if (r[0] != '-') {
6926 hd_filename[0] = argv[optind++];
6927 } else {
6928 const QEMUOption *popt;
6930 optind++;
6931 /* Treat --foo the same as -foo. */
6932 if (r[1] == '-')
6933 r++;
6934 popt = qemu_options;
6935 for(;;) {
6936 if (!popt->name) {
6937 fprintf(stderr, "%s: invalid option -- '%s'\n",
6938 argv[0], r);
6939 exit(1);
6941 if (!strcmp(popt->name, r + 1))
6942 break;
6943 popt++;
6945 if (popt->flags & HAS_ARG) {
6946 if (optind >= argc) {
6947 fprintf(stderr, "%s: option '%s' requires an argument\n",
6948 argv[0], r);
6949 exit(1);
6951 optarg = argv[optind++];
6952 } else {
6953 optarg = NULL;
6956 switch(popt->index) {
6957 case QEMU_OPTION_M:
6958 machine = find_machine(optarg);
6959 if (!machine) {
6960 QEMUMachine *m;
6961 printf("Supported machines are:\n");
6962 for(m = first_machine; m != NULL; m = m->next) {
6963 printf("%-10s %s%s\n",
6964 m->name, m->desc,
6965 m == first_machine ? " (default)" : "");
6967 exit(1);
6969 break;
6970 case QEMU_OPTION_initrd:
6971 initrd_filename = optarg;
6972 break;
6973 case QEMU_OPTION_hda:
6974 case QEMU_OPTION_hdb:
6975 case QEMU_OPTION_hdc:
6976 case QEMU_OPTION_hdd:
6978 int hd_index;
6979 hd_index = popt->index - QEMU_OPTION_hda;
6980 hd_filename[hd_index] = optarg;
6981 if (hd_index == cdrom_index)
6982 cdrom_index = -1;
6984 break;
6985 case QEMU_OPTION_snapshot:
6986 snapshot = 1;
6987 break;
6988 case QEMU_OPTION_hdachs:
6990 const char *p;
6991 p = optarg;
6992 cyls = strtol(p, (char **)&p, 0);
6993 if (cyls < 1 || cyls > 16383)
6994 goto chs_fail;
6995 if (*p != ',')
6996 goto chs_fail;
6997 p++;
6998 heads = strtol(p, (char **)&p, 0);
6999 if (heads < 1 || heads > 16)
7000 goto chs_fail;
7001 if (*p != ',')
7002 goto chs_fail;
7003 p++;
7004 secs = strtol(p, (char **)&p, 0);
7005 if (secs < 1 || secs > 63)
7006 goto chs_fail;
7007 if (*p == ',') {
7008 p++;
7009 if (!strcmp(p, "none"))
7010 translation = BIOS_ATA_TRANSLATION_NONE;
7011 else if (!strcmp(p, "lba"))
7012 translation = BIOS_ATA_TRANSLATION_LBA;
7013 else if (!strcmp(p, "auto"))
7014 translation = BIOS_ATA_TRANSLATION_AUTO;
7015 else
7016 goto chs_fail;
7017 } else if (*p != '\0') {
7018 chs_fail:
7019 fprintf(stderr, "qemu: invalid physical CHS format\n");
7020 exit(1);
7023 break;
7024 case QEMU_OPTION_nographic:
7025 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7026 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7027 nographic = 1;
7028 break;
7029 case QEMU_OPTION_kernel:
7030 kernel_filename = optarg;
7031 break;
7032 case QEMU_OPTION_append:
7033 kernel_cmdline = optarg;
7034 break;
7035 case QEMU_OPTION_cdrom:
7036 if (cdrom_index >= 0) {
7037 hd_filename[cdrom_index] = optarg;
7039 break;
7040 case QEMU_OPTION_boot:
7041 boot_device = optarg[0];
7042 if (boot_device != 'a' &&
7043 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7044 // Network boot
7045 boot_device != 'n' &&
7046 #endif
7047 boot_device != 'c' && boot_device != 'd') {
7048 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7049 exit(1);
7051 break;
7052 case QEMU_OPTION_fda:
7053 fd_filename[0] = optarg;
7054 break;
7055 case QEMU_OPTION_fdb:
7056 fd_filename[1] = optarg;
7057 break;
7058 #ifdef TARGET_I386
7059 case QEMU_OPTION_no_fd_bootchk:
7060 fd_bootchk = 0;
7061 break;
7062 #endif
7063 case QEMU_OPTION_no_code_copy:
7064 code_copy_enabled = 0;
7065 break;
7066 case QEMU_OPTION_net:
7067 if (nb_net_clients >= MAX_NET_CLIENTS) {
7068 fprintf(stderr, "qemu: too many network clients\n");
7069 exit(1);
7071 pstrcpy(net_clients[nb_net_clients],
7072 sizeof(net_clients[0]),
7073 optarg);
7074 nb_net_clients++;
7075 break;
7076 #ifdef CONFIG_SLIRP
7077 case QEMU_OPTION_tftp:
7078 tftp_prefix = optarg;
7079 break;
7080 #ifndef _WIN32
7081 case QEMU_OPTION_smb:
7082 net_slirp_smb(optarg);
7083 break;
7084 #endif
7085 case QEMU_OPTION_redir:
7086 net_slirp_redir(optarg);
7087 break;
7088 #endif
7089 #ifdef HAS_AUDIO
7090 case QEMU_OPTION_audio_help:
7091 AUD_help ();
7092 exit (0);
7093 break;
7094 case QEMU_OPTION_soundhw:
7095 select_soundhw (optarg);
7096 break;
7097 #endif
7098 case QEMU_OPTION_h:
7099 help();
7100 break;
7101 case QEMU_OPTION_m:
7102 ram_size = atoi(optarg) * 1024 * 1024;
7103 if (ram_size <= 0)
7104 help();
7105 if (ram_size > PHYS_RAM_MAX_SIZE) {
7106 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7107 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7108 exit(1);
7110 break;
7111 case QEMU_OPTION_d:
7113 int mask;
7114 CPULogItem *item;
7116 mask = cpu_str_to_log_mask(optarg);
7117 if (!mask) {
7118 printf("Log items (comma separated):\n");
7119 for(item = cpu_log_items; item->mask != 0; item++) {
7120 printf("%-10s %s\n", item->name, item->help);
7122 exit(1);
7124 cpu_set_log(mask);
7126 break;
7127 #ifdef CONFIG_GDBSTUB
7128 case QEMU_OPTION_s:
7129 use_gdbstub = 1;
7130 break;
7131 case QEMU_OPTION_p:
7132 gdbstub_port = atoi(optarg);
7133 break;
7134 #endif
7135 case QEMU_OPTION_L:
7136 bios_dir = optarg;
7137 break;
7138 case QEMU_OPTION_S:
7139 autostart = 0;
7140 break;
7141 case QEMU_OPTION_k:
7142 keyboard_layout = optarg;
7143 break;
7144 case QEMU_OPTION_localtime:
7145 rtc_utc = 0;
7146 break;
7147 case QEMU_OPTION_cirrusvga:
7148 cirrus_vga_enabled = 1;
7149 break;
7150 case QEMU_OPTION_std_vga:
7151 cirrus_vga_enabled = 0;
7152 break;
7153 case QEMU_OPTION_g:
7155 const char *p;
7156 int w, h, depth;
7157 p = optarg;
7158 w = strtol(p, (char **)&p, 10);
7159 if (w <= 0) {
7160 graphic_error:
7161 fprintf(stderr, "qemu: invalid resolution or depth\n");
7162 exit(1);
7164 if (*p != 'x')
7165 goto graphic_error;
7166 p++;
7167 h = strtol(p, (char **)&p, 10);
7168 if (h <= 0)
7169 goto graphic_error;
7170 if (*p == 'x') {
7171 p++;
7172 depth = strtol(p, (char **)&p, 10);
7173 if (depth != 8 && depth != 15 && depth != 16 &&
7174 depth != 24 && depth != 32)
7175 goto graphic_error;
7176 } else if (*p == '\0') {
7177 depth = graphic_depth;
7178 } else {
7179 goto graphic_error;
7182 graphic_width = w;
7183 graphic_height = h;
7184 graphic_depth = depth;
7186 break;
7187 case QEMU_OPTION_monitor:
7188 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7189 break;
7190 case QEMU_OPTION_vmchannel:
7191 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7192 fprintf(stderr, "qemu: too many vmchannel devices\n");
7193 exit(1);
7195 pstrcpy(vmchannel_devices[vmchannel_device_index],
7196 sizeof(vmchannel_devices[0]), optarg);
7197 vmchannel_device_index++;
7198 break;
7199 case QEMU_OPTION_serial:
7200 if (serial_device_index >= MAX_SERIAL_PORTS) {
7201 fprintf(stderr, "qemu: too many serial ports\n");
7202 exit(1);
7204 pstrcpy(serial_devices[serial_device_index],
7205 sizeof(serial_devices[0]), optarg);
7206 serial_device_index++;
7207 break;
7208 case QEMU_OPTION_parallel:
7209 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7210 fprintf(stderr, "qemu: too many parallel ports\n");
7211 exit(1);
7213 pstrcpy(parallel_devices[parallel_device_index],
7214 sizeof(parallel_devices[0]), optarg);
7215 parallel_device_index++;
7216 break;
7217 case QEMU_OPTION_loadvm:
7218 loadvm = optarg;
7219 break;
7220 case QEMU_OPTION_incoming:
7221 incoming = optarg;
7222 break;
7223 case QEMU_OPTION_full_screen:
7224 full_screen = 1;
7225 break;
7226 #ifdef CONFIG_SDL
7227 case QEMU_OPTION_no_quit:
7228 no_quit = 1;
7229 break;
7230 #endif
7231 case QEMU_OPTION_pidfile:
7232 create_pidfile(optarg);
7233 break;
7234 #ifdef TARGET_I386
7235 case QEMU_OPTION_win2k_hack:
7236 win2k_install_hack = 1;
7237 break;
7238 #endif
7239 #ifdef USE_KQEMU
7240 case QEMU_OPTION_no_kqemu:
7241 kqemu_allowed = 0;
7242 break;
7243 case QEMU_OPTION_kernel_kqemu:
7244 kqemu_allowed = 2;
7245 break;
7246 #endif
7247 #ifdef USE_KVM
7248 case QEMU_OPTION_no_kvm:
7249 kvm_allowed = 0;
7250 break;
7251 #endif
7252 case QEMU_OPTION_usb:
7253 usb_enabled = 1;
7254 break;
7255 case QEMU_OPTION_usbdevice:
7256 usb_enabled = 1;
7257 if (usb_devices_index >= MAX_USB_CMDLINE) {
7258 fprintf(stderr, "Too many USB devices\n");
7259 exit(1);
7261 pstrcpy(usb_devices[usb_devices_index],
7262 sizeof(usb_devices[usb_devices_index]),
7263 optarg);
7264 usb_devices_index++;
7265 break;
7266 case QEMU_OPTION_smp:
7267 smp_cpus = atoi(optarg);
7268 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7269 fprintf(stderr, "Invalid number of CPUs\n");
7270 exit(1);
7272 break;
7273 case QEMU_OPTION_vnc:
7274 vnc_display = optarg;
7275 break;
7276 case QEMU_OPTION_no_acpi:
7277 acpi_enabled = 0;
7278 break;
7279 case QEMU_OPTION_no_reboot:
7280 no_reboot = 1;
7281 break;
7282 case QEMU_OPTION_daemonize:
7283 daemonize = 1;
7284 break;
7285 case QEMU_OPTION_option_rom:
7286 if (nb_option_roms >= MAX_OPTION_ROMS) {
7287 fprintf(stderr, "Too many option ROMs\n");
7288 exit(1);
7290 option_rom[nb_option_roms] = optarg;
7291 nb_option_roms++;
7292 break;
7293 case QEMU_OPTION_semihosting:
7294 semihosting_enabled = 1;
7295 break;
7300 #ifndef _WIN32
7301 if (daemonize) {
7302 pid_t pid;
7304 if (pipe(fds) == -1)
7305 exit(1);
7307 pid = fork();
7308 if (pid > 0) {
7309 uint8_t status;
7310 ssize_t len;
7312 close(fds[1]);
7314 again:
7315 len = read(fds[0], &status, 1);
7316 if (len == -1 && (errno == EINTR))
7317 goto again;
7319 if (len != 1 || status != 0)
7320 exit(1);
7321 else
7322 exit(0);
7323 } else if (pid < 0)
7324 exit(1);
7326 setsid();
7328 pid = fork();
7329 if (pid > 0)
7330 exit(0);
7331 else if (pid < 0)
7332 exit(1);
7334 umask(027);
7336 signal(SIGTSTP, SIG_IGN);
7337 signal(SIGTTOU, SIG_IGN);
7338 signal(SIGTTIN, SIG_IGN);
7340 #endif
7342 #if USE_KVM
7343 if (kvm_allowed) {
7344 if (kvm_qemu_init() < 0) {
7345 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
7346 kvm_allowed = 0;
7349 #endif
7351 #ifdef USE_KQEMU
7352 if (smp_cpus > 1)
7353 kqemu_allowed = 0;
7354 #endif
7355 linux_boot = (kernel_filename != NULL);
7357 if (!linux_boot &&
7358 hd_filename[0] == '\0' &&
7359 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7360 fd_filename[0] == '\0')
7361 help();
7363 /* boot to floppy or the default cd if no hard disk defined yet */
7364 if (hd_filename[0] == '\0' && boot_device == 'c') {
7365 if (fd_filename[0] != '\0')
7366 boot_device = 'a';
7367 else
7368 boot_device = 'd';
7371 setvbuf(stdout, NULL, _IOLBF, 0);
7373 init_timers();
7374 init_timer_alarm();
7375 qemu_aio_init();
7377 #ifdef _WIN32
7378 socket_init();
7379 #endif
7381 /* init network clients */
7382 if (nb_net_clients == 0) {
7383 /* if no clients, we use a default config */
7384 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7385 "nic");
7386 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7387 "user");
7388 nb_net_clients = 2;
7391 for(i = 0;i < nb_net_clients; i++) {
7392 if (net_client_init(net_clients[i]) < 0)
7393 exit(1);
7396 #ifdef TARGET_I386
7397 if (boot_device == 'n') {
7398 for (i = 0; i < nb_nics; i++) {
7399 const char *model = nd_table[i].model;
7400 char buf[1024];
7401 if (model == NULL)
7402 model = "ne2k_pci";
7403 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7404 if (get_image_size(buf) > 0) {
7405 option_rom[nb_option_roms] = strdup(buf);
7406 nb_option_roms++;
7407 break;
7410 if (i == nb_nics) {
7411 fprintf(stderr, "No valid PXE rom found for network device\n");
7412 exit(1);
7414 boot_device = 'c'; /* to prevent confusion by the BIOS */
7416 #endif
7418 /* init the memory */
7419 phys_ram_size = ram_size + vga_ram_size + bios_size;
7422 for (i = 0; i < nb_option_roms; i++) {
7423 int ret = get_image_size(option_rom[i]);
7424 if (ret == -1) {
7425 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7426 exit(1);
7428 phys_ram_size += ret;
7431 #if USE_KVM
7432 /* Initialize kvm */
7433 if (kvm_allowed) {
7434 phys_ram_size += KVM_EXTRA_PAGES * 4096;
7435 if (kvm_qemu_create_context() < 0) {
7436 fprintf(stderr, "Could not create KVM context\n");
7437 exit(1);
7439 } else {
7440 phys_ram_base = qemu_vmalloc(phys_ram_size);
7441 if (!phys_ram_base) {
7442 fprintf(stderr, "Could not allocate physical memory\n");
7443 exit(1);
7446 #else
7447 phys_ram_base = qemu_vmalloc(phys_ram_size);
7448 if (!phys_ram_base) {
7449 fprintf(stderr, "Could not allocate physical memory\n");
7450 exit(1);
7452 #endif
7454 /* we always create the cdrom drive, even if no disk is there */
7455 bdrv_init();
7456 if (cdrom_index >= 0) {
7457 bs_table[cdrom_index] = bdrv_new("cdrom");
7458 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7461 /* open the virtual block devices */
7462 for(i = 0; i < MAX_DISKS; i++) {
7463 if (hd_filename[i]) {
7464 if (!bs_table[i]) {
7465 char buf[64];
7466 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7467 bs_table[i] = bdrv_new(buf);
7469 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7470 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7471 hd_filename[i]);
7472 exit(1);
7474 if (i == 0 && cyls != 0) {
7475 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7476 bdrv_set_translation_hint(bs_table[i], translation);
7481 /* we always create at least one floppy disk */
7482 fd_table[0] = bdrv_new("fda");
7483 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7485 for(i = 0; i < MAX_FD; i++) {
7486 if (fd_filename[i]) {
7487 if (!fd_table[i]) {
7488 char buf[64];
7489 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7490 fd_table[i] = bdrv_new(buf);
7491 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7493 if (fd_filename[i] != '\0') {
7494 if (bdrv_open(fd_table[i], fd_filename[i],
7495 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7496 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7497 fd_filename[i]);
7498 exit(1);
7504 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7505 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
7507 init_ioports();
7509 /* terminal init */
7510 if (nographic) {
7511 dumb_display_init(ds);
7512 } else if (vnc_display != NULL) {
7513 vnc_display_init(ds, vnc_display);
7514 } else {
7515 #if defined(CONFIG_SDL)
7516 sdl_display_init(ds, full_screen);
7517 #elif defined(CONFIG_COCOA)
7518 cocoa_display_init(ds, full_screen);
7519 #else
7520 dumb_display_init(ds);
7521 #endif
7524 monitor_hd = qemu_chr_open(monitor_device);
7525 if (!monitor_hd) {
7526 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7527 exit(1);
7529 monitor_init(monitor_hd, !nographic);
7531 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
7532 const char *devname = vmchannel_devices[i];
7533 if (devname[0] != '\0' && strcmp(devname, "none")) {
7534 int devid;
7535 char *termn;
7537 if (strstart(devname, "di:", &devname)) {
7538 devid = strtol(devname, &termn, 16);
7539 devname = termn + 1;
7541 else {
7542 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
7543 devname);
7544 exit(1);
7546 vmchannel_hds[i] = qemu_chr_open(devname);
7547 if (!vmchannel_hds[i]) {
7548 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
7549 devname);
7550 exit(1);
7552 vmchannel_init(vmchannel_hds[i], devid, i);
7556 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7557 const char *devname = serial_devices[i];
7558 if (devname[0] != '\0' && strcmp(devname, "none")) {
7559 serial_hds[i] = qemu_chr_open(devname);
7560 if (!serial_hds[i]) {
7561 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7562 devname);
7563 exit(1);
7565 if (!strcmp(devname, "vc"))
7566 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7570 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7571 const char *devname = parallel_devices[i];
7572 if (devname[0] != '\0' && strcmp(devname, "none")) {
7573 parallel_hds[i] = qemu_chr_open(devname);
7574 if (!parallel_hds[i]) {
7575 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7576 devname);
7577 exit(1);
7579 if (!strcmp(devname, "vc"))
7580 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7584 machine->init(ram_size, vga_ram_size, boot_device,
7585 ds, fd_filename, snapshot,
7586 kernel_filename, kernel_cmdline, initrd_filename);
7588 /* init USB devices */
7589 if (usb_enabled) {
7590 for(i = 0; i < usb_devices_index; i++) {
7591 if (usb_device_add(usb_devices[i]) < 0) {
7592 fprintf(stderr, "Warning: could not add USB device %s\n",
7593 usb_devices[i]);
7598 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7599 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7601 #ifdef CONFIG_GDBSTUB
7602 if (use_gdbstub) {
7603 /* XXX: use standard host:port notation and modify options
7604 accordingly. */
7605 if (gdbserver_start_port(gdbstub_port) < 0) {
7606 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7607 gdbstub_port);
7608 exit(1);
7610 } else
7611 #endif
7612 if (loadvm) {
7613 do_loadvm(loadvm);
7616 if (incoming) {
7617 int rc;
7619 rc = migrate_incoming(incoming);
7620 if (rc != 0) {
7621 fprintf(stderr, "Migration failed rc=%d\n", rc);
7622 exit(rc);
7627 /* XXX: simplify init */
7628 read_passwords();
7629 if (autostart) {
7630 vm_start();
7634 if (daemonize) {
7635 uint8_t status = 0;
7636 ssize_t len;
7637 int fd;
7639 again1:
7640 len = write(fds[1], &status, 1);
7641 if (len == -1 && (errno == EINTR))
7642 goto again1;
7644 if (len != 1)
7645 exit(1);
7647 chdir("/");
7648 fd = open("/dev/null", O_RDWR);
7649 if (fd == -1)
7650 exit(1);
7652 dup2(fd, 0);
7653 dup2(fd, 1);
7654 dup2(fd, 2);
7656 close(fd);
7659 main_loop();
7660 quit_timers();
7661 return 0;