Merge qemu-0.9.0
[qemu-kvm/fedora.git] / vl.c
blob065facefde25d568133cea76cd11876fcd8974ba
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 *serial_hds[MAX_SERIAL_PORTS];
157 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
158 #ifdef TARGET_I386
159 int win2k_install_hack = 0;
160 #endif
161 int usb_enabled = 0;
162 static VLANState *first_vlan;
163 int smp_cpus = 1;
164 const char *vnc_display;
165 #if defined(TARGET_SPARC)
166 #define MAX_CPUS 16
167 #elif defined(TARGET_I386)
168 #define MAX_CPUS 255
169 #else
170 #define MAX_CPUS 1
171 #endif
172 int acpi_enabled = 1;
173 int fd_bootchk = 1;
174 int no_reboot = 0;
175 int daemonize = 0;
176 const char *option_rom[MAX_OPTION_ROMS];
177 int nb_option_roms;
178 int semihosting_enabled = 0;
179 int autostart = 1;
181 /***********************************************************/
182 /* x86 ISA bus support */
184 target_phys_addr_t isa_mem_base = 0;
185 PicState2 *isa_pic;
187 uint32_t default_ioport_readb(void *opaque, uint32_t address)
189 #ifdef DEBUG_UNUSED_IOPORT
190 fprintf(stderr, "inb: port=0x%04x\n", address);
191 #endif
192 return 0xff;
195 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
197 #ifdef DEBUG_UNUSED_IOPORT
198 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
199 #endif
202 /* default is to make two byte accesses */
203 uint32_t default_ioport_readw(void *opaque, uint32_t address)
205 uint32_t data;
206 data = ioport_read_table[0][address](ioport_opaque[address], address);
207 address = (address + 1) & (MAX_IOPORTS - 1);
208 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
209 return data;
212 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
214 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
215 address = (address + 1) & (MAX_IOPORTS - 1);
216 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
219 uint32_t default_ioport_readl(void *opaque, uint32_t address)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "inl: port=0x%04x\n", address);
223 #endif
224 return 0xffffffff;
227 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
229 #ifdef DEBUG_UNUSED_IOPORT
230 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
231 #endif
234 void init_ioports(void)
236 int i;
238 for(i = 0; i < MAX_IOPORTS; i++) {
239 ioport_read_table[0][i] = default_ioport_readb;
240 ioport_write_table[0][i] = default_ioport_writeb;
241 ioport_read_table[1][i] = default_ioport_readw;
242 ioport_write_table[1][i] = default_ioport_writew;
243 ioport_read_table[2][i] = default_ioport_readl;
244 ioport_write_table[2][i] = default_ioport_writel;
248 /* size is the word size in byte */
249 int register_ioport_read(int start, int length, int size,
250 IOPortReadFunc *func, void *opaque)
252 int i, bsize;
254 if (size == 1) {
255 bsize = 0;
256 } else if (size == 2) {
257 bsize = 1;
258 } else if (size == 4) {
259 bsize = 2;
260 } else {
261 hw_error("register_ioport_read: invalid size");
262 return -1;
264 for(i = start; i < start + length; i += size) {
265 ioport_read_table[bsize][i] = func;
266 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
267 hw_error("register_ioport_read: invalid opaque");
268 ioport_opaque[i] = opaque;
270 return 0;
273 /* size is the word size in byte */
274 int register_ioport_write(int start, int length, int size,
275 IOPortWriteFunc *func, void *opaque)
277 int i, bsize;
279 if (size == 1) {
280 bsize = 0;
281 } else if (size == 2) {
282 bsize = 1;
283 } else if (size == 4) {
284 bsize = 2;
285 } else {
286 hw_error("register_ioport_write: invalid size");
287 return -1;
289 for(i = start; i < start + length; i += size) {
290 ioport_write_table[bsize][i] = func;
291 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
292 hw_error("register_ioport_write: invalid opaque");
293 ioport_opaque[i] = opaque;
295 return 0;
298 void isa_unassign_ioport(int start, int length)
300 int i;
302 for(i = start; i < start + length; i++) {
303 ioport_read_table[0][i] = default_ioport_readb;
304 ioport_read_table[1][i] = default_ioport_readw;
305 ioport_read_table[2][i] = default_ioport_readl;
307 ioport_write_table[0][i] = default_ioport_writeb;
308 ioport_write_table[1][i] = default_ioport_writew;
309 ioport_write_table[2][i] = default_ioport_writel;
313 /***********************************************************/
315 void cpu_outb(CPUState *env, int addr, int val)
317 #ifdef DEBUG_IOPORT
318 if (loglevel & CPU_LOG_IOPORT)
319 fprintf(logfile, "outb: %04x %02x\n", addr, val);
320 #endif
321 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
322 #ifdef USE_KQEMU
323 if (env)
324 env->last_io_time = cpu_get_time_fast();
325 #endif
328 void cpu_outw(CPUState *env, int addr, int val)
330 #ifdef DEBUG_IOPORT
331 if (loglevel & CPU_LOG_IOPORT)
332 fprintf(logfile, "outw: %04x %04x\n", addr, val);
333 #endif
334 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
335 #ifdef USE_KQEMU
336 if (env)
337 env->last_io_time = cpu_get_time_fast();
338 #endif
341 void cpu_outl(CPUState *env, int addr, int val)
343 #ifdef DEBUG_IOPORT
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outl: %04x %08x\n", addr, val);
346 #endif
347 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
348 #ifdef USE_KQEMU
349 if (env)
350 env->last_io_time = cpu_get_time_fast();
351 #endif
354 int cpu_inb(CPUState *env, int addr)
356 int val;
357 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
358 #ifdef DEBUG_IOPORT
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "inb : %04x %02x\n", addr, val);
361 #endif
362 #ifdef USE_KQEMU
363 if (env)
364 env->last_io_time = cpu_get_time_fast();
365 #endif
366 return val;
369 int cpu_inw(CPUState *env, int addr)
371 int val;
372 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
373 #ifdef DEBUG_IOPORT
374 if (loglevel & CPU_LOG_IOPORT)
375 fprintf(logfile, "inw : %04x %04x\n", addr, val);
376 #endif
377 #ifdef USE_KQEMU
378 if (env)
379 env->last_io_time = cpu_get_time_fast();
380 #endif
381 return val;
384 int cpu_inl(CPUState *env, int addr)
386 int val;
387 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
388 #ifdef DEBUG_IOPORT
389 if (loglevel & CPU_LOG_IOPORT)
390 fprintf(logfile, "inl : %04x %08x\n", addr, val);
391 #endif
392 #ifdef USE_KQEMU
393 if (env)
394 env->last_io_time = cpu_get_time_fast();
395 #endif
396 return val;
399 /***********************************************************/
400 void hw_error(const char *fmt, ...)
402 va_list ap;
403 CPUState *env;
405 va_start(ap, fmt);
406 fprintf(stderr, "qemu: hardware error: ");
407 vfprintf(stderr, fmt, ap);
408 fprintf(stderr, "\n");
409 for(env = first_cpu; env != NULL; env = env->next_cpu) {
410 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
411 #ifdef TARGET_I386
412 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
413 #else
414 cpu_dump_state(env, stderr, fprintf, 0);
415 #endif
417 va_end(ap);
418 abort();
421 /***********************************************************/
422 /* keyboard/mouse */
424 static QEMUPutKBDEvent *qemu_put_kbd_event;
425 static void *qemu_put_kbd_event_opaque;
426 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
427 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
429 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
431 qemu_put_kbd_event_opaque = opaque;
432 qemu_put_kbd_event = func;
435 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
436 void *opaque, int absolute,
437 const char *name)
439 QEMUPutMouseEntry *s, *cursor;
441 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
442 if (!s)
443 return NULL;
445 s->qemu_put_mouse_event = func;
446 s->qemu_put_mouse_event_opaque = opaque;
447 s->qemu_put_mouse_event_absolute = absolute;
448 s->qemu_put_mouse_event_name = qemu_strdup(name);
449 s->next = NULL;
451 if (!qemu_put_mouse_event_head) {
452 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
453 return s;
456 cursor = qemu_put_mouse_event_head;
457 while (cursor->next != NULL)
458 cursor = cursor->next;
460 cursor->next = s;
461 qemu_put_mouse_event_current = s;
463 return s;
466 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
468 QEMUPutMouseEntry *prev = NULL, *cursor;
470 if (!qemu_put_mouse_event_head || entry == NULL)
471 return;
473 cursor = qemu_put_mouse_event_head;
474 while (cursor != NULL && cursor != entry) {
475 prev = cursor;
476 cursor = cursor->next;
479 if (cursor == NULL) // does not exist or list empty
480 return;
481 else if (prev == NULL) { // entry is head
482 qemu_put_mouse_event_head = cursor->next;
483 if (qemu_put_mouse_event_current == entry)
484 qemu_put_mouse_event_current = cursor->next;
485 qemu_free(entry->qemu_put_mouse_event_name);
486 qemu_free(entry);
487 return;
490 prev->next = entry->next;
492 if (qemu_put_mouse_event_current == entry)
493 qemu_put_mouse_event_current = prev;
495 qemu_free(entry->qemu_put_mouse_event_name);
496 qemu_free(entry);
499 void kbd_put_keycode(int keycode)
501 if (qemu_put_kbd_event) {
502 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
506 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
508 QEMUPutMouseEvent *mouse_event;
509 void *mouse_event_opaque;
511 if (!qemu_put_mouse_event_current) {
512 return;
515 mouse_event =
516 qemu_put_mouse_event_current->qemu_put_mouse_event;
517 mouse_event_opaque =
518 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
520 if (mouse_event) {
521 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
525 int kbd_mouse_is_absolute(void)
527 if (!qemu_put_mouse_event_current)
528 return 0;
530 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
533 void do_info_mice(void)
535 QEMUPutMouseEntry *cursor;
536 int index = 0;
538 if (!qemu_put_mouse_event_head) {
539 term_printf("No mouse devices connected\n");
540 return;
543 term_printf("Mouse devices available:\n");
544 cursor = qemu_put_mouse_event_head;
545 while (cursor != NULL) {
546 term_printf("%c Mouse #%d: %s\n",
547 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
548 index, cursor->qemu_put_mouse_event_name);
549 index++;
550 cursor = cursor->next;
554 void do_mouse_set(int index)
556 QEMUPutMouseEntry *cursor;
557 int i = 0;
559 if (!qemu_put_mouse_event_head) {
560 term_printf("No mouse devices connected\n");
561 return;
564 cursor = qemu_put_mouse_event_head;
565 while (cursor != NULL && index != i) {
566 i++;
567 cursor = cursor->next;
570 if (cursor != NULL)
571 qemu_put_mouse_event_current = cursor;
572 else
573 term_printf("Mouse at given index not found\n");
576 /* compute with 96 bit intermediate result: (a*b)/c */
577 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
579 union {
580 uint64_t ll;
581 struct {
582 #ifdef WORDS_BIGENDIAN
583 uint32_t high, low;
584 #else
585 uint32_t low, high;
586 #endif
587 } l;
588 } u, res;
589 uint64_t rl, rh;
591 u.ll = a;
592 rl = (uint64_t)u.l.low * (uint64_t)b;
593 rh = (uint64_t)u.l.high * (uint64_t)b;
594 rh += (rl >> 32);
595 res.l.high = rh / c;
596 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
597 return res.ll;
600 /***********************************************************/
601 /* real time host monotonic timer */
603 #define QEMU_TIMER_BASE 1000000000LL
605 #ifdef WIN32
607 static int64_t clock_freq;
609 static void init_get_clock(void)
611 LARGE_INTEGER freq;
612 int ret;
613 ret = QueryPerformanceFrequency(&freq);
614 if (ret == 0) {
615 fprintf(stderr, "Could not calibrate ticks\n");
616 exit(1);
618 clock_freq = freq.QuadPart;
621 static int64_t get_clock(void)
623 LARGE_INTEGER ti;
624 QueryPerformanceCounter(&ti);
625 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
628 #else
630 static int use_rt_clock;
632 static void init_get_clock(void)
634 use_rt_clock = 0;
635 #if defined(__linux__)
637 struct timespec ts;
638 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
639 use_rt_clock = 1;
642 #endif
645 static int64_t get_clock(void)
647 #if defined(__linux__)
648 if (use_rt_clock) {
649 struct timespec ts;
650 clock_gettime(CLOCK_MONOTONIC, &ts);
651 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
652 } else
653 #endif
655 /* XXX: using gettimeofday leads to problems if the date
656 changes, so it should be avoided. */
657 struct timeval tv;
658 gettimeofday(&tv, NULL);
659 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
663 #endif
665 /***********************************************************/
666 /* guest cycle counter */
668 static int64_t cpu_ticks_prev;
669 static int64_t cpu_ticks_offset;
670 static int64_t cpu_clock_offset;
671 static int cpu_ticks_enabled;
673 /* return the host CPU cycle counter and handle stop/restart */
674 int64_t cpu_get_ticks(void)
676 if (!cpu_ticks_enabled) {
677 return cpu_ticks_offset;
678 } else {
679 int64_t ticks;
680 ticks = cpu_get_real_ticks();
681 if (cpu_ticks_prev > ticks) {
682 /* Note: non increasing ticks may happen if the host uses
683 software suspend */
684 cpu_ticks_offset += cpu_ticks_prev - ticks;
686 cpu_ticks_prev = ticks;
687 return ticks + cpu_ticks_offset;
691 /* return the host CPU monotonic timer and handle stop/restart */
692 static int64_t cpu_get_clock(void)
694 int64_t ti;
695 if (!cpu_ticks_enabled) {
696 return cpu_clock_offset;
697 } else {
698 ti = get_clock();
699 return ti + cpu_clock_offset;
703 /* enable cpu_get_ticks() */
704 void cpu_enable_ticks(void)
706 if (!cpu_ticks_enabled) {
707 cpu_ticks_offset -= cpu_get_real_ticks();
708 cpu_clock_offset -= get_clock();
709 cpu_ticks_enabled = 1;
713 /* disable cpu_get_ticks() : the clock is stopped. You must not call
714 cpu_get_ticks() after that. */
715 void cpu_disable_ticks(void)
717 if (cpu_ticks_enabled) {
718 cpu_ticks_offset = cpu_get_ticks();
719 cpu_clock_offset = cpu_get_clock();
720 cpu_ticks_enabled = 0;
724 /***********************************************************/
725 /* timers */
727 #define QEMU_TIMER_REALTIME 0
728 #define QEMU_TIMER_VIRTUAL 1
730 struct QEMUClock {
731 int type;
732 /* XXX: add frequency */
735 struct QEMUTimer {
736 QEMUClock *clock;
737 int64_t expire_time;
738 QEMUTimerCB *cb;
739 void *opaque;
740 struct QEMUTimer *next;
743 QEMUClock *rt_clock;
744 QEMUClock *vm_clock;
746 static QEMUTimer *active_timers[2];
747 #ifdef _WIN32
748 static MMRESULT timerID;
749 static HANDLE host_alarm = NULL;
750 static unsigned int period = 1;
751 #else
752 /* frequency of the times() clock tick */
753 static int timer_freq;
754 #endif
756 QEMUClock *qemu_new_clock(int type)
758 QEMUClock *clock;
759 clock = qemu_mallocz(sizeof(QEMUClock));
760 if (!clock)
761 return NULL;
762 clock->type = type;
763 return clock;
766 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
768 QEMUTimer *ts;
770 ts = qemu_mallocz(sizeof(QEMUTimer));
771 ts->clock = clock;
772 ts->cb = cb;
773 ts->opaque = opaque;
774 return ts;
777 void qemu_free_timer(QEMUTimer *ts)
779 qemu_free(ts);
782 /* stop a timer, but do not dealloc it */
783 void qemu_del_timer(QEMUTimer *ts)
785 QEMUTimer **pt, *t;
787 /* NOTE: this code must be signal safe because
788 qemu_timer_expired() can be called from a signal. */
789 pt = &active_timers[ts->clock->type];
790 for(;;) {
791 t = *pt;
792 if (!t)
793 break;
794 if (t == ts) {
795 *pt = t->next;
796 break;
798 pt = &t->next;
802 /* modify the current timer so that it will be fired when current_time
803 >= expire_time. The corresponding callback will be called. */
804 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
806 QEMUTimer **pt, *t;
808 qemu_del_timer(ts);
810 /* add the timer in the sorted list */
811 /* NOTE: this code must be signal safe because
812 qemu_timer_expired() can be called from a signal. */
813 pt = &active_timers[ts->clock->type];
814 for(;;) {
815 t = *pt;
816 if (!t)
817 break;
818 if (t->expire_time > expire_time)
819 break;
820 pt = &t->next;
822 ts->expire_time = expire_time;
823 ts->next = *pt;
824 *pt = ts;
827 int qemu_timer_pending(QEMUTimer *ts)
829 QEMUTimer *t;
830 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
831 if (t == ts)
832 return 1;
834 return 0;
837 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
839 if (!timer_head)
840 return 0;
841 return (timer_head->expire_time <= current_time);
844 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
846 QEMUTimer *ts;
848 for(;;) {
849 ts = *ptimer_head;
850 if (!ts || ts->expire_time > current_time)
851 break;
852 /* remove timer from the list before calling the callback */
853 *ptimer_head = ts->next;
854 ts->next = NULL;
856 /* run the callback (the timer list can be modified) */
857 ts->cb(ts->opaque);
861 int64_t qemu_get_clock(QEMUClock *clock)
863 switch(clock->type) {
864 case QEMU_TIMER_REALTIME:
865 return get_clock() / 1000000;
866 default:
867 case QEMU_TIMER_VIRTUAL:
868 return cpu_get_clock();
872 static void init_timers(void)
874 init_get_clock();
875 ticks_per_sec = QEMU_TIMER_BASE;
876 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
877 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
880 /* save a timer */
881 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
883 uint64_t expire_time;
885 if (qemu_timer_pending(ts)) {
886 expire_time = ts->expire_time;
887 } else {
888 expire_time = -1;
890 qemu_put_be64(f, expire_time);
893 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
895 uint64_t expire_time;
897 expire_time = qemu_get_be64(f);
898 if (expire_time != -1) {
899 qemu_mod_timer(ts, expire_time);
900 } else {
901 qemu_del_timer(ts);
905 static void timer_save(QEMUFile *f, void *opaque)
907 if (cpu_ticks_enabled) {
908 hw_error("cannot save state if virtual timers are running");
910 qemu_put_be64s(f, &cpu_ticks_offset);
911 qemu_put_be64s(f, &ticks_per_sec);
912 qemu_put_be64s(f, &cpu_clock_offset);
915 static int timer_load(QEMUFile *f, void *opaque, int version_id)
917 if (version_id != 1 && version_id != 2)
918 return -EINVAL;
919 if (cpu_ticks_enabled) {
920 return -EINVAL;
922 qemu_get_be64s(f, &cpu_ticks_offset);
923 qemu_get_be64s(f, &ticks_per_sec);
924 if (version_id == 2) {
925 qemu_get_be64s(f, &cpu_clock_offset);
927 return 0;
930 #ifdef _WIN32
931 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
932 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
933 #else
934 static void host_alarm_handler(int host_signum)
935 #endif
937 #if 0
938 #define DISP_FREQ 1000
940 static int64_t delta_min = INT64_MAX;
941 static int64_t delta_max, delta_cum, last_clock, delta, ti;
942 static int count;
943 ti = qemu_get_clock(vm_clock);
944 if (last_clock != 0) {
945 delta = ti - last_clock;
946 if (delta < delta_min)
947 delta_min = delta;
948 if (delta > delta_max)
949 delta_max = delta;
950 delta_cum += delta;
951 if (++count == DISP_FREQ) {
952 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
953 muldiv64(delta_min, 1000000, ticks_per_sec),
954 muldiv64(delta_max, 1000000, ticks_per_sec),
955 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
956 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
957 count = 0;
958 delta_min = INT64_MAX;
959 delta_max = 0;
960 delta_cum = 0;
963 last_clock = ti;
965 #endif
966 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
967 qemu_get_clock(vm_clock)) ||
968 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
969 qemu_get_clock(rt_clock))) {
970 #ifdef _WIN32
971 SetEvent(host_alarm);
972 #endif
973 CPUState *env = cpu_single_env;
974 if (env) {
975 /* stop the currently executing cpu because a timer occured */
976 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
977 #ifdef USE_KQEMU
978 if (env->kqemu_enabled) {
979 kqemu_cpu_interrupt(env);
981 #endif
986 #ifndef _WIN32
988 #if defined(__linux__)
990 #define RTC_FREQ 1024
992 static int rtc_fd;
994 static int start_rtc_timer(void)
996 rtc_fd = open("/dev/rtc", O_RDONLY);
997 if (rtc_fd < 0)
998 return -1;
999 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1000 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1001 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1002 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1003 goto fail;
1005 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1006 fail:
1007 close(rtc_fd);
1008 return -1;
1010 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1011 return 0;
1014 #else
1016 static int start_rtc_timer(void)
1018 return -1;
1021 #endif /* !defined(__linux__) */
1023 #endif /* !defined(_WIN32) */
1025 static void init_timer_alarm(void)
1027 #ifdef _WIN32
1029 int count=0;
1030 TIMECAPS tc;
1032 ZeroMemory(&tc, sizeof(TIMECAPS));
1033 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1034 if (period < tc.wPeriodMin)
1035 period = tc.wPeriodMin;
1036 timeBeginPeriod(period);
1037 timerID = timeSetEvent(1, // interval (ms)
1038 period, // resolution
1039 host_alarm_handler, // function
1040 (DWORD)&count, // user parameter
1041 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1042 if( !timerID ) {
1043 perror("failed timer alarm");
1044 exit(1);
1046 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1047 if (!host_alarm) {
1048 perror("failed CreateEvent");
1049 exit(1);
1051 qemu_add_wait_object(host_alarm, NULL, NULL);
1053 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1054 #else
1056 struct sigaction act;
1057 struct itimerval itv;
1059 /* get times() syscall frequency */
1060 timer_freq = sysconf(_SC_CLK_TCK);
1062 /* timer signal */
1063 sigfillset(&act.sa_mask);
1064 act.sa_flags = 0;
1065 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1066 act.sa_flags |= SA_ONSTACK;
1067 #endif
1068 act.sa_handler = host_alarm_handler;
1069 sigaction(SIGALRM, &act, NULL);
1071 itv.it_interval.tv_sec = 0;
1072 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1073 itv.it_value.tv_sec = 0;
1074 itv.it_value.tv_usec = 10 * 1000;
1075 setitimer(ITIMER_REAL, &itv, NULL);
1076 /* we probe the tick duration of the kernel to inform the user if
1077 the emulated kernel requested a too high timer frequency */
1078 getitimer(ITIMER_REAL, &itv);
1080 #if defined(__linux__)
1081 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1082 have timers with 1 ms resolution. The correct solution will
1083 be to use the POSIX real time timers available in recent
1084 2.6 kernels */
1085 if (itv.it_interval.tv_usec > 1000 || 1) {
1086 /* try to use /dev/rtc to have a faster timer */
1087 if (start_rtc_timer() < 0)
1088 goto use_itimer;
1089 /* disable itimer */
1090 itv.it_interval.tv_sec = 0;
1091 itv.it_interval.tv_usec = 0;
1092 itv.it_value.tv_sec = 0;
1093 itv.it_value.tv_usec = 0;
1094 setitimer(ITIMER_REAL, &itv, NULL);
1096 /* use the RTC */
1097 sigaction(SIGIO, &act, NULL);
1098 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1099 fcntl(rtc_fd, F_SETOWN, getpid());
1100 } else
1101 #endif /* defined(__linux__) */
1103 use_itimer:
1104 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1105 PIT_FREQ) / 1000000;
1108 #endif
1111 void quit_timers(void)
1113 #ifdef _WIN32
1114 timeKillEvent(timerID);
1115 timeEndPeriod(period);
1116 if (host_alarm) {
1117 CloseHandle(host_alarm);
1118 host_alarm = NULL;
1120 #endif
1123 /***********************************************************/
1124 /* character device */
1126 static void qemu_chr_event(CharDriverState *s, int event)
1128 if (!s->chr_event)
1129 return;
1130 s->chr_event(s->handler_opaque, event);
1133 static void qemu_chr_reset_bh(void *opaque)
1135 CharDriverState *s = opaque;
1136 qemu_chr_event(s, CHR_EVENT_RESET);
1137 qemu_bh_delete(s->bh);
1138 s->bh = NULL;
1141 void qemu_chr_reset(CharDriverState *s)
1143 if (s->bh == NULL) {
1144 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1145 qemu_bh_schedule(s->bh);
1149 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1151 return s->chr_write(s, buf, len);
1154 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1156 if (!s->chr_ioctl)
1157 return -ENOTSUP;
1158 return s->chr_ioctl(s, cmd, arg);
1161 int qemu_chr_can_read(CharDriverState *s)
1163 if (!s->chr_can_read)
1164 return 0;
1165 return s->chr_can_read(s->handler_opaque);
1168 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1170 s->chr_read(s->handler_opaque, buf, len);
1174 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1176 char buf[4096];
1177 va_list ap;
1178 va_start(ap, fmt);
1179 vsnprintf(buf, sizeof(buf), fmt, ap);
1180 qemu_chr_write(s, buf, strlen(buf));
1181 va_end(ap);
1184 void qemu_chr_send_event(CharDriverState *s, int event)
1186 if (s->chr_send_event)
1187 s->chr_send_event(s, event);
1190 void qemu_chr_add_handlers(CharDriverState *s,
1191 IOCanRWHandler *fd_can_read,
1192 IOReadHandler *fd_read,
1193 IOEventHandler *fd_event,
1194 void *opaque)
1196 s->chr_can_read = fd_can_read;
1197 s->chr_read = fd_read;
1198 s->chr_event = fd_event;
1199 s->handler_opaque = opaque;
1200 if (s->chr_update_read_handler)
1201 s->chr_update_read_handler(s);
1204 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1206 return len;
1209 static CharDriverState *qemu_chr_open_null(void)
1211 CharDriverState *chr;
1213 chr = qemu_mallocz(sizeof(CharDriverState));
1214 if (!chr)
1215 return NULL;
1216 chr->chr_write = null_chr_write;
1217 return chr;
1220 #ifdef _WIN32
1222 static void socket_cleanup(void)
1224 WSACleanup();
1227 static int socket_init(void)
1229 WSADATA Data;
1230 int ret, err;
1232 ret = WSAStartup(MAKEWORD(2,2), &Data);
1233 if (ret != 0) {
1234 err = WSAGetLastError();
1235 fprintf(stderr, "WSAStartup: %d\n", err);
1236 return -1;
1238 atexit(socket_cleanup);
1239 return 0;
1242 static int send_all(int fd, const uint8_t *buf, int len1)
1244 int ret, len;
1246 len = len1;
1247 while (len > 0) {
1248 ret = send(fd, buf, len, 0);
1249 if (ret < 0) {
1250 int errno;
1251 errno = WSAGetLastError();
1252 if (errno != WSAEWOULDBLOCK) {
1253 return -1;
1255 } else if (ret == 0) {
1256 break;
1257 } else {
1258 buf += ret;
1259 len -= ret;
1262 return len1 - len;
1265 void socket_set_nonblock(int fd)
1267 unsigned long opt = 1;
1268 ioctlsocket(fd, FIONBIO, &opt);
1271 #else
1273 static int unix_write(int fd, const uint8_t *buf, int len1)
1275 int ret, len;
1277 len = len1;
1278 while (len > 0) {
1279 ret = write(fd, buf, len);
1280 if (ret < 0) {
1281 if (errno != EINTR && errno != EAGAIN)
1282 return -1;
1283 } else if (ret == 0) {
1284 break;
1285 } else {
1286 buf += ret;
1287 len -= ret;
1290 return len1 - len;
1293 static inline int send_all(int fd, const uint8_t *buf, int len1)
1295 return unix_write(fd, buf, len1);
1298 void socket_set_nonblock(int fd)
1300 fcntl(fd, F_SETFL, O_NONBLOCK);
1302 #endif /* !_WIN32 */
1304 #ifndef _WIN32
1306 typedef struct {
1307 int fd_in, fd_out;
1308 int max_size;
1309 } FDCharDriver;
1311 #define STDIO_MAX_CLIENTS 2
1313 static int stdio_nb_clients;
1314 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1316 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1318 FDCharDriver *s = chr->opaque;
1319 return unix_write(s->fd_out, buf, len);
1322 static int fd_chr_read_poll(void *opaque)
1324 CharDriverState *chr = opaque;
1325 FDCharDriver *s = chr->opaque;
1327 s->max_size = qemu_chr_can_read(chr);
1328 return s->max_size;
1331 static void fd_chr_read(void *opaque)
1333 CharDriverState *chr = opaque;
1334 FDCharDriver *s = chr->opaque;
1335 int size, len;
1336 uint8_t buf[1024];
1338 len = sizeof(buf);
1339 if (len > s->max_size)
1340 len = s->max_size;
1341 if (len == 0)
1342 return;
1343 size = read(s->fd_in, buf, len);
1344 if (size == 0) {
1345 /* FD has been closed. Remove it from the active list. */
1346 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1347 return;
1349 if (size > 0) {
1350 qemu_chr_read(chr, buf, size);
1354 static void fd_chr_update_read_handler(CharDriverState *chr)
1356 FDCharDriver *s = chr->opaque;
1358 if (s->fd_in >= 0) {
1359 if (nographic && s->fd_in == 0) {
1360 } else {
1361 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1362 fd_chr_read, NULL, chr);
1367 /* open a character device to a unix fd */
1368 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1370 CharDriverState *chr;
1371 FDCharDriver *s;
1373 chr = qemu_mallocz(sizeof(CharDriverState));
1374 if (!chr)
1375 return NULL;
1376 s = qemu_mallocz(sizeof(FDCharDriver));
1377 if (!s) {
1378 free(chr);
1379 return NULL;
1381 s->fd_in = fd_in;
1382 s->fd_out = fd_out;
1383 chr->opaque = s;
1384 chr->chr_write = fd_chr_write;
1385 chr->chr_update_read_handler = fd_chr_update_read_handler;
1387 qemu_chr_reset(chr);
1389 return chr;
1392 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1394 int fd_out;
1396 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1397 if (fd_out < 0)
1398 return NULL;
1399 return qemu_chr_open_fd(-1, fd_out);
1402 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1404 int fd_in, fd_out;
1405 char filename_in[256], filename_out[256];
1407 snprintf(filename_in, 256, "%s.in", filename);
1408 snprintf(filename_out, 256, "%s.out", filename);
1409 fd_in = open(filename_in, O_RDWR | O_BINARY);
1410 fd_out = open(filename_out, O_RDWR | O_BINARY);
1411 if (fd_in < 0 || fd_out < 0) {
1412 if (fd_in >= 0)
1413 close(fd_in);
1414 if (fd_out >= 0)
1415 close(fd_out);
1416 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1417 if (fd_in < 0)
1418 return NULL;
1420 return qemu_chr_open_fd(fd_in, fd_out);
1424 /* for STDIO, we handle the case where several clients use it
1425 (nographic mode) */
1427 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1429 #define TERM_FIFO_MAX_SIZE 1
1431 static int term_got_escape, client_index;
1432 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1433 static int term_fifo_size;
1434 static int term_timestamps;
1435 static int64_t term_timestamps_start;
1437 void term_print_help(void)
1439 printf("\n"
1440 "C-a h print this help\n"
1441 "C-a x exit emulator\n"
1442 "C-a s save disk data back to file (if -snapshot)\n"
1443 "C-a b send break (magic sysrq)\n"
1444 "C-a t toggle console timestamps\n"
1445 "C-a c switch between console and monitor\n"
1446 "C-a C-a send C-a\n"
1450 /* called when a char is received */
1451 static void stdio_received_byte(int ch)
1453 if (term_got_escape) {
1454 term_got_escape = 0;
1455 switch(ch) {
1456 case 'h':
1457 term_print_help();
1458 break;
1459 case 'x':
1460 exit(0);
1461 break;
1462 case 's':
1464 int i;
1465 for (i = 0; i < MAX_DISKS; i++) {
1466 if (bs_table[i])
1467 bdrv_commit(bs_table[i]);
1470 break;
1471 case 'b':
1472 if (client_index < stdio_nb_clients) {
1473 CharDriverState *chr;
1474 FDCharDriver *s;
1476 chr = stdio_clients[client_index];
1477 s = chr->opaque;
1478 qemu_chr_event(chr, CHR_EVENT_BREAK);
1480 break;
1481 case 'c':
1482 client_index++;
1483 if (client_index >= stdio_nb_clients)
1484 client_index = 0;
1485 if (client_index == 0) {
1486 /* send a new line in the monitor to get the prompt */
1487 ch = '\r';
1488 goto send_char;
1490 break;
1491 case 't':
1492 term_timestamps = !term_timestamps;
1493 term_timestamps_start = -1;
1494 break;
1495 case TERM_ESCAPE:
1496 goto send_char;
1498 } else if (ch == TERM_ESCAPE) {
1499 term_got_escape = 1;
1500 } else {
1501 send_char:
1502 if (client_index < stdio_nb_clients) {
1503 uint8_t buf[1];
1504 CharDriverState *chr;
1506 chr = stdio_clients[client_index];
1507 if (qemu_chr_can_read(chr) > 0) {
1508 buf[0] = ch;
1509 qemu_chr_read(chr, buf, 1);
1510 } else if (term_fifo_size == 0) {
1511 term_fifo[term_fifo_size++] = ch;
1517 static int stdio_read_poll(void *opaque)
1519 CharDriverState *chr;
1521 if (client_index < stdio_nb_clients) {
1522 chr = stdio_clients[client_index];
1523 /* try to flush the queue if needed */
1524 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1525 qemu_chr_read(chr, term_fifo, 1);
1526 term_fifo_size = 0;
1528 /* see if we can absorb more chars */
1529 if (term_fifo_size == 0)
1530 return 1;
1531 else
1532 return 0;
1533 } else {
1534 return 1;
1538 static void stdio_read(void *opaque)
1540 int size;
1541 uint8_t buf[1];
1543 size = read(0, buf, 1);
1544 if (size == 0) {
1545 /* stdin has been closed. Remove it from the active list. */
1546 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1547 return;
1549 if (size > 0)
1550 stdio_received_byte(buf[0]);
1553 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1555 FDCharDriver *s = chr->opaque;
1556 if (!term_timestamps) {
1557 return unix_write(s->fd_out, buf, len);
1558 } else {
1559 int i;
1560 char buf1[64];
1562 for(i = 0; i < len; i++) {
1563 unix_write(s->fd_out, buf + i, 1);
1564 if (buf[i] == '\n') {
1565 int64_t ti;
1566 int secs;
1568 ti = get_clock();
1569 if (term_timestamps_start == -1)
1570 term_timestamps_start = ti;
1571 ti -= term_timestamps_start;
1572 secs = ti / 1000000000;
1573 snprintf(buf1, sizeof(buf1),
1574 "[%02d:%02d:%02d.%03d] ",
1575 secs / 3600,
1576 (secs / 60) % 60,
1577 secs % 60,
1578 (int)((ti / 1000000) % 1000));
1579 unix_write(s->fd_out, buf1, strlen(buf1));
1582 return len;
1586 /* init terminal so that we can grab keys */
1587 static struct termios oldtty;
1588 static int old_fd0_flags;
1590 static void term_exit(void)
1592 tcsetattr (0, TCSANOW, &oldtty);
1593 fcntl(0, F_SETFL, old_fd0_flags);
1596 static void term_init(void)
1598 struct termios tty;
1600 tcgetattr (0, &tty);
1601 oldtty = tty;
1602 old_fd0_flags = fcntl(0, F_GETFL);
1604 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1605 |INLCR|IGNCR|ICRNL|IXON);
1606 tty.c_oflag |= OPOST;
1607 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1608 /* if graphical mode, we allow Ctrl-C handling */
1609 if (nographic)
1610 tty.c_lflag &= ~ISIG;
1611 tty.c_cflag &= ~(CSIZE|PARENB);
1612 tty.c_cflag |= CS8;
1613 tty.c_cc[VMIN] = 1;
1614 tty.c_cc[VTIME] = 0;
1616 tcsetattr (0, TCSANOW, &tty);
1618 atexit(term_exit);
1620 fcntl(0, F_SETFL, O_NONBLOCK);
1623 static CharDriverState *qemu_chr_open_stdio(void)
1625 CharDriverState *chr;
1627 if (nographic) {
1628 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1629 return NULL;
1630 chr = qemu_chr_open_fd(0, 1);
1631 chr->chr_write = stdio_write;
1632 if (stdio_nb_clients == 0)
1633 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1634 client_index = stdio_nb_clients;
1635 } else {
1636 if (stdio_nb_clients != 0)
1637 return NULL;
1638 chr = qemu_chr_open_fd(0, 1);
1640 stdio_clients[stdio_nb_clients++] = chr;
1641 if (stdio_nb_clients == 1) {
1642 /* set the terminal in raw mode */
1643 term_init();
1645 return chr;
1648 #if defined(__linux__)
1649 static CharDriverState *qemu_chr_open_pty(void)
1651 struct termios tty;
1652 char slave_name[1024];
1653 int master_fd, slave_fd;
1655 /* Not satisfying */
1656 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1657 return NULL;
1660 /* Disabling local echo and line-buffered output */
1661 tcgetattr (master_fd, &tty);
1662 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1663 tty.c_cc[VMIN] = 1;
1664 tty.c_cc[VTIME] = 0;
1665 tcsetattr (master_fd, TCSAFLUSH, &tty);
1667 fprintf(stderr, "char device redirected to %s\n", slave_name);
1668 return qemu_chr_open_fd(master_fd, master_fd);
1671 static void tty_serial_init(int fd, int speed,
1672 int parity, int data_bits, int stop_bits)
1674 struct termios tty;
1675 speed_t spd;
1677 #if 0
1678 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1679 speed, parity, data_bits, stop_bits);
1680 #endif
1681 tcgetattr (fd, &tty);
1683 switch(speed) {
1684 case 50:
1685 spd = B50;
1686 break;
1687 case 75:
1688 spd = B75;
1689 break;
1690 case 300:
1691 spd = B300;
1692 break;
1693 case 600:
1694 spd = B600;
1695 break;
1696 case 1200:
1697 spd = B1200;
1698 break;
1699 case 2400:
1700 spd = B2400;
1701 break;
1702 case 4800:
1703 spd = B4800;
1704 break;
1705 case 9600:
1706 spd = B9600;
1707 break;
1708 case 19200:
1709 spd = B19200;
1710 break;
1711 case 38400:
1712 spd = B38400;
1713 break;
1714 case 57600:
1715 spd = B57600;
1716 break;
1717 default:
1718 case 115200:
1719 spd = B115200;
1720 break;
1723 cfsetispeed(&tty, spd);
1724 cfsetospeed(&tty, spd);
1726 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1727 |INLCR|IGNCR|ICRNL|IXON);
1728 tty.c_oflag |= OPOST;
1729 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1730 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1731 switch(data_bits) {
1732 default:
1733 case 8:
1734 tty.c_cflag |= CS8;
1735 break;
1736 case 7:
1737 tty.c_cflag |= CS7;
1738 break;
1739 case 6:
1740 tty.c_cflag |= CS6;
1741 break;
1742 case 5:
1743 tty.c_cflag |= CS5;
1744 break;
1746 switch(parity) {
1747 default:
1748 case 'N':
1749 break;
1750 case 'E':
1751 tty.c_cflag |= PARENB;
1752 break;
1753 case 'O':
1754 tty.c_cflag |= PARENB | PARODD;
1755 break;
1757 if (stop_bits == 2)
1758 tty.c_cflag |= CSTOPB;
1760 tcsetattr (fd, TCSANOW, &tty);
1763 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1765 FDCharDriver *s = chr->opaque;
1767 switch(cmd) {
1768 case CHR_IOCTL_SERIAL_SET_PARAMS:
1770 QEMUSerialSetParams *ssp = arg;
1771 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1772 ssp->data_bits, ssp->stop_bits);
1774 break;
1775 case CHR_IOCTL_SERIAL_SET_BREAK:
1777 int enable = *(int *)arg;
1778 if (enable)
1779 tcsendbreak(s->fd_in, 1);
1781 break;
1782 default:
1783 return -ENOTSUP;
1785 return 0;
1788 static CharDriverState *qemu_chr_open_tty(const char *filename)
1790 CharDriverState *chr;
1791 int fd;
1793 fd = open(filename, O_RDWR | O_NONBLOCK);
1794 if (fd < 0)
1795 return NULL;
1796 fcntl(fd, F_SETFL, O_NONBLOCK);
1797 tty_serial_init(fd, 115200, 'N', 8, 1);
1798 chr = qemu_chr_open_fd(fd, fd);
1799 if (!chr)
1800 return NULL;
1801 chr->chr_ioctl = tty_serial_ioctl;
1802 qemu_chr_reset(chr);
1803 return chr;
1806 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1808 int fd = (int)chr->opaque;
1809 uint8_t b;
1811 switch(cmd) {
1812 case CHR_IOCTL_PP_READ_DATA:
1813 if (ioctl(fd, PPRDATA, &b) < 0)
1814 return -ENOTSUP;
1815 *(uint8_t *)arg = b;
1816 break;
1817 case CHR_IOCTL_PP_WRITE_DATA:
1818 b = *(uint8_t *)arg;
1819 if (ioctl(fd, PPWDATA, &b) < 0)
1820 return -ENOTSUP;
1821 break;
1822 case CHR_IOCTL_PP_READ_CONTROL:
1823 if (ioctl(fd, PPRCONTROL, &b) < 0)
1824 return -ENOTSUP;
1825 *(uint8_t *)arg = b;
1826 break;
1827 case CHR_IOCTL_PP_WRITE_CONTROL:
1828 b = *(uint8_t *)arg;
1829 if (ioctl(fd, PPWCONTROL, &b) < 0)
1830 return -ENOTSUP;
1831 break;
1832 case CHR_IOCTL_PP_READ_STATUS:
1833 if (ioctl(fd, PPRSTATUS, &b) < 0)
1834 return -ENOTSUP;
1835 *(uint8_t *)arg = b;
1836 break;
1837 default:
1838 return -ENOTSUP;
1840 return 0;
1843 static CharDriverState *qemu_chr_open_pp(const char *filename)
1845 CharDriverState *chr;
1846 int fd;
1848 fd = open(filename, O_RDWR);
1849 if (fd < 0)
1850 return NULL;
1852 if (ioctl(fd, PPCLAIM) < 0) {
1853 close(fd);
1854 return NULL;
1857 chr = qemu_mallocz(sizeof(CharDriverState));
1858 if (!chr) {
1859 close(fd);
1860 return NULL;
1862 chr->opaque = (void *)fd;
1863 chr->chr_write = null_chr_write;
1864 chr->chr_ioctl = pp_ioctl;
1866 qemu_chr_reset(chr);
1868 return chr;
1871 #else
1872 static CharDriverState *qemu_chr_open_pty(void)
1874 return NULL;
1876 #endif
1878 #endif /* !defined(_WIN32) */
1880 #ifdef _WIN32
1881 typedef struct {
1882 CharDriverState *chr;
1883 int max_size;
1884 HANDLE hcom, hrecv, hsend;
1885 OVERLAPPED orecv, osend;
1886 BOOL fpipe;
1887 DWORD len;
1888 } WinCharState;
1890 #define NSENDBUF 2048
1891 #define NRECVBUF 2048
1892 #define MAXCONNECT 1
1893 #define NTIMEOUT 5000
1895 static int win_chr_poll(void *opaque);
1896 static int win_chr_pipe_poll(void *opaque);
1898 static void win_chr_close2(WinCharState *s)
1900 if (s->hsend) {
1901 CloseHandle(s->hsend);
1902 s->hsend = NULL;
1904 if (s->hrecv) {
1905 CloseHandle(s->hrecv);
1906 s->hrecv = NULL;
1908 if (s->hcom) {
1909 CloseHandle(s->hcom);
1910 s->hcom = NULL;
1912 if (s->fpipe)
1913 qemu_del_polling_cb(win_chr_pipe_poll, s);
1914 else
1915 qemu_del_polling_cb(win_chr_poll, s);
1918 static void win_chr_close(CharDriverState *chr)
1920 WinCharState *s = chr->opaque;
1921 win_chr_close2(s);
1924 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
1926 COMMCONFIG comcfg;
1927 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1928 COMSTAT comstat;
1929 DWORD size;
1930 DWORD err;
1932 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1933 if (!s->hsend) {
1934 fprintf(stderr, "Failed CreateEvent\n");
1935 goto fail;
1937 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1938 if (!s->hrecv) {
1939 fprintf(stderr, "Failed CreateEvent\n");
1940 goto fail;
1943 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1944 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1945 if (s->hcom == INVALID_HANDLE_VALUE) {
1946 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1947 s->hcom = NULL;
1948 goto fail;
1951 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1952 fprintf(stderr, "Failed SetupComm\n");
1953 goto fail;
1956 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1957 size = sizeof(COMMCONFIG);
1958 GetDefaultCommConfig(filename, &comcfg, &size);
1959 comcfg.dcb.DCBlength = sizeof(DCB);
1960 CommConfigDialog(filename, NULL, &comcfg);
1962 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1963 fprintf(stderr, "Failed SetCommState\n");
1964 goto fail;
1967 if (!SetCommMask(s->hcom, EV_ERR)) {
1968 fprintf(stderr, "Failed SetCommMask\n");
1969 goto fail;
1972 cto.ReadIntervalTimeout = MAXDWORD;
1973 if (!SetCommTimeouts(s->hcom, &cto)) {
1974 fprintf(stderr, "Failed SetCommTimeouts\n");
1975 goto fail;
1978 if (!ClearCommError(s->hcom, &err, &comstat)) {
1979 fprintf(stderr, "Failed ClearCommError\n");
1980 goto fail;
1982 s->chr = chr;
1983 qemu_add_polling_cb(win_chr_poll, s);
1984 return 0;
1986 fail:
1987 win_chr_close2(s);
1988 return -1;
1991 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1993 WinCharState *s = chr->opaque;
1994 DWORD len, ret, size, err;
1996 len = len1;
1997 ZeroMemory(&s->osend, sizeof(s->osend));
1998 s->osend.hEvent = s->hsend;
1999 while (len > 0) {
2000 if (s->hsend)
2001 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2002 else
2003 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2004 if (!ret) {
2005 err = GetLastError();
2006 if (err == ERROR_IO_PENDING) {
2007 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2008 if (ret) {
2009 buf += size;
2010 len -= size;
2011 } else {
2012 break;
2014 } else {
2015 break;
2017 } else {
2018 buf += size;
2019 len -= size;
2022 return len1 - len;
2025 static int win_chr_read_poll(WinCharState *s)
2027 s->max_size = qemu_chr_can_read(s->chr);
2028 return s->max_size;
2031 static void win_chr_readfile(WinCharState *s)
2033 int ret, err;
2034 uint8_t buf[1024];
2035 DWORD size;
2037 ZeroMemory(&s->orecv, sizeof(s->orecv));
2038 s->orecv.hEvent = s->hrecv;
2039 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2040 if (!ret) {
2041 err = GetLastError();
2042 if (err == ERROR_IO_PENDING) {
2043 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2047 if (size > 0) {
2048 qemu_chr_read(s->chr, buf, size);
2052 static void win_chr_read(WinCharState *s)
2054 if (s->len > s->max_size)
2055 s->len = s->max_size;
2056 if (s->len == 0)
2057 return;
2059 win_chr_readfile(s);
2062 static int win_chr_poll(void *opaque)
2064 WinCharState *s = opaque;
2065 COMSTAT status;
2066 DWORD comerr;
2068 ClearCommError(s->hcom, &comerr, &status);
2069 if (status.cbInQue > 0) {
2070 s->len = status.cbInQue;
2071 win_chr_read_poll(s);
2072 win_chr_read(s);
2073 return 1;
2075 return 0;
2078 static CharDriverState *qemu_chr_open_win(const char *filename)
2080 CharDriverState *chr;
2081 WinCharState *s;
2083 chr = qemu_mallocz(sizeof(CharDriverState));
2084 if (!chr)
2085 return NULL;
2086 s = qemu_mallocz(sizeof(WinCharState));
2087 if (!s) {
2088 free(chr);
2089 return NULL;
2091 chr->opaque = s;
2092 chr->chr_write = win_chr_write;
2093 chr->chr_close = win_chr_close;
2095 if (win_chr_init(s, chr, filename) < 0) {
2096 free(s);
2097 free(chr);
2098 return NULL;
2100 qemu_chr_reset(chr);
2101 return chr;
2104 static int win_chr_pipe_poll(void *opaque)
2106 WinCharState *s = opaque;
2107 DWORD size;
2109 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2110 if (size > 0) {
2111 s->len = size;
2112 win_chr_read_poll(s);
2113 win_chr_read(s);
2114 return 1;
2116 return 0;
2119 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2121 OVERLAPPED ov;
2122 int ret;
2123 DWORD size;
2124 char openname[256];
2126 s->fpipe = TRUE;
2128 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2129 if (!s->hsend) {
2130 fprintf(stderr, "Failed CreateEvent\n");
2131 goto fail;
2133 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2134 if (!s->hrecv) {
2135 fprintf(stderr, "Failed CreateEvent\n");
2136 goto fail;
2139 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2140 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2141 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2142 PIPE_WAIT,
2143 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2144 if (s->hcom == INVALID_HANDLE_VALUE) {
2145 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2146 s->hcom = NULL;
2147 goto fail;
2150 ZeroMemory(&ov, sizeof(ov));
2151 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2152 ret = ConnectNamedPipe(s->hcom, &ov);
2153 if (ret) {
2154 fprintf(stderr, "Failed ConnectNamedPipe\n");
2155 goto fail;
2158 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2159 if (!ret) {
2160 fprintf(stderr, "Failed GetOverlappedResult\n");
2161 if (ov.hEvent) {
2162 CloseHandle(ov.hEvent);
2163 ov.hEvent = NULL;
2165 goto fail;
2168 if (ov.hEvent) {
2169 CloseHandle(ov.hEvent);
2170 ov.hEvent = NULL;
2172 qemu_add_polling_cb(win_chr_pipe_poll, s);
2173 return 0;
2175 fail:
2176 win_chr_close2(s);
2177 return -1;
2181 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2183 CharDriverState *chr;
2184 WinCharState *s;
2186 chr = qemu_mallocz(sizeof(CharDriverState));
2187 if (!chr)
2188 return NULL;
2189 s = qemu_mallocz(sizeof(WinCharState));
2190 if (!s) {
2191 free(chr);
2192 return NULL;
2194 chr->opaque = s;
2195 chr->chr_write = win_chr_write;
2196 chr->chr_close = win_chr_close;
2198 if (win_chr_pipe_init(s, filename) < 0) {
2199 free(s);
2200 free(chr);
2201 return NULL;
2203 qemu_chr_reset(chr);
2204 return chr;
2207 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2209 CharDriverState *chr;
2210 WinCharState *s;
2212 chr = qemu_mallocz(sizeof(CharDriverState));
2213 if (!chr)
2214 return NULL;
2215 s = qemu_mallocz(sizeof(WinCharState));
2216 if (!s) {
2217 free(chr);
2218 return NULL;
2220 s->hcom = fd_out;
2221 chr->opaque = s;
2222 chr->chr_write = win_chr_write;
2223 qemu_chr_reset(chr);
2224 return chr;
2227 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2229 HANDLE fd_out;
2231 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2232 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2233 if (fd_out == INVALID_HANDLE_VALUE)
2234 return NULL;
2236 return qemu_chr_open_win_file(fd_out);
2238 #endif
2240 /***********************************************************/
2241 /* UDP Net console */
2243 typedef struct {
2244 int fd;
2245 struct sockaddr_in daddr;
2246 char buf[1024];
2247 int bufcnt;
2248 int bufptr;
2249 int max_size;
2250 } NetCharDriver;
2252 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2254 NetCharDriver *s = chr->opaque;
2256 return sendto(s->fd, buf, len, 0,
2257 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2260 static int udp_chr_read_poll(void *opaque)
2262 CharDriverState *chr = opaque;
2263 NetCharDriver *s = chr->opaque;
2265 s->max_size = qemu_chr_can_read(chr);
2267 /* If there were any stray characters in the queue process them
2268 * first
2270 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2271 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2272 s->bufptr++;
2273 s->max_size = qemu_chr_can_read(chr);
2275 return s->max_size;
2278 static void udp_chr_read(void *opaque)
2280 CharDriverState *chr = opaque;
2281 NetCharDriver *s = chr->opaque;
2283 if (s->max_size == 0)
2284 return;
2285 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2286 s->bufptr = s->bufcnt;
2287 if (s->bufcnt <= 0)
2288 return;
2290 s->bufptr = 0;
2291 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2292 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2293 s->bufptr++;
2294 s->max_size = qemu_chr_can_read(chr);
2298 static void udp_chr_update_read_handler(CharDriverState *chr)
2300 NetCharDriver *s = chr->opaque;
2302 if (s->fd >= 0) {
2303 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2304 udp_chr_read, NULL, chr);
2308 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2309 #ifndef _WIN32
2310 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2311 #endif
2312 int parse_host_src_port(struct sockaddr_in *haddr,
2313 struct sockaddr_in *saddr,
2314 const char *str);
2316 static CharDriverState *qemu_chr_open_udp(const char *def)
2318 CharDriverState *chr = NULL;
2319 NetCharDriver *s = NULL;
2320 int fd = -1;
2321 struct sockaddr_in saddr;
2323 chr = qemu_mallocz(sizeof(CharDriverState));
2324 if (!chr)
2325 goto return_err;
2326 s = qemu_mallocz(sizeof(NetCharDriver));
2327 if (!s)
2328 goto return_err;
2330 fd = socket(PF_INET, SOCK_DGRAM, 0);
2331 if (fd < 0) {
2332 perror("socket(PF_INET, SOCK_DGRAM)");
2333 goto return_err;
2336 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2337 printf("Could not parse: %s\n", def);
2338 goto return_err;
2341 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2343 perror("bind");
2344 goto return_err;
2347 s->fd = fd;
2348 s->bufcnt = 0;
2349 s->bufptr = 0;
2350 chr->opaque = s;
2351 chr->chr_write = udp_chr_write;
2352 chr->chr_update_read_handler = udp_chr_update_read_handler;
2353 return chr;
2355 return_err:
2356 if (chr)
2357 free(chr);
2358 if (s)
2359 free(s);
2360 if (fd >= 0)
2361 closesocket(fd);
2362 return NULL;
2365 /***********************************************************/
2366 /* TCP Net console */
2368 typedef struct {
2369 int fd, listen_fd;
2370 int connected;
2371 int max_size;
2372 int do_telnetopt;
2373 int do_nodelay;
2374 int is_unix;
2375 } TCPCharDriver;
2377 static void tcp_chr_accept(void *opaque);
2379 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2381 TCPCharDriver *s = chr->opaque;
2382 if (s->connected) {
2383 return send_all(s->fd, buf, len);
2384 } else {
2385 /* XXX: indicate an error ? */
2386 return len;
2390 static int tcp_chr_read_poll(void *opaque)
2392 CharDriverState *chr = opaque;
2393 TCPCharDriver *s = chr->opaque;
2394 if (!s->connected)
2395 return 0;
2396 s->max_size = qemu_chr_can_read(chr);
2397 return s->max_size;
2400 #define IAC 255
2401 #define IAC_BREAK 243
2402 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2403 TCPCharDriver *s,
2404 char *buf, int *size)
2406 /* Handle any telnet client's basic IAC options to satisfy char by
2407 * char mode with no echo. All IAC options will be removed from
2408 * the buf and the do_telnetopt variable will be used to track the
2409 * state of the width of the IAC information.
2411 * IAC commands come in sets of 3 bytes with the exception of the
2412 * "IAC BREAK" command and the double IAC.
2415 int i;
2416 int j = 0;
2418 for (i = 0; i < *size; i++) {
2419 if (s->do_telnetopt > 1) {
2420 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2421 /* Double IAC means send an IAC */
2422 if (j != i)
2423 buf[j] = buf[i];
2424 j++;
2425 s->do_telnetopt = 1;
2426 } else {
2427 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2428 /* Handle IAC break commands by sending a serial break */
2429 qemu_chr_event(chr, CHR_EVENT_BREAK);
2430 s->do_telnetopt++;
2432 s->do_telnetopt++;
2434 if (s->do_telnetopt >= 4) {
2435 s->do_telnetopt = 1;
2437 } else {
2438 if ((unsigned char)buf[i] == IAC) {
2439 s->do_telnetopt = 2;
2440 } else {
2441 if (j != i)
2442 buf[j] = buf[i];
2443 j++;
2447 *size = j;
2450 static void tcp_chr_read(void *opaque)
2452 CharDriverState *chr = opaque;
2453 TCPCharDriver *s = chr->opaque;
2454 uint8_t buf[1024];
2455 int len, size;
2457 if (!s->connected || s->max_size <= 0)
2458 return;
2459 len = sizeof(buf);
2460 if (len > s->max_size)
2461 len = s->max_size;
2462 size = recv(s->fd, buf, len, 0);
2463 if (size == 0) {
2464 /* connection closed */
2465 s->connected = 0;
2466 if (s->listen_fd >= 0) {
2467 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2469 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2470 closesocket(s->fd);
2471 s->fd = -1;
2472 } else if (size > 0) {
2473 if (s->do_telnetopt)
2474 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2475 if (size > 0)
2476 qemu_chr_read(chr, buf, size);
2480 static void tcp_chr_connect(void *opaque)
2482 CharDriverState *chr = opaque;
2483 TCPCharDriver *s = chr->opaque;
2485 s->connected = 1;
2486 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2487 tcp_chr_read, NULL, chr);
2488 qemu_chr_reset(chr);
2491 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2492 static void tcp_chr_telnet_init(int fd)
2494 char buf[3];
2495 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2496 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2497 send(fd, (char *)buf, 3, 0);
2498 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2499 send(fd, (char *)buf, 3, 0);
2500 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2501 send(fd, (char *)buf, 3, 0);
2502 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2503 send(fd, (char *)buf, 3, 0);
2506 static void socket_set_nodelay(int fd)
2508 int val = 1;
2509 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2512 static void tcp_chr_accept(void *opaque)
2514 CharDriverState *chr = opaque;
2515 TCPCharDriver *s = chr->opaque;
2516 struct sockaddr_in saddr;
2517 #ifndef _WIN32
2518 struct sockaddr_un uaddr;
2519 #endif
2520 struct sockaddr *addr;
2521 socklen_t len;
2522 int fd;
2524 for(;;) {
2525 #ifndef _WIN32
2526 if (s->is_unix) {
2527 len = sizeof(uaddr);
2528 addr = (struct sockaddr *)&uaddr;
2529 } else
2530 #endif
2532 len = sizeof(saddr);
2533 addr = (struct sockaddr *)&saddr;
2535 fd = accept(s->listen_fd, addr, &len);
2536 if (fd < 0 && errno != EINTR) {
2537 return;
2538 } else if (fd >= 0) {
2539 if (s->do_telnetopt)
2540 tcp_chr_telnet_init(fd);
2541 break;
2544 socket_set_nonblock(fd);
2545 if (s->do_nodelay)
2546 socket_set_nodelay(fd);
2547 s->fd = fd;
2548 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2549 tcp_chr_connect(chr);
2552 static void tcp_chr_close(CharDriverState *chr)
2554 TCPCharDriver *s = chr->opaque;
2555 if (s->fd >= 0)
2556 closesocket(s->fd);
2557 if (s->listen_fd >= 0)
2558 closesocket(s->listen_fd);
2559 qemu_free(s);
2562 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2563 int is_telnet,
2564 int is_unix)
2566 CharDriverState *chr = NULL;
2567 TCPCharDriver *s = NULL;
2568 int fd = -1, ret, err, val;
2569 int is_listen = 0;
2570 int is_waitconnect = 1;
2571 int do_nodelay = 0;
2572 const char *ptr;
2573 struct sockaddr_in saddr;
2574 #ifndef _WIN32
2575 struct sockaddr_un uaddr;
2576 #endif
2577 struct sockaddr *addr;
2578 socklen_t addrlen;
2580 #ifndef _WIN32
2581 if (is_unix) {
2582 addr = (struct sockaddr *)&uaddr;
2583 addrlen = sizeof(uaddr);
2584 if (parse_unix_path(&uaddr, host_str) < 0)
2585 goto fail;
2586 } else
2587 #endif
2589 addr = (struct sockaddr *)&saddr;
2590 addrlen = sizeof(saddr);
2591 if (parse_host_port(&saddr, host_str) < 0)
2592 goto fail;
2595 ptr = host_str;
2596 while((ptr = strchr(ptr,','))) {
2597 ptr++;
2598 if (!strncmp(ptr,"server",6)) {
2599 is_listen = 1;
2600 } else if (!strncmp(ptr,"nowait",6)) {
2601 is_waitconnect = 0;
2602 } else if (!strncmp(ptr,"nodelay",6)) {
2603 do_nodelay = 1;
2604 } else {
2605 printf("Unknown option: %s\n", ptr);
2606 goto fail;
2609 if (!is_listen)
2610 is_waitconnect = 0;
2612 chr = qemu_mallocz(sizeof(CharDriverState));
2613 if (!chr)
2614 goto fail;
2615 s = qemu_mallocz(sizeof(TCPCharDriver));
2616 if (!s)
2617 goto fail;
2619 #ifndef _WIN32
2620 if (is_unix)
2621 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2622 else
2623 #endif
2624 fd = socket(PF_INET, SOCK_STREAM, 0);
2626 if (fd < 0)
2627 goto fail;
2629 if (!is_waitconnect)
2630 socket_set_nonblock(fd);
2632 s->connected = 0;
2633 s->fd = -1;
2634 s->listen_fd = -1;
2635 s->is_unix = is_unix;
2636 s->do_nodelay = do_nodelay && !is_unix;
2638 chr->opaque = s;
2639 chr->chr_write = tcp_chr_write;
2640 chr->chr_close = tcp_chr_close;
2642 if (is_listen) {
2643 /* allow fast reuse */
2644 #ifndef _WIN32
2645 if (is_unix) {
2646 char path[109];
2647 strncpy(path, uaddr.sun_path, 108);
2648 path[108] = 0;
2649 unlink(path);
2650 } else
2651 #endif
2653 val = 1;
2654 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2657 ret = bind(fd, addr, addrlen);
2658 if (ret < 0)
2659 goto fail;
2661 ret = listen(fd, 0);
2662 if (ret < 0)
2663 goto fail;
2665 s->listen_fd = fd;
2666 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2667 if (is_telnet)
2668 s->do_telnetopt = 1;
2669 } else {
2670 for(;;) {
2671 ret = connect(fd, addr, addrlen);
2672 if (ret < 0) {
2673 err = socket_error();
2674 if (err == EINTR || err == EWOULDBLOCK) {
2675 } else if (err == EINPROGRESS) {
2676 break;
2677 } else {
2678 goto fail;
2680 } else {
2681 s->connected = 1;
2682 break;
2685 s->fd = fd;
2686 socket_set_nodelay(fd);
2687 if (s->connected)
2688 tcp_chr_connect(chr);
2689 else
2690 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2693 if (is_listen && is_waitconnect) {
2694 printf("QEMU waiting for connection on: %s\n", host_str);
2695 tcp_chr_accept(chr);
2696 socket_set_nonblock(s->listen_fd);
2699 return chr;
2700 fail:
2701 if (fd >= 0)
2702 closesocket(fd);
2703 qemu_free(s);
2704 qemu_free(chr);
2705 return NULL;
2708 CharDriverState *qemu_chr_open(const char *filename)
2710 const char *p;
2712 if (!strcmp(filename, "vc")) {
2713 return text_console_init(&display_state);
2714 } else if (!strcmp(filename, "null")) {
2715 return qemu_chr_open_null();
2716 } else
2717 if (strstart(filename, "tcp:", &p)) {
2718 return qemu_chr_open_tcp(p, 0, 0);
2719 } else
2720 if (strstart(filename, "telnet:", &p)) {
2721 return qemu_chr_open_tcp(p, 1, 0);
2722 } else
2723 if (strstart(filename, "udp:", &p)) {
2724 return qemu_chr_open_udp(p);
2725 } else
2726 #ifndef _WIN32
2727 if (strstart(filename, "unix:", &p)) {
2728 return qemu_chr_open_tcp(p, 0, 1);
2729 } else if (strstart(filename, "file:", &p)) {
2730 return qemu_chr_open_file_out(p);
2731 } else if (strstart(filename, "pipe:", &p)) {
2732 return qemu_chr_open_pipe(p);
2733 } else if (!strcmp(filename, "pty")) {
2734 return qemu_chr_open_pty();
2735 } else if (!strcmp(filename, "stdio")) {
2736 return qemu_chr_open_stdio();
2737 } else
2738 #endif
2739 #if defined(__linux__)
2740 if (strstart(filename, "/dev/parport", NULL)) {
2741 return qemu_chr_open_pp(filename);
2742 } else
2743 if (strstart(filename, "/dev/", NULL)) {
2744 return qemu_chr_open_tty(filename);
2745 } else
2746 #endif
2747 #ifdef _WIN32
2748 if (strstart(filename, "COM", NULL)) {
2749 return qemu_chr_open_win(filename);
2750 } else
2751 if (strstart(filename, "pipe:", &p)) {
2752 return qemu_chr_open_win_pipe(p);
2753 } else
2754 if (strstart(filename, "file:", &p)) {
2755 return qemu_chr_open_win_file_out(p);
2757 #endif
2759 return NULL;
2763 void qemu_chr_close(CharDriverState *chr)
2765 if (chr->chr_close)
2766 chr->chr_close(chr);
2769 /***********************************************************/
2770 /* network device redirectors */
2772 void hex_dump(FILE *f, const uint8_t *buf, int size)
2774 int len, i, j, c;
2776 for(i=0;i<size;i+=16) {
2777 len = size - i;
2778 if (len > 16)
2779 len = 16;
2780 fprintf(f, "%08x ", i);
2781 for(j=0;j<16;j++) {
2782 if (j < len)
2783 fprintf(f, " %02x", buf[i+j]);
2784 else
2785 fprintf(f, " ");
2787 fprintf(f, " ");
2788 for(j=0;j<len;j++) {
2789 c = buf[i+j];
2790 if (c < ' ' || c > '~')
2791 c = '.';
2792 fprintf(f, "%c", c);
2794 fprintf(f, "\n");
2798 static int parse_macaddr(uint8_t *macaddr, const char *p)
2800 int i;
2801 for(i = 0; i < 6; i++) {
2802 macaddr[i] = strtol(p, (char **)&p, 16);
2803 if (i == 5) {
2804 if (*p != '\0')
2805 return -1;
2806 } else {
2807 if (*p != ':')
2808 return -1;
2809 p++;
2812 return 0;
2815 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2817 const char *p, *p1;
2818 int len;
2819 p = *pp;
2820 p1 = strchr(p, sep);
2821 if (!p1)
2822 return -1;
2823 len = p1 - p;
2824 p1++;
2825 if (buf_size > 0) {
2826 if (len > buf_size - 1)
2827 len = buf_size - 1;
2828 memcpy(buf, p, len);
2829 buf[len] = '\0';
2831 *pp = p1;
2832 return 0;
2835 int parse_host_src_port(struct sockaddr_in *haddr,
2836 struct sockaddr_in *saddr,
2837 const char *input_str)
2839 char *str = strdup(input_str);
2840 char *host_str = str;
2841 char *src_str;
2842 char *ptr;
2845 * Chop off any extra arguments at the end of the string which
2846 * would start with a comma, then fill in the src port information
2847 * if it was provided else use the "any address" and "any port".
2849 if ((ptr = strchr(str,',')))
2850 *ptr = '\0';
2852 if ((src_str = strchr(input_str,'@'))) {
2853 *src_str = '\0';
2854 src_str++;
2857 if (parse_host_port(haddr, host_str) < 0)
2858 goto fail;
2860 if (!src_str || *src_str == '\0')
2861 src_str = ":0";
2863 if (parse_host_port(saddr, src_str) < 0)
2864 goto fail;
2866 free(str);
2867 return(0);
2869 fail:
2870 free(str);
2871 return -1;
2874 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2876 char buf[512];
2877 struct hostent *he;
2878 const char *p, *r;
2879 int port;
2881 p = str;
2882 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2883 return -1;
2884 saddr->sin_family = AF_INET;
2885 if (buf[0] == '\0') {
2886 saddr->sin_addr.s_addr = 0;
2887 } else {
2888 if (isdigit(buf[0])) {
2889 if (!inet_aton(buf, &saddr->sin_addr))
2890 return -1;
2891 } else {
2892 if ((he = gethostbyname(buf)) == NULL)
2893 return - 1;
2894 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2897 port = strtol(p, (char **)&r, 0);
2898 if (r == p)
2899 return -1;
2900 saddr->sin_port = htons(port);
2901 return 0;
2904 #ifndef _WIN32
2905 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2907 const char *p;
2908 int len;
2910 len = MIN(108, strlen(str));
2911 p = strchr(str, ',');
2912 if (p)
2913 len = MIN(len, p - str);
2915 memset(uaddr, 0, sizeof(*uaddr));
2917 uaddr->sun_family = AF_UNIX;
2918 memcpy(uaddr->sun_path, str, len);
2920 return 0;
2922 #endif
2924 /* find or alloc a new VLAN */
2925 VLANState *qemu_find_vlan(int id)
2927 VLANState **pvlan, *vlan;
2928 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2929 if (vlan->id == id)
2930 return vlan;
2932 vlan = qemu_mallocz(sizeof(VLANState));
2933 if (!vlan)
2934 return NULL;
2935 vlan->id = id;
2936 vlan->next = NULL;
2937 pvlan = &first_vlan;
2938 while (*pvlan != NULL)
2939 pvlan = &(*pvlan)->next;
2940 *pvlan = vlan;
2941 return vlan;
2944 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2945 IOReadHandler *fd_read,
2946 IOCanRWHandler *fd_can_read,
2947 void *opaque)
2949 VLANClientState *vc, **pvc;
2950 vc = qemu_mallocz(sizeof(VLANClientState));
2951 if (!vc)
2952 return NULL;
2953 vc->fd_read = fd_read;
2954 vc->fd_can_read = fd_can_read;
2955 vc->opaque = opaque;
2956 vc->vlan = vlan;
2958 vc->next = NULL;
2959 pvc = &vlan->first_client;
2960 while (*pvc != NULL)
2961 pvc = &(*pvc)->next;
2962 *pvc = vc;
2963 return vc;
2966 int qemu_can_send_packet(VLANClientState *vc1)
2968 VLANState *vlan = vc1->vlan;
2969 VLANClientState *vc;
2971 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2972 if (vc != vc1) {
2973 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2974 return 0;
2977 return 1;
2980 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2982 VLANState *vlan = vc1->vlan;
2983 VLANClientState *vc;
2985 #if 0
2986 printf("vlan %d send:\n", vlan->id);
2987 hex_dump(stdout, buf, size);
2988 #endif
2989 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2990 if (vc != vc1) {
2991 vc->fd_read(vc->opaque, buf, size);
2996 #if defined(CONFIG_SLIRP)
2998 /* slirp network adapter */
3000 static int slirp_inited;
3001 static VLANClientState *slirp_vc;
3003 int slirp_can_output(void)
3005 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3008 void slirp_output(const uint8_t *pkt, int pkt_len)
3010 #if 0
3011 printf("slirp output:\n");
3012 hex_dump(stdout, pkt, pkt_len);
3013 #endif
3014 if (!slirp_vc)
3015 return;
3016 qemu_send_packet(slirp_vc, pkt, pkt_len);
3019 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3021 #if 0
3022 printf("slirp input:\n");
3023 hex_dump(stdout, buf, size);
3024 #endif
3025 slirp_input(buf, size);
3028 static int net_slirp_init(VLANState *vlan)
3030 if (!slirp_inited) {
3031 slirp_inited = 1;
3032 slirp_init();
3034 slirp_vc = qemu_new_vlan_client(vlan,
3035 slirp_receive, NULL, NULL);
3036 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3037 return 0;
3040 static void net_slirp_redir(const char *redir_str)
3042 int is_udp;
3043 char buf[256], *r;
3044 const char *p;
3045 struct in_addr guest_addr;
3046 int host_port, guest_port;
3048 if (!slirp_inited) {
3049 slirp_inited = 1;
3050 slirp_init();
3053 p = redir_str;
3054 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3055 goto fail;
3056 if (!strcmp(buf, "tcp")) {
3057 is_udp = 0;
3058 } else if (!strcmp(buf, "udp")) {
3059 is_udp = 1;
3060 } else {
3061 goto fail;
3064 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3065 goto fail;
3066 host_port = strtol(buf, &r, 0);
3067 if (r == buf)
3068 goto fail;
3070 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3071 goto fail;
3072 if (buf[0] == '\0') {
3073 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3075 if (!inet_aton(buf, &guest_addr))
3076 goto fail;
3078 guest_port = strtol(p, &r, 0);
3079 if (r == p)
3080 goto fail;
3082 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3083 fprintf(stderr, "qemu: could not set up redirection\n");
3084 exit(1);
3086 return;
3087 fail:
3088 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3089 exit(1);
3092 #ifndef _WIN32
3094 char smb_dir[1024];
3096 static void smb_exit(void)
3098 DIR *d;
3099 struct dirent *de;
3100 char filename[1024];
3102 /* erase all the files in the directory */
3103 d = opendir(smb_dir);
3104 for(;;) {
3105 de = readdir(d);
3106 if (!de)
3107 break;
3108 if (strcmp(de->d_name, ".") != 0 &&
3109 strcmp(de->d_name, "..") != 0) {
3110 snprintf(filename, sizeof(filename), "%s/%s",
3111 smb_dir, de->d_name);
3112 unlink(filename);
3115 closedir(d);
3116 rmdir(smb_dir);
3119 /* automatic user mode samba server configuration */
3120 void net_slirp_smb(const char *exported_dir)
3122 char smb_conf[1024];
3123 char smb_cmdline[1024];
3124 FILE *f;
3126 if (!slirp_inited) {
3127 slirp_inited = 1;
3128 slirp_init();
3131 /* XXX: better tmp dir construction */
3132 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3133 if (mkdir(smb_dir, 0700) < 0) {
3134 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3135 exit(1);
3137 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3139 f = fopen(smb_conf, "w");
3140 if (!f) {
3141 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3142 exit(1);
3144 fprintf(f,
3145 "[global]\n"
3146 "private dir=%s\n"
3147 "smb ports=0\n"
3148 "socket address=127.0.0.1\n"
3149 "pid directory=%s\n"
3150 "lock directory=%s\n"
3151 "log file=%s/log.smbd\n"
3152 "smb passwd file=%s/smbpasswd\n"
3153 "security = share\n"
3154 "[qemu]\n"
3155 "path=%s\n"
3156 "read only=no\n"
3157 "guest ok=yes\n",
3158 smb_dir,
3159 smb_dir,
3160 smb_dir,
3161 smb_dir,
3162 smb_dir,
3163 exported_dir
3165 fclose(f);
3166 atexit(smb_exit);
3168 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3169 SMBD_COMMAND, smb_conf);
3171 slirp_add_exec(0, smb_cmdline, 4, 139);
3174 #endif /* !defined(_WIN32) */
3176 #endif /* CONFIG_SLIRP */
3178 #if !defined(_WIN32)
3180 typedef struct TAPState {
3181 VLANClientState *vc;
3182 int fd;
3183 } TAPState;
3185 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3187 TAPState *s = opaque;
3188 int ret;
3189 for(;;) {
3190 ret = write(s->fd, buf, size);
3191 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3192 } else {
3193 break;
3198 static void tap_send(void *opaque)
3200 TAPState *s = opaque;
3201 uint8_t buf[4096];
3202 int size;
3204 size = read(s->fd, buf, sizeof(buf));
3205 if (size > 0) {
3206 qemu_send_packet(s->vc, buf, size);
3210 /* fd support */
3212 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3214 TAPState *s;
3216 s = qemu_mallocz(sizeof(TAPState));
3217 if (!s)
3218 return NULL;
3219 s->fd = fd;
3220 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3221 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3222 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3223 return s;
3226 #ifdef _BSD
3227 static int tap_open(char *ifname, int ifname_size)
3229 int fd;
3230 char *dev;
3231 struct stat s;
3233 fd = open("/dev/tap", O_RDWR);
3234 if (fd < 0) {
3235 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3236 return -1;
3239 fstat(fd, &s);
3240 dev = devname(s.st_rdev, S_IFCHR);
3241 pstrcpy(ifname, ifname_size, dev);
3243 fcntl(fd, F_SETFL, O_NONBLOCK);
3244 return fd;
3246 #elif defined(__sun__)
3247 static int tap_open(char *ifname, int ifname_size)
3249 fprintf(stderr, "warning: tap_open not yet implemented\n");
3250 return -1;
3252 #else
3253 static int tap_open(char *ifname, int ifname_size)
3255 struct ifreq ifr;
3256 int fd, ret;
3258 fd = open("/dev/net/tun", O_RDWR);
3259 if (fd < 0) {
3260 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3261 return -1;
3263 memset(&ifr, 0, sizeof(ifr));
3264 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3265 if (ifname[0] != '\0')
3266 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3267 else
3268 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3269 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3270 if (ret != 0) {
3271 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3272 close(fd);
3273 return -1;
3275 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3276 fcntl(fd, F_SETFL, O_NONBLOCK);
3277 return fd;
3279 #endif
3281 static int net_tap_init(VLANState *vlan, const char *ifname1,
3282 const char *setup_script)
3284 TAPState *s;
3285 int pid, status, fd;
3286 char *args[3];
3287 char **parg;
3288 char ifname[128];
3290 if (ifname1 != NULL)
3291 pstrcpy(ifname, sizeof(ifname), ifname1);
3292 else
3293 ifname[0] = '\0';
3294 fd = tap_open(ifname, sizeof(ifname));
3295 if (fd < 0)
3296 return -1;
3298 if (!setup_script || !strcmp(setup_script, "no"))
3299 setup_script = "";
3300 if (setup_script[0] != '\0') {
3301 /* try to launch network init script */
3302 pid = fork();
3303 if (pid >= 0) {
3304 if (pid == 0) {
3305 parg = args;
3306 *parg++ = (char *)setup_script;
3307 *parg++ = ifname;
3308 *parg++ = NULL;
3309 execv(setup_script, args);
3310 _exit(1);
3312 while (waitpid(pid, &status, 0) != pid);
3313 if (!WIFEXITED(status) ||
3314 WEXITSTATUS(status) != 0) {
3315 fprintf(stderr, "%s: could not launch network script\n",
3316 setup_script);
3317 return -1;
3321 s = net_tap_fd_init(vlan, fd);
3322 if (!s)
3323 return -1;
3324 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3325 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3326 return 0;
3329 #endif /* !_WIN32 */
3331 /* network connection */
3332 typedef struct NetSocketState {
3333 VLANClientState *vc;
3334 int fd;
3335 int state; /* 0 = getting length, 1 = getting data */
3336 int index;
3337 int packet_len;
3338 uint8_t buf[4096];
3339 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3340 } NetSocketState;
3342 typedef struct NetSocketListenState {
3343 VLANState *vlan;
3344 int fd;
3345 } NetSocketListenState;
3347 /* XXX: we consider we can send the whole packet without blocking */
3348 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3350 NetSocketState *s = opaque;
3351 uint32_t len;
3352 len = htonl(size);
3354 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3355 send_all(s->fd, buf, size);
3358 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3360 NetSocketState *s = opaque;
3361 sendto(s->fd, buf, size, 0,
3362 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3365 static void net_socket_send(void *opaque)
3367 NetSocketState *s = opaque;
3368 int l, size, err;
3369 uint8_t buf1[4096];
3370 const uint8_t *buf;
3372 size = recv(s->fd, buf1, sizeof(buf1), 0);
3373 if (size < 0) {
3374 err = socket_error();
3375 if (err != EWOULDBLOCK)
3376 goto eoc;
3377 } else if (size == 0) {
3378 /* end of connection */
3379 eoc:
3380 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3381 closesocket(s->fd);
3382 return;
3384 buf = buf1;
3385 while (size > 0) {
3386 /* reassemble a packet from the network */
3387 switch(s->state) {
3388 case 0:
3389 l = 4 - s->index;
3390 if (l > size)
3391 l = size;
3392 memcpy(s->buf + s->index, buf, l);
3393 buf += l;
3394 size -= l;
3395 s->index += l;
3396 if (s->index == 4) {
3397 /* got length */
3398 s->packet_len = ntohl(*(uint32_t *)s->buf);
3399 s->index = 0;
3400 s->state = 1;
3402 break;
3403 case 1:
3404 l = s->packet_len - s->index;
3405 if (l > size)
3406 l = size;
3407 memcpy(s->buf + s->index, buf, l);
3408 s->index += l;
3409 buf += l;
3410 size -= l;
3411 if (s->index >= s->packet_len) {
3412 qemu_send_packet(s->vc, s->buf, s->packet_len);
3413 s->index = 0;
3414 s->state = 0;
3416 break;
3421 static void net_socket_send_dgram(void *opaque)
3423 NetSocketState *s = opaque;
3424 int size;
3426 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3427 if (size < 0)
3428 return;
3429 if (size == 0) {
3430 /* end of connection */
3431 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3432 return;
3434 qemu_send_packet(s->vc, s->buf, size);
3437 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3439 struct ip_mreq imr;
3440 int fd;
3441 int val, ret;
3442 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3443 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3444 inet_ntoa(mcastaddr->sin_addr),
3445 (int)ntohl(mcastaddr->sin_addr.s_addr));
3446 return -1;
3449 fd = socket(PF_INET, SOCK_DGRAM, 0);
3450 if (fd < 0) {
3451 perror("socket(PF_INET, SOCK_DGRAM)");
3452 return -1;
3455 val = 1;
3456 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3457 (const char *)&val, sizeof(val));
3458 if (ret < 0) {
3459 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3460 goto fail;
3463 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3464 if (ret < 0) {
3465 perror("bind");
3466 goto fail;
3469 /* Add host to multicast group */
3470 imr.imr_multiaddr = mcastaddr->sin_addr;
3471 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3473 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3474 (const char *)&imr, sizeof(struct ip_mreq));
3475 if (ret < 0) {
3476 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3477 goto fail;
3480 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3481 val = 1;
3482 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3483 (const char *)&val, sizeof(val));
3484 if (ret < 0) {
3485 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3486 goto fail;
3489 socket_set_nonblock(fd);
3490 return fd;
3491 fail:
3492 if (fd >= 0)
3493 closesocket(fd);
3494 return -1;
3497 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3498 int is_connected)
3500 struct sockaddr_in saddr;
3501 int newfd;
3502 socklen_t saddr_len;
3503 NetSocketState *s;
3505 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3506 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3507 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3510 if (is_connected) {
3511 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3512 /* must be bound */
3513 if (saddr.sin_addr.s_addr==0) {
3514 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3515 fd);
3516 return NULL;
3518 /* clone dgram socket */
3519 newfd = net_socket_mcast_create(&saddr);
3520 if (newfd < 0) {
3521 /* error already reported by net_socket_mcast_create() */
3522 close(fd);
3523 return NULL;
3525 /* clone newfd to fd, close newfd */
3526 dup2(newfd, fd);
3527 close(newfd);
3529 } else {
3530 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3531 fd, strerror(errno));
3532 return NULL;
3536 s = qemu_mallocz(sizeof(NetSocketState));
3537 if (!s)
3538 return NULL;
3539 s->fd = fd;
3541 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3542 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3544 /* mcast: save bound address as dst */
3545 if (is_connected) s->dgram_dst=saddr;
3547 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3548 "socket: fd=%d (%s mcast=%s:%d)",
3549 fd, is_connected? "cloned" : "",
3550 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3551 return s;
3554 static void net_socket_connect(void *opaque)
3556 NetSocketState *s = opaque;
3557 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3560 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3561 int is_connected)
3563 NetSocketState *s;
3564 s = qemu_mallocz(sizeof(NetSocketState));
3565 if (!s)
3566 return NULL;
3567 s->fd = fd;
3568 s->vc = qemu_new_vlan_client(vlan,
3569 net_socket_receive, NULL, s);
3570 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3571 "socket: fd=%d", fd);
3572 if (is_connected) {
3573 net_socket_connect(s);
3574 } else {
3575 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3577 return s;
3580 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3581 int is_connected)
3583 int so_type=-1, optlen=sizeof(so_type);
3585 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3586 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3587 return NULL;
3589 switch(so_type) {
3590 case SOCK_DGRAM:
3591 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3592 case SOCK_STREAM:
3593 return net_socket_fd_init_stream(vlan, fd, is_connected);
3594 default:
3595 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3596 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3597 return net_socket_fd_init_stream(vlan, fd, is_connected);
3599 return NULL;
3602 static void net_socket_accept(void *opaque)
3604 NetSocketListenState *s = opaque;
3605 NetSocketState *s1;
3606 struct sockaddr_in saddr;
3607 socklen_t len;
3608 int fd;
3610 for(;;) {
3611 len = sizeof(saddr);
3612 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3613 if (fd < 0 && errno != EINTR) {
3614 return;
3615 } else if (fd >= 0) {
3616 break;
3619 s1 = net_socket_fd_init(s->vlan, fd, 1);
3620 if (!s1) {
3621 closesocket(fd);
3622 } else {
3623 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3624 "socket: connection from %s:%d",
3625 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3629 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3631 NetSocketListenState *s;
3632 int fd, val, ret;
3633 struct sockaddr_in saddr;
3635 if (parse_host_port(&saddr, host_str) < 0)
3636 return -1;
3638 s = qemu_mallocz(sizeof(NetSocketListenState));
3639 if (!s)
3640 return -1;
3642 fd = socket(PF_INET, SOCK_STREAM, 0);
3643 if (fd < 0) {
3644 perror("socket");
3645 return -1;
3647 socket_set_nonblock(fd);
3649 /* allow fast reuse */
3650 val = 1;
3651 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3653 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3654 if (ret < 0) {
3655 perror("bind");
3656 return -1;
3658 ret = listen(fd, 0);
3659 if (ret < 0) {
3660 perror("listen");
3661 return -1;
3663 s->vlan = vlan;
3664 s->fd = fd;
3665 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3666 return 0;
3669 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3671 NetSocketState *s;
3672 int fd, connected, ret, err;
3673 struct sockaddr_in saddr;
3675 if (parse_host_port(&saddr, host_str) < 0)
3676 return -1;
3678 fd = socket(PF_INET, SOCK_STREAM, 0);
3679 if (fd < 0) {
3680 perror("socket");
3681 return -1;
3683 socket_set_nonblock(fd);
3685 connected = 0;
3686 for(;;) {
3687 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3688 if (ret < 0) {
3689 err = socket_error();
3690 if (err == EINTR || err == EWOULDBLOCK) {
3691 } else if (err == EINPROGRESS) {
3692 break;
3693 } else {
3694 perror("connect");
3695 closesocket(fd);
3696 return -1;
3698 } else {
3699 connected = 1;
3700 break;
3703 s = net_socket_fd_init(vlan, fd, connected);
3704 if (!s)
3705 return -1;
3706 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3707 "socket: connect to %s:%d",
3708 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3709 return 0;
3712 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3714 NetSocketState *s;
3715 int fd;
3716 struct sockaddr_in saddr;
3718 if (parse_host_port(&saddr, host_str) < 0)
3719 return -1;
3722 fd = net_socket_mcast_create(&saddr);
3723 if (fd < 0)
3724 return -1;
3726 s = net_socket_fd_init(vlan, fd, 0);
3727 if (!s)
3728 return -1;
3730 s->dgram_dst = saddr;
3732 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3733 "socket: mcast=%s:%d",
3734 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3735 return 0;
3739 static int get_param_value(char *buf, int buf_size,
3740 const char *tag, const char *str)
3742 const char *p;
3743 char *q;
3744 char option[128];
3746 p = str;
3747 for(;;) {
3748 q = option;
3749 while (*p != '\0' && *p != '=') {
3750 if ((q - option) < sizeof(option) - 1)
3751 *q++ = *p;
3752 p++;
3754 *q = '\0';
3755 if (*p != '=')
3756 break;
3757 p++;
3758 if (!strcmp(tag, option)) {
3759 q = buf;
3760 while (*p != '\0' && *p != ',') {
3761 if ((q - buf) < buf_size - 1)
3762 *q++ = *p;
3763 p++;
3765 *q = '\0';
3766 return q - buf;
3767 } else {
3768 while (*p != '\0' && *p != ',') {
3769 p++;
3772 if (*p != ',')
3773 break;
3774 p++;
3776 return 0;
3779 static int net_client_init(const char *str)
3781 const char *p;
3782 char *q;
3783 char device[64];
3784 char buf[1024];
3785 int vlan_id, ret;
3786 VLANState *vlan;
3788 p = str;
3789 q = device;
3790 while (*p != '\0' && *p != ',') {
3791 if ((q - device) < sizeof(device) - 1)
3792 *q++ = *p;
3793 p++;
3795 *q = '\0';
3796 if (*p == ',')
3797 p++;
3798 vlan_id = 0;
3799 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3800 vlan_id = strtol(buf, NULL, 0);
3802 vlan = qemu_find_vlan(vlan_id);
3803 if (!vlan) {
3804 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3805 return -1;
3807 if (!strcmp(device, "nic")) {
3808 NICInfo *nd;
3809 uint8_t *macaddr;
3811 if (nb_nics >= MAX_NICS) {
3812 fprintf(stderr, "Too Many NICs\n");
3813 return -1;
3815 nd = &nd_table[nb_nics];
3816 macaddr = nd->macaddr;
3817 macaddr[0] = 0x52;
3818 macaddr[1] = 0x54;
3819 macaddr[2] = 0x00;
3820 macaddr[3] = 0x12;
3821 macaddr[4] = 0x34;
3822 macaddr[5] = 0x56 + nb_nics;
3824 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3825 if (parse_macaddr(macaddr, buf) < 0) {
3826 fprintf(stderr, "invalid syntax for ethernet address\n");
3827 return -1;
3830 if (get_param_value(buf, sizeof(buf), "model", p)) {
3831 nd->model = strdup(buf);
3833 nd->vlan = vlan;
3834 nb_nics++;
3835 ret = 0;
3836 } else
3837 if (!strcmp(device, "none")) {
3838 /* does nothing. It is needed to signal that no network cards
3839 are wanted */
3840 ret = 0;
3841 } else
3842 #ifdef CONFIG_SLIRP
3843 if (!strcmp(device, "user")) {
3844 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3845 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3847 ret = net_slirp_init(vlan);
3848 } else
3849 #endif
3850 #ifdef _WIN32
3851 if (!strcmp(device, "tap")) {
3852 char ifname[64];
3853 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3854 fprintf(stderr, "tap: no interface name\n");
3855 return -1;
3857 ret = tap_win32_init(vlan, ifname);
3858 } else
3859 #else
3860 if (!strcmp(device, "tap")) {
3861 char ifname[64];
3862 char setup_script[1024];
3863 int fd;
3864 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3865 fd = strtol(buf, NULL, 0);
3866 ret = -1;
3867 if (net_tap_fd_init(vlan, fd))
3868 ret = 0;
3869 } else {
3870 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3871 ifname[0] = '\0';
3873 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3874 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3876 ret = net_tap_init(vlan, ifname, setup_script);
3878 } else
3879 #endif
3880 if (!strcmp(device, "socket")) {
3881 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3882 int fd;
3883 fd = strtol(buf, NULL, 0);
3884 ret = -1;
3885 if (net_socket_fd_init(vlan, fd, 1))
3886 ret = 0;
3887 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3888 ret = net_socket_listen_init(vlan, buf);
3889 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3890 ret = net_socket_connect_init(vlan, buf);
3891 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3892 ret = net_socket_mcast_init(vlan, buf);
3893 } else {
3894 fprintf(stderr, "Unknown socket options: %s\n", p);
3895 return -1;
3897 } else
3899 fprintf(stderr, "Unknown network device: %s\n", device);
3900 return -1;
3902 if (ret < 0) {
3903 fprintf(stderr, "Could not initialize device '%s'\n", device);
3906 return ret;
3909 void do_info_network(void)
3911 VLANState *vlan;
3912 VLANClientState *vc;
3914 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3915 term_printf("VLAN %d devices:\n", vlan->id);
3916 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3917 term_printf(" %s\n", vc->info_str);
3921 /***********************************************************/
3922 /* USB devices */
3924 static USBPort *used_usb_ports;
3925 static USBPort *free_usb_ports;
3927 /* ??? Maybe change this to register a hub to keep track of the topology. */
3928 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3929 usb_attachfn attach)
3931 port->opaque = opaque;
3932 port->index = index;
3933 port->attach = attach;
3934 port->next = free_usb_ports;
3935 free_usb_ports = port;
3938 static int usb_device_add(const char *devname)
3940 const char *p;
3941 USBDevice *dev;
3942 USBPort *port;
3944 if (!free_usb_ports)
3945 return -1;
3947 if (strstart(devname, "host:", &p)) {
3948 dev = usb_host_device_open(p);
3949 } else if (!strcmp(devname, "mouse")) {
3950 dev = usb_mouse_init();
3951 } else if (!strcmp(devname, "tablet")) {
3952 dev = usb_tablet_init();
3953 } else if (strstart(devname, "disk:", &p)) {
3954 dev = usb_msd_init(p);
3955 } else {
3956 return -1;
3958 if (!dev)
3959 return -1;
3961 /* Find a USB port to add the device to. */
3962 port = free_usb_ports;
3963 if (!port->next) {
3964 USBDevice *hub;
3966 /* Create a new hub and chain it on. */
3967 free_usb_ports = NULL;
3968 port->next = used_usb_ports;
3969 used_usb_ports = port;
3971 hub = usb_hub_init(VM_USB_HUB_SIZE);
3972 usb_attach(port, hub);
3973 port = free_usb_ports;
3976 free_usb_ports = port->next;
3977 port->next = used_usb_ports;
3978 used_usb_ports = port;
3979 usb_attach(port, dev);
3980 return 0;
3983 static int usb_device_del(const char *devname)
3985 USBPort *port;
3986 USBPort **lastp;
3987 USBDevice *dev;
3988 int bus_num, addr;
3989 const char *p;
3991 if (!used_usb_ports)
3992 return -1;
3994 p = strchr(devname, '.');
3995 if (!p)
3996 return -1;
3997 bus_num = strtoul(devname, NULL, 0);
3998 addr = strtoul(p + 1, NULL, 0);
3999 if (bus_num != 0)
4000 return -1;
4002 lastp = &used_usb_ports;
4003 port = used_usb_ports;
4004 while (port && port->dev->addr != addr) {
4005 lastp = &port->next;
4006 port = port->next;
4009 if (!port)
4010 return -1;
4012 dev = port->dev;
4013 *lastp = port->next;
4014 usb_attach(port, NULL);
4015 dev->handle_destroy(dev);
4016 port->next = free_usb_ports;
4017 free_usb_ports = port;
4018 return 0;
4021 void do_usb_add(const char *devname)
4023 int ret;
4024 ret = usb_device_add(devname);
4025 if (ret < 0)
4026 term_printf("Could not add USB device '%s'\n", devname);
4029 void do_usb_del(const char *devname)
4031 int ret;
4032 ret = usb_device_del(devname);
4033 if (ret < 0)
4034 term_printf("Could not remove USB device '%s'\n", devname);
4037 void usb_info(void)
4039 USBDevice *dev;
4040 USBPort *port;
4041 const char *speed_str;
4043 if (!usb_enabled) {
4044 term_printf("USB support not enabled\n");
4045 return;
4048 for (port = used_usb_ports; port; port = port->next) {
4049 dev = port->dev;
4050 if (!dev)
4051 continue;
4052 switch(dev->speed) {
4053 case USB_SPEED_LOW:
4054 speed_str = "1.5";
4055 break;
4056 case USB_SPEED_FULL:
4057 speed_str = "12";
4058 break;
4059 case USB_SPEED_HIGH:
4060 speed_str = "480";
4061 break;
4062 default:
4063 speed_str = "?";
4064 break;
4066 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4067 0, dev->addr, speed_str, dev->devname);
4071 /***********************************************************/
4072 /* pid file */
4074 static char *pid_filename;
4076 /* Remove PID file. Called on normal exit */
4078 static void remove_pidfile(void)
4080 unlink (pid_filename);
4083 static void create_pidfile(const char *filename)
4085 struct stat pidstat;
4086 FILE *f;
4088 /* Try to write our PID to the named file */
4089 if (stat(filename, &pidstat) < 0) {
4090 if (errno == ENOENT) {
4091 if ((f = fopen (filename, "w")) == NULL) {
4092 perror("Opening pidfile");
4093 exit(1);
4095 fprintf(f, "%d\n", getpid());
4096 fclose(f);
4097 pid_filename = qemu_strdup(filename);
4098 if (!pid_filename) {
4099 fprintf(stderr, "Could not save PID filename");
4100 exit(1);
4102 atexit(remove_pidfile);
4104 } else {
4105 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4106 filename);
4107 exit(1);
4111 /***********************************************************/
4112 /* dumb display */
4114 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4118 static void dumb_resize(DisplayState *ds, int w, int h)
4122 static void dumb_refresh(DisplayState *ds)
4124 vga_hw_update();
4127 void dumb_display_init(DisplayState *ds)
4129 ds->data = NULL;
4130 ds->linesize = 0;
4131 ds->depth = 0;
4132 ds->dpy_update = dumb_update;
4133 ds->dpy_resize = dumb_resize;
4134 ds->dpy_refresh = dumb_refresh;
4137 /***********************************************************/
4138 /* I/O handling */
4140 #define MAX_IO_HANDLERS 64
4142 typedef struct IOHandlerRecord {
4143 int fd;
4144 IOCanRWHandler *fd_read_poll;
4145 IOHandler *fd_read;
4146 IOHandler *fd_write;
4147 void *opaque;
4148 /* temporary data */
4149 struct pollfd *ufd;
4150 struct IOHandlerRecord *next;
4151 } IOHandlerRecord;
4153 static IOHandlerRecord *first_io_handler;
4155 /* XXX: fd_read_poll should be suppressed, but an API change is
4156 necessary in the character devices to suppress fd_can_read(). */
4157 int qemu_set_fd_handler2(int fd,
4158 IOCanRWHandler *fd_read_poll,
4159 IOHandler *fd_read,
4160 IOHandler *fd_write,
4161 void *opaque)
4163 IOHandlerRecord **pioh, *ioh;
4165 if (!fd_read && !fd_write) {
4166 pioh = &first_io_handler;
4167 for(;;) {
4168 ioh = *pioh;
4169 if (ioh == NULL)
4170 break;
4171 if (ioh->fd == fd) {
4172 *pioh = ioh->next;
4173 qemu_free(ioh);
4174 break;
4176 pioh = &ioh->next;
4178 } else {
4179 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4180 if (ioh->fd == fd)
4181 goto found;
4183 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4184 if (!ioh)
4185 return -1;
4186 ioh->next = first_io_handler;
4187 first_io_handler = ioh;
4188 found:
4189 ioh->fd = fd;
4190 ioh->fd_read_poll = fd_read_poll;
4191 ioh->fd_read = fd_read;
4192 ioh->fd_write = fd_write;
4193 ioh->opaque = opaque;
4195 return 0;
4198 int qemu_set_fd_handler(int fd,
4199 IOHandler *fd_read,
4200 IOHandler *fd_write,
4201 void *opaque)
4203 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4206 /***********************************************************/
4207 /* Polling handling */
4209 typedef struct PollingEntry {
4210 PollingFunc *func;
4211 void *opaque;
4212 struct PollingEntry *next;
4213 } PollingEntry;
4215 static PollingEntry *first_polling_entry;
4217 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4219 PollingEntry **ppe, *pe;
4220 pe = qemu_mallocz(sizeof(PollingEntry));
4221 if (!pe)
4222 return -1;
4223 pe->func = func;
4224 pe->opaque = opaque;
4225 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4226 *ppe = pe;
4227 return 0;
4230 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4232 PollingEntry **ppe, *pe;
4233 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4234 pe = *ppe;
4235 if (pe->func == func && pe->opaque == opaque) {
4236 *ppe = pe->next;
4237 qemu_free(pe);
4238 break;
4243 #ifdef _WIN32
4244 /***********************************************************/
4245 /* Wait objects support */
4246 typedef struct WaitObjects {
4247 int num;
4248 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4249 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4250 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4251 } WaitObjects;
4253 static WaitObjects wait_objects = {0};
4255 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4257 WaitObjects *w = &wait_objects;
4259 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4260 return -1;
4261 w->events[w->num] = handle;
4262 w->func[w->num] = func;
4263 w->opaque[w->num] = opaque;
4264 w->num++;
4265 return 0;
4268 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4270 int i, found;
4271 WaitObjects *w = &wait_objects;
4273 found = 0;
4274 for (i = 0; i < w->num; i++) {
4275 if (w->events[i] == handle)
4276 found = 1;
4277 if (found) {
4278 w->events[i] = w->events[i + 1];
4279 w->func[i] = w->func[i + 1];
4280 w->opaque[i] = w->opaque[i + 1];
4283 if (found)
4284 w->num--;
4286 #endif
4288 /***********************************************************/
4289 /* savevm/loadvm support */
4291 #define IO_BUF_SIZE 32768
4293 struct QEMUFile {
4294 FILE *outfile;
4295 BlockDriverState *bs;
4296 int is_file;
4297 int is_writable;
4298 int64_t base_offset;
4299 int64_t buf_offset; /* start of buffer when writing, end of buffer
4300 when reading */
4301 int buf_index;
4302 int buf_size; /* 0 when writing */
4303 uint8_t buf[IO_BUF_SIZE];
4306 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4308 QEMUFile *f;
4310 f = qemu_mallocz(sizeof(QEMUFile));
4311 if (!f)
4312 return NULL;
4313 if (!strcmp(mode, "wb")) {
4314 f->is_writable = 1;
4315 } else if (!strcmp(mode, "rb")) {
4316 f->is_writable = 0;
4317 } else {
4318 goto fail;
4320 f->outfile = fopen(filename, mode);
4321 if (!f->outfile)
4322 goto fail;
4323 f->is_file = 1;
4324 return f;
4325 fail:
4326 if (f->outfile)
4327 fclose(f->outfile);
4328 qemu_free(f);
4329 return NULL;
4332 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4334 QEMUFile *f;
4336 f = qemu_mallocz(sizeof(QEMUFile));
4337 if (!f)
4338 return NULL;
4339 f->is_file = 0;
4340 f->bs = bs;
4341 f->is_writable = is_writable;
4342 f->base_offset = offset;
4343 return f;
4346 void qemu_fflush(QEMUFile *f)
4348 if (!f->is_writable)
4349 return;
4350 if (f->buf_index > 0) {
4351 if (f->is_file) {
4352 fseek(f->outfile, f->buf_offset, SEEK_SET);
4353 fwrite(f->buf, 1, f->buf_index, f->outfile);
4354 } else {
4355 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4356 f->buf, f->buf_index);
4358 f->buf_offset += f->buf_index;
4359 f->buf_index = 0;
4363 static void qemu_fill_buffer(QEMUFile *f)
4365 int len;
4367 if (f->is_writable)
4368 return;
4369 if (f->is_file) {
4370 fseek(f->outfile, f->buf_offset, SEEK_SET);
4371 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4372 if (len < 0)
4373 len = 0;
4374 } else {
4375 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4376 f->buf, IO_BUF_SIZE);
4377 if (len < 0)
4378 len = 0;
4380 f->buf_index = 0;
4381 f->buf_size = len;
4382 f->buf_offset += len;
4385 void qemu_fclose(QEMUFile *f)
4387 if (f->is_writable)
4388 qemu_fflush(f);
4389 if (f->is_file) {
4390 fclose(f->outfile);
4392 qemu_free(f);
4395 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4397 int l;
4398 while (size > 0) {
4399 l = IO_BUF_SIZE - f->buf_index;
4400 if (l > size)
4401 l = size;
4402 memcpy(f->buf + f->buf_index, buf, l);
4403 f->buf_index += l;
4404 buf += l;
4405 size -= l;
4406 if (f->buf_index >= IO_BUF_SIZE)
4407 qemu_fflush(f);
4411 void qemu_put_byte(QEMUFile *f, int v)
4413 f->buf[f->buf_index++] = v;
4414 if (f->buf_index >= IO_BUF_SIZE)
4415 qemu_fflush(f);
4418 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4420 int size, l;
4422 size = size1;
4423 while (size > 0) {
4424 l = f->buf_size - f->buf_index;
4425 if (l == 0) {
4426 qemu_fill_buffer(f);
4427 l = f->buf_size - f->buf_index;
4428 if (l == 0)
4429 break;
4431 if (l > size)
4432 l = size;
4433 memcpy(buf, f->buf + f->buf_index, l);
4434 f->buf_index += l;
4435 buf += l;
4436 size -= l;
4438 return size1 - size;
4441 int qemu_get_byte(QEMUFile *f)
4443 if (f->buf_index >= f->buf_size) {
4444 qemu_fill_buffer(f);
4445 if (f->buf_index >= f->buf_size)
4446 return 0;
4448 return f->buf[f->buf_index++];
4451 int64_t qemu_ftell(QEMUFile *f)
4453 return f->buf_offset - f->buf_size + f->buf_index;
4456 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4458 if (whence == SEEK_SET) {
4459 /* nothing to do */
4460 } else if (whence == SEEK_CUR) {
4461 pos += qemu_ftell(f);
4462 } else {
4463 /* SEEK_END not supported */
4464 return -1;
4466 if (f->is_writable) {
4467 qemu_fflush(f);
4468 f->buf_offset = pos;
4469 } else {
4470 f->buf_offset = pos;
4471 f->buf_index = 0;
4472 f->buf_size = 0;
4474 return pos;
4477 void qemu_put_be16(QEMUFile *f, unsigned int v)
4479 qemu_put_byte(f, v >> 8);
4480 qemu_put_byte(f, v);
4483 void qemu_put_be32(QEMUFile *f, unsigned int v)
4485 qemu_put_byte(f, v >> 24);
4486 qemu_put_byte(f, v >> 16);
4487 qemu_put_byte(f, v >> 8);
4488 qemu_put_byte(f, v);
4491 void qemu_put_be64(QEMUFile *f, uint64_t v)
4493 qemu_put_be32(f, v >> 32);
4494 qemu_put_be32(f, v);
4497 unsigned int qemu_get_be16(QEMUFile *f)
4499 unsigned int v;
4500 v = qemu_get_byte(f) << 8;
4501 v |= qemu_get_byte(f);
4502 return v;
4505 unsigned int qemu_get_be32(QEMUFile *f)
4507 unsigned int v;
4508 v = qemu_get_byte(f) << 24;
4509 v |= qemu_get_byte(f) << 16;
4510 v |= qemu_get_byte(f) << 8;
4511 v |= qemu_get_byte(f);
4512 return v;
4515 uint64_t qemu_get_be64(QEMUFile *f)
4517 uint64_t v;
4518 v = (uint64_t)qemu_get_be32(f) << 32;
4519 v |= qemu_get_be32(f);
4520 return v;
4523 typedef struct SaveStateEntry {
4524 char idstr[256];
4525 int instance_id;
4526 int version_id;
4527 SaveStateHandler *save_state;
4528 LoadStateHandler *load_state;
4529 void *opaque;
4530 struct SaveStateEntry *next;
4531 } SaveStateEntry;
4533 static SaveStateEntry *first_se;
4535 int register_savevm(const char *idstr,
4536 int instance_id,
4537 int version_id,
4538 SaveStateHandler *save_state,
4539 LoadStateHandler *load_state,
4540 void *opaque)
4542 SaveStateEntry *se, **pse;
4544 se = qemu_malloc(sizeof(SaveStateEntry));
4545 if (!se)
4546 return -1;
4547 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4548 se->instance_id = instance_id;
4549 se->version_id = version_id;
4550 se->save_state = save_state;
4551 se->load_state = load_state;
4552 se->opaque = opaque;
4553 se->next = NULL;
4555 /* add at the end of list */
4556 pse = &first_se;
4557 while (*pse != NULL)
4558 pse = &(*pse)->next;
4559 *pse = se;
4560 return 0;
4563 #define QEMU_VM_FILE_MAGIC 0x5145564d
4564 #define QEMU_VM_FILE_VERSION 0x00000002
4566 int qemu_savevm_state(QEMUFile *f)
4568 SaveStateEntry *se;
4569 int len, ret;
4570 int64_t cur_pos, len_pos, total_len_pos;
4572 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4573 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4574 total_len_pos = qemu_ftell(f);
4575 qemu_put_be64(f, 0); /* total size */
4577 for(se = first_se; se != NULL; se = se->next) {
4578 /* ID string */
4579 len = strlen(se->idstr);
4580 qemu_put_byte(f, len);
4581 qemu_put_buffer(f, se->idstr, len);
4583 qemu_put_be32(f, se->instance_id);
4584 qemu_put_be32(f, se->version_id);
4586 /* record size: filled later */
4587 len_pos = qemu_ftell(f);
4588 qemu_put_be32(f, 0);
4590 se->save_state(f, se->opaque);
4592 /* fill record size */
4593 cur_pos = qemu_ftell(f);
4594 len = cur_pos - len_pos - 4;
4595 qemu_fseek(f, len_pos, SEEK_SET);
4596 qemu_put_be32(f, len);
4597 qemu_fseek(f, cur_pos, SEEK_SET);
4599 cur_pos = qemu_ftell(f);
4600 qemu_fseek(f, total_len_pos, SEEK_SET);
4601 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4602 qemu_fseek(f, cur_pos, SEEK_SET);
4604 ret = 0;
4605 return ret;
4608 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4610 SaveStateEntry *se;
4612 for(se = first_se; se != NULL; se = se->next) {
4613 if (!strcmp(se->idstr, idstr) &&
4614 instance_id == se->instance_id)
4615 return se;
4617 return NULL;
4620 int qemu_loadvm_state(QEMUFile *f)
4622 SaveStateEntry *se;
4623 int len, ret, instance_id, record_len, version_id;
4624 int64_t total_len, end_pos, cur_pos;
4625 unsigned int v;
4626 char idstr[256];
4628 v = qemu_get_be32(f);
4629 if (v != QEMU_VM_FILE_MAGIC)
4630 goto fail;
4631 v = qemu_get_be32(f);
4632 if (v != QEMU_VM_FILE_VERSION) {
4633 fail:
4634 ret = -1;
4635 goto the_end;
4637 total_len = qemu_get_be64(f);
4638 end_pos = total_len + qemu_ftell(f);
4639 for(;;) {
4640 if (qemu_ftell(f) >= end_pos)
4641 break;
4642 len = qemu_get_byte(f);
4643 qemu_get_buffer(f, idstr, len);
4644 idstr[len] = '\0';
4645 instance_id = qemu_get_be32(f);
4646 version_id = qemu_get_be32(f);
4647 record_len = qemu_get_be32(f);
4648 #if 0
4649 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4650 idstr, instance_id, version_id, record_len);
4651 #endif
4652 cur_pos = qemu_ftell(f);
4653 se = find_se(idstr, instance_id);
4654 if (!se) {
4655 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4656 instance_id, idstr);
4657 } else {
4658 ret = se->load_state(f, se->opaque, version_id);
4659 if (ret < 0) {
4660 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4661 instance_id, idstr);
4664 /* always seek to exact end of record */
4665 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4667 ret = 0;
4668 the_end:
4669 return ret;
4672 /* device can contain snapshots */
4673 static int bdrv_can_snapshot(BlockDriverState *bs)
4675 return (bs &&
4676 !bdrv_is_removable(bs) &&
4677 !bdrv_is_read_only(bs));
4680 /* device must be snapshots in order to have a reliable snapshot */
4681 static int bdrv_has_snapshot(BlockDriverState *bs)
4683 return (bs &&
4684 !bdrv_is_removable(bs) &&
4685 !bdrv_is_read_only(bs));
4688 static BlockDriverState *get_bs_snapshots(void)
4690 BlockDriverState *bs;
4691 int i;
4693 if (bs_snapshots)
4694 return bs_snapshots;
4695 for(i = 0; i <= MAX_DISKS; i++) {
4696 bs = bs_table[i];
4697 if (bdrv_can_snapshot(bs))
4698 goto ok;
4700 return NULL;
4702 bs_snapshots = bs;
4703 return bs;
4706 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4707 const char *name)
4709 QEMUSnapshotInfo *sn_tab, *sn;
4710 int nb_sns, i, ret;
4712 ret = -ENOENT;
4713 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4714 if (nb_sns < 0)
4715 return ret;
4716 for(i = 0; i < nb_sns; i++) {
4717 sn = &sn_tab[i];
4718 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4719 *sn_info = *sn;
4720 ret = 0;
4721 break;
4724 qemu_free(sn_tab);
4725 return ret;
4728 void do_savevm(const char *name)
4730 BlockDriverState *bs, *bs1;
4731 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4732 int must_delete, ret, i;
4733 BlockDriverInfo bdi1, *bdi = &bdi1;
4734 QEMUFile *f;
4735 int saved_vm_running;
4736 #ifdef _WIN32
4737 struct _timeb tb;
4738 #else
4739 struct timeval tv;
4740 #endif
4742 bs = get_bs_snapshots();
4743 if (!bs) {
4744 term_printf("No block device can accept snapshots\n");
4745 return;
4748 /* ??? Should this occur after vm_stop? */
4749 qemu_aio_flush();
4751 saved_vm_running = vm_running;
4752 vm_stop(0);
4754 must_delete = 0;
4755 if (name) {
4756 ret = bdrv_snapshot_find(bs, old_sn, name);
4757 if (ret >= 0) {
4758 must_delete = 1;
4761 memset(sn, 0, sizeof(*sn));
4762 if (must_delete) {
4763 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4764 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4765 } else {
4766 if (name)
4767 pstrcpy(sn->name, sizeof(sn->name), name);
4770 /* fill auxiliary fields */
4771 #ifdef _WIN32
4772 _ftime(&tb);
4773 sn->date_sec = tb.time;
4774 sn->date_nsec = tb.millitm * 1000000;
4775 #else
4776 gettimeofday(&tv, NULL);
4777 sn->date_sec = tv.tv_sec;
4778 sn->date_nsec = tv.tv_usec * 1000;
4779 #endif
4780 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4782 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4783 term_printf("Device %s does not support VM state snapshots\n",
4784 bdrv_get_device_name(bs));
4785 goto the_end;
4788 /* save the VM state */
4789 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4790 if (!f) {
4791 term_printf("Could not open VM state file\n");
4792 goto the_end;
4794 ret = qemu_savevm_state(f);
4795 sn->vm_state_size = qemu_ftell(f);
4796 qemu_fclose(f);
4797 if (ret < 0) {
4798 term_printf("Error %d while writing VM\n", ret);
4799 goto the_end;
4802 /* create the snapshots */
4804 for(i = 0; i < MAX_DISKS; i++) {
4805 bs1 = bs_table[i];
4806 if (bdrv_has_snapshot(bs1)) {
4807 if (must_delete) {
4808 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4809 if (ret < 0) {
4810 term_printf("Error while deleting snapshot on '%s'\n",
4811 bdrv_get_device_name(bs1));
4814 ret = bdrv_snapshot_create(bs1, sn);
4815 if (ret < 0) {
4816 term_printf("Error while creating snapshot on '%s'\n",
4817 bdrv_get_device_name(bs1));
4822 the_end:
4823 if (saved_vm_running)
4824 vm_start();
4827 void do_loadvm(const char *name)
4829 BlockDriverState *bs, *bs1;
4830 BlockDriverInfo bdi1, *bdi = &bdi1;
4831 QEMUFile *f;
4832 int i, ret;
4833 int saved_vm_running;
4835 bs = get_bs_snapshots();
4836 if (!bs) {
4837 term_printf("No block device supports snapshots\n");
4838 return;
4841 /* Flush all IO requests so they don't interfere with the new state. */
4842 qemu_aio_flush();
4844 saved_vm_running = vm_running;
4845 vm_stop(0);
4847 for(i = 0; i <= MAX_DISKS; i++) {
4848 bs1 = bs_table[i];
4849 if (bdrv_has_snapshot(bs1)) {
4850 ret = bdrv_snapshot_goto(bs1, name);
4851 if (ret < 0) {
4852 if (bs != bs1)
4853 term_printf("Warning: ");
4854 switch(ret) {
4855 case -ENOTSUP:
4856 term_printf("Snapshots not supported on device '%s'\n",
4857 bdrv_get_device_name(bs1));
4858 break;
4859 case -ENOENT:
4860 term_printf("Could not find snapshot '%s' on device '%s'\n",
4861 name, bdrv_get_device_name(bs1));
4862 break;
4863 default:
4864 term_printf("Error %d while activating snapshot on '%s'\n",
4865 ret, bdrv_get_device_name(bs1));
4866 break;
4868 /* fatal on snapshot block device */
4869 if (bs == bs1)
4870 goto the_end;
4875 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4876 term_printf("Device %s does not support VM state snapshots\n",
4877 bdrv_get_device_name(bs));
4878 return;
4881 /* restore the VM state */
4882 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4883 if (!f) {
4884 term_printf("Could not open VM state file\n");
4885 goto the_end;
4887 ret = qemu_loadvm_state(f);
4888 qemu_fclose(f);
4889 if (ret < 0) {
4890 term_printf("Error %d while loading VM state\n", ret);
4892 the_end:
4893 if (saved_vm_running)
4894 vm_start();
4897 void do_delvm(const char *name)
4899 BlockDriverState *bs, *bs1;
4900 int i, ret;
4902 bs = get_bs_snapshots();
4903 if (!bs) {
4904 term_printf("No block device supports snapshots\n");
4905 return;
4908 for(i = 0; i <= MAX_DISKS; i++) {
4909 bs1 = bs_table[i];
4910 if (bdrv_has_snapshot(bs1)) {
4911 ret = bdrv_snapshot_delete(bs1, name);
4912 if (ret < 0) {
4913 if (ret == -ENOTSUP)
4914 term_printf("Snapshots not supported on device '%s'\n",
4915 bdrv_get_device_name(bs1));
4916 else
4917 term_printf("Error %d while deleting snapshot on '%s'\n",
4918 ret, bdrv_get_device_name(bs1));
4924 void do_info_snapshots(void)
4926 BlockDriverState *bs, *bs1;
4927 QEMUSnapshotInfo *sn_tab, *sn;
4928 int nb_sns, i;
4929 char buf[256];
4931 bs = get_bs_snapshots();
4932 if (!bs) {
4933 term_printf("No available block device supports snapshots\n");
4934 return;
4936 term_printf("Snapshot devices:");
4937 for(i = 0; i <= MAX_DISKS; i++) {
4938 bs1 = bs_table[i];
4939 if (bdrv_has_snapshot(bs1)) {
4940 if (bs == bs1)
4941 term_printf(" %s", bdrv_get_device_name(bs1));
4944 term_printf("\n");
4946 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4947 if (nb_sns < 0) {
4948 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4949 return;
4951 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4952 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4953 for(i = 0; i < nb_sns; i++) {
4954 sn = &sn_tab[i];
4955 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4957 qemu_free(sn_tab);
4960 /***********************************************************/
4961 /* cpu save/restore */
4963 #if defined(TARGET_I386)
4965 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4967 qemu_put_be32(f, dt->selector);
4968 qemu_put_betl(f, dt->base);
4969 qemu_put_be32(f, dt->limit);
4970 qemu_put_be32(f, dt->flags);
4973 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4975 dt->selector = qemu_get_be32(f);
4976 dt->base = qemu_get_betl(f);
4977 dt->limit = qemu_get_be32(f);
4978 dt->flags = qemu_get_be32(f);
4981 void cpu_save(QEMUFile *f, void *opaque)
4983 CPUState *env = opaque;
4984 uint16_t fptag, fpus, fpuc, fpregs_format;
4985 uint32_t hflags;
4986 int i;
4988 #ifdef USE_KVM
4989 if (kvm_allowed)
4990 kvm_save_registers(env);
4991 #endif
4993 for(i = 0; i < CPU_NB_REGS; i++)
4994 qemu_put_betls(f, &env->regs[i]);
4995 qemu_put_betls(f, &env->eip);
4996 qemu_put_betls(f, &env->eflags);
4997 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4998 qemu_put_be32s(f, &hflags);
5000 /* FPU */
5001 fpuc = env->fpuc;
5002 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5003 fptag = 0;
5004 for(i = 0; i < 8; i++) {
5005 fptag |= ((!env->fptags[i]) << i);
5008 qemu_put_be16s(f, &fpuc);
5009 qemu_put_be16s(f, &fpus);
5010 qemu_put_be16s(f, &fptag);
5012 #ifdef USE_X86LDOUBLE
5013 fpregs_format = 0;
5014 #else
5015 fpregs_format = 1;
5016 #endif
5017 qemu_put_be16s(f, &fpregs_format);
5019 for(i = 0; i < 8; i++) {
5020 #ifdef USE_X86LDOUBLE
5022 uint64_t mant;
5023 uint16_t exp;
5024 /* we save the real CPU data (in case of MMX usage only 'mant'
5025 contains the MMX register */
5026 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5027 qemu_put_be64(f, mant);
5028 qemu_put_be16(f, exp);
5030 #else
5031 /* if we use doubles for float emulation, we save the doubles to
5032 avoid losing information in case of MMX usage. It can give
5033 problems if the image is restored on a CPU where long
5034 doubles are used instead. */
5035 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5036 #endif
5039 for(i = 0; i < 6; i++)
5040 cpu_put_seg(f, &env->segs[i]);
5041 cpu_put_seg(f, &env->ldt);
5042 cpu_put_seg(f, &env->tr);
5043 cpu_put_seg(f, &env->gdt);
5044 cpu_put_seg(f, &env->idt);
5046 qemu_put_be32s(f, &env->sysenter_cs);
5047 qemu_put_be32s(f, &env->sysenter_esp);
5048 qemu_put_be32s(f, &env->sysenter_eip);
5050 qemu_put_betls(f, &env->cr[0]);
5051 qemu_put_betls(f, &env->cr[2]);
5052 qemu_put_betls(f, &env->cr[3]);
5053 qemu_put_betls(f, &env->cr[4]);
5055 for(i = 0; i < 8; i++)
5056 qemu_put_betls(f, &env->dr[i]);
5058 /* MMU */
5059 qemu_put_be32s(f, &env->a20_mask);
5061 /* XMM */
5062 qemu_put_be32s(f, &env->mxcsr);
5063 for(i = 0; i < CPU_NB_REGS; i++) {
5064 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5065 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5068 #ifdef TARGET_X86_64
5069 qemu_put_be64s(f, &env->efer);
5070 qemu_put_be64s(f, &env->star);
5071 qemu_put_be64s(f, &env->lstar);
5072 qemu_put_be64s(f, &env->cstar);
5073 qemu_put_be64s(f, &env->fmask);
5074 qemu_put_be64s(f, &env->kernelgsbase);
5075 #endif
5076 qemu_put_be32s(f, &env->smbase);
5079 #ifdef USE_X86LDOUBLE
5080 /* XXX: add that in a FPU generic layer */
5081 union x86_longdouble {
5082 uint64_t mant;
5083 uint16_t exp;
5086 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5087 #define EXPBIAS1 1023
5088 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5089 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5091 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5093 int e;
5094 /* mantissa */
5095 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5096 /* exponent + sign */
5097 e = EXPD1(temp) - EXPBIAS1 + 16383;
5098 e |= SIGND1(temp) >> 16;
5099 p->exp = e;
5101 #endif
5103 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5105 CPUState *env = opaque;
5106 int i, guess_mmx;
5107 uint32_t hflags;
5108 uint16_t fpus, fpuc, fptag, fpregs_format;
5110 if (version_id != 3 && version_id != 4)
5111 return -EINVAL;
5112 for(i = 0; i < CPU_NB_REGS; i++)
5113 qemu_get_betls(f, &env->regs[i]);
5114 qemu_get_betls(f, &env->eip);
5115 qemu_get_betls(f, &env->eflags);
5116 qemu_get_be32s(f, &hflags);
5118 qemu_get_be16s(f, &fpuc);
5119 qemu_get_be16s(f, &fpus);
5120 qemu_get_be16s(f, &fptag);
5121 qemu_get_be16s(f, &fpregs_format);
5123 /* NOTE: we cannot always restore the FPU state if the image come
5124 from a host with a different 'USE_X86LDOUBLE' define. We guess
5125 if we are in an MMX state to restore correctly in that case. */
5126 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5127 for(i = 0; i < 8; i++) {
5128 uint64_t mant;
5129 uint16_t exp;
5131 switch(fpregs_format) {
5132 case 0:
5133 mant = qemu_get_be64(f);
5134 exp = qemu_get_be16(f);
5135 #ifdef USE_X86LDOUBLE
5136 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5137 #else
5138 /* difficult case */
5139 if (guess_mmx)
5140 env->fpregs[i].mmx.MMX_Q(0) = mant;
5141 else
5142 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5143 #endif
5144 break;
5145 case 1:
5146 mant = qemu_get_be64(f);
5147 #ifdef USE_X86LDOUBLE
5149 union x86_longdouble *p;
5150 /* difficult case */
5151 p = (void *)&env->fpregs[i];
5152 if (guess_mmx) {
5153 p->mant = mant;
5154 p->exp = 0xffff;
5155 } else {
5156 fp64_to_fp80(p, mant);
5159 #else
5160 env->fpregs[i].mmx.MMX_Q(0) = mant;
5161 #endif
5162 break;
5163 default:
5164 return -EINVAL;
5168 env->fpuc = fpuc;
5169 /* XXX: restore FPU round state */
5170 env->fpstt = (fpus >> 11) & 7;
5171 env->fpus = fpus & ~0x3800;
5172 fptag ^= 0xff;
5173 for(i = 0; i < 8; i++) {
5174 env->fptags[i] = (fptag >> i) & 1;
5177 for(i = 0; i < 6; i++)
5178 cpu_get_seg(f, &env->segs[i]);
5179 cpu_get_seg(f, &env->ldt);
5180 cpu_get_seg(f, &env->tr);
5181 cpu_get_seg(f, &env->gdt);
5182 cpu_get_seg(f, &env->idt);
5184 qemu_get_be32s(f, &env->sysenter_cs);
5185 qemu_get_be32s(f, &env->sysenter_esp);
5186 qemu_get_be32s(f, &env->sysenter_eip);
5188 qemu_get_betls(f, &env->cr[0]);
5189 qemu_get_betls(f, &env->cr[2]);
5190 qemu_get_betls(f, &env->cr[3]);
5191 qemu_get_betls(f, &env->cr[4]);
5193 for(i = 0; i < 8; i++)
5194 qemu_get_betls(f, &env->dr[i]);
5196 /* MMU */
5197 qemu_get_be32s(f, &env->a20_mask);
5199 qemu_get_be32s(f, &env->mxcsr);
5200 for(i = 0; i < CPU_NB_REGS; i++) {
5201 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5202 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5205 #ifdef TARGET_X86_64
5206 qemu_get_be64s(f, &env->efer);
5207 qemu_get_be64s(f, &env->star);
5208 qemu_get_be64s(f, &env->lstar);
5209 qemu_get_be64s(f, &env->cstar);
5210 qemu_get_be64s(f, &env->fmask);
5211 qemu_get_be64s(f, &env->kernelgsbase);
5212 #endif
5213 if (version_id >= 4)
5214 qemu_get_be32s(f, &env->smbase);
5216 /* XXX: compute hflags from scratch, except for CPL and IIF */
5217 env->hflags = hflags;
5218 tlb_flush(env, 1);
5219 #ifdef USE_KVM
5220 if (kvm_allowed) {
5221 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5222 qemu_get_betls(f, &env->kvm_interrupt_bitmap[i]);
5224 qemu_get_be64s(f, &env->tsc);
5225 kvm_load_registers(env);
5227 #endif
5228 return 0;
5231 #elif defined(TARGET_PPC)
5232 void cpu_save(QEMUFile *f, void *opaque)
5236 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5238 return 0;
5241 #elif defined(TARGET_MIPS)
5242 void cpu_save(QEMUFile *f, void *opaque)
5246 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5248 return 0;
5251 #elif defined(TARGET_SPARC)
5252 void cpu_save(QEMUFile *f, void *opaque)
5254 CPUState *env = opaque;
5255 int i;
5256 uint32_t tmp;
5258 for(i = 0; i < 8; i++)
5259 qemu_put_betls(f, &env->gregs[i]);
5260 for(i = 0; i < NWINDOWS * 16; i++)
5261 qemu_put_betls(f, &env->regbase[i]);
5263 /* FPU */
5264 for(i = 0; i < TARGET_FPREGS; i++) {
5265 union {
5266 float32 f;
5267 uint32_t i;
5268 } u;
5269 u.f = env->fpr[i];
5270 qemu_put_be32(f, u.i);
5273 qemu_put_betls(f, &env->pc);
5274 qemu_put_betls(f, &env->npc);
5275 qemu_put_betls(f, &env->y);
5276 tmp = GET_PSR(env);
5277 qemu_put_be32(f, tmp);
5278 qemu_put_betls(f, &env->fsr);
5279 qemu_put_betls(f, &env->tbr);
5280 #ifndef TARGET_SPARC64
5281 qemu_put_be32s(f, &env->wim);
5282 /* MMU */
5283 for(i = 0; i < 16; i++)
5284 qemu_put_be32s(f, &env->mmuregs[i]);
5285 #endif
5287 #ifdef USE_KVM
5288 if (kvm_allowed) {
5289 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5290 qemu_put_betls(f, &env->kvm_interrupt_bitmap[i]);
5292 qemu_put_be64s(f, &env->tsc);
5294 #endif
5297 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5299 CPUState *env = opaque;
5300 int i;
5301 uint32_t tmp;
5303 for(i = 0; i < 8; i++)
5304 qemu_get_betls(f, &env->gregs[i]);
5305 for(i = 0; i < NWINDOWS * 16; i++)
5306 qemu_get_betls(f, &env->regbase[i]);
5308 /* FPU */
5309 for(i = 0; i < TARGET_FPREGS; i++) {
5310 union {
5311 float32 f;
5312 uint32_t i;
5313 } u;
5314 u.i = qemu_get_be32(f);
5315 env->fpr[i] = u.f;
5318 qemu_get_betls(f, &env->pc);
5319 qemu_get_betls(f, &env->npc);
5320 qemu_get_betls(f, &env->y);
5321 tmp = qemu_get_be32(f);
5322 env->cwp = 0; /* needed to ensure that the wrapping registers are
5323 correctly updated */
5324 PUT_PSR(env, tmp);
5325 qemu_get_betls(f, &env->fsr);
5326 qemu_get_betls(f, &env->tbr);
5327 #ifndef TARGET_SPARC64
5328 qemu_get_be32s(f, &env->wim);
5329 /* MMU */
5330 for(i = 0; i < 16; i++)
5331 qemu_get_be32s(f, &env->mmuregs[i]);
5332 #endif
5333 tlb_flush(env, 1);
5334 return 0;
5337 #elif defined(TARGET_ARM)
5339 /* ??? Need to implement these. */
5340 void cpu_save(QEMUFile *f, void *opaque)
5344 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5346 return 0;
5349 #else
5351 #warning No CPU save/restore functions
5353 #endif
5355 /***********************************************************/
5356 /* ram save/restore */
5358 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5360 int v;
5362 v = qemu_get_byte(f);
5363 switch(v) {
5364 case 0:
5365 if (qemu_get_buffer(f, buf, len) != len)
5366 return -EIO;
5367 break;
5368 case 1:
5369 v = qemu_get_byte(f);
5370 memset(buf, v, len);
5371 break;
5372 default:
5373 return -EINVAL;
5375 return 0;
5378 static int ram_load_v1(QEMUFile *f, void *opaque)
5380 int i, ret;
5382 if (qemu_get_be32(f) != phys_ram_size)
5383 return -EINVAL;
5384 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5385 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5386 if (ret)
5387 return ret;
5389 return 0;
5392 #define BDRV_HASH_BLOCK_SIZE 1024
5393 #define IOBUF_SIZE 4096
5394 #define RAM_CBLOCK_MAGIC 0xfabe
5396 typedef struct RamCompressState {
5397 z_stream zstream;
5398 QEMUFile *f;
5399 uint8_t buf[IOBUF_SIZE];
5400 } RamCompressState;
5402 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5404 int ret;
5405 memset(s, 0, sizeof(*s));
5406 s->f = f;
5407 ret = deflateInit2(&s->zstream, 1,
5408 Z_DEFLATED, 15,
5409 9, Z_DEFAULT_STRATEGY);
5410 if (ret != Z_OK)
5411 return -1;
5412 s->zstream.avail_out = IOBUF_SIZE;
5413 s->zstream.next_out = s->buf;
5414 return 0;
5417 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5419 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5420 qemu_put_be16(s->f, len);
5421 qemu_put_buffer(s->f, buf, len);
5424 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5426 int ret;
5428 s->zstream.avail_in = len;
5429 s->zstream.next_in = (uint8_t *)buf;
5430 while (s->zstream.avail_in > 0) {
5431 ret = deflate(&s->zstream, Z_NO_FLUSH);
5432 if (ret != Z_OK)
5433 return -1;
5434 if (s->zstream.avail_out == 0) {
5435 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5436 s->zstream.avail_out = IOBUF_SIZE;
5437 s->zstream.next_out = s->buf;
5440 return 0;
5443 static void ram_compress_close(RamCompressState *s)
5445 int len, ret;
5447 /* compress last bytes */
5448 for(;;) {
5449 ret = deflate(&s->zstream, Z_FINISH);
5450 if (ret == Z_OK || ret == Z_STREAM_END) {
5451 len = IOBUF_SIZE - s->zstream.avail_out;
5452 if (len > 0) {
5453 ram_put_cblock(s, s->buf, len);
5455 s->zstream.avail_out = IOBUF_SIZE;
5456 s->zstream.next_out = s->buf;
5457 if (ret == Z_STREAM_END)
5458 break;
5459 } else {
5460 goto fail;
5463 fail:
5464 deflateEnd(&s->zstream);
5467 typedef struct RamDecompressState {
5468 z_stream zstream;
5469 QEMUFile *f;
5470 uint8_t buf[IOBUF_SIZE];
5471 } RamDecompressState;
5473 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5475 int ret;
5476 memset(s, 0, sizeof(*s));
5477 s->f = f;
5478 ret = inflateInit(&s->zstream);
5479 if (ret != Z_OK)
5480 return -1;
5481 return 0;
5484 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5486 int ret, clen;
5488 s->zstream.avail_out = len;
5489 s->zstream.next_out = buf;
5490 while (s->zstream.avail_out > 0) {
5491 if (s->zstream.avail_in == 0) {
5492 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5493 return -1;
5494 clen = qemu_get_be16(s->f);
5495 if (clen > IOBUF_SIZE)
5496 return -1;
5497 qemu_get_buffer(s->f, s->buf, clen);
5498 s->zstream.avail_in = clen;
5499 s->zstream.next_in = s->buf;
5501 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5502 if (ret != Z_OK && ret != Z_STREAM_END) {
5503 return -1;
5506 return 0;
5509 static void ram_decompress_close(RamDecompressState *s)
5511 inflateEnd(&s->zstream);
5514 static void ram_save(QEMUFile *f, void *opaque)
5516 int i;
5517 RamCompressState s1, *s = &s1;
5518 uint8_t buf[10];
5520 qemu_put_be32(f, phys_ram_size);
5521 if (ram_compress_open(s, f) < 0)
5522 return;
5523 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5524 #if 0
5525 if (tight_savevm_enabled) {
5526 int64_t sector_num;
5527 int j;
5529 /* find if the memory block is available on a virtual
5530 block device */
5531 sector_num = -1;
5532 for(j = 0; j < MAX_DISKS; j++) {
5533 if (bs_table[j]) {
5534 sector_num = bdrv_hash_find(bs_table[j],
5535 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5536 if (sector_num >= 0)
5537 break;
5540 if (j == MAX_DISKS)
5541 goto normal_compress;
5542 buf[0] = 1;
5543 buf[1] = j;
5544 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5545 ram_compress_buf(s, buf, 10);
5546 } else
5547 #endif
5549 // normal_compress:
5550 buf[0] = 0;
5551 ram_compress_buf(s, buf, 1);
5552 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5555 ram_compress_close(s);
5558 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5560 RamDecompressState s1, *s = &s1;
5561 uint8_t buf[10];
5562 int i;
5564 if (version_id == 1)
5565 return ram_load_v1(f, opaque);
5566 if (version_id != 2)
5567 return -EINVAL;
5568 if (qemu_get_be32(f) != phys_ram_size)
5569 return -EINVAL;
5570 if (ram_decompress_open(s, f) < 0)
5571 return -EINVAL;
5572 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5573 if (ram_decompress_buf(s, buf, 1) < 0) {
5574 fprintf(stderr, "Error while reading ram block header\n");
5575 goto error;
5577 if (buf[0] == 0) {
5578 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5579 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5580 goto error;
5582 } else
5583 #if 0
5584 if (buf[0] == 1) {
5585 int bs_index;
5586 int64_t sector_num;
5588 ram_decompress_buf(s, buf + 1, 9);
5589 bs_index = buf[1];
5590 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5591 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5592 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5593 goto error;
5595 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5596 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5597 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5598 bs_index, sector_num);
5599 goto error;
5601 } else
5602 #endif
5604 error:
5605 printf("Error block header\n");
5606 return -EINVAL;
5609 ram_decompress_close(s);
5610 return 0;
5613 /***********************************************************/
5614 /* bottom halves (can be seen as timers which expire ASAP) */
5616 struct QEMUBH {
5617 QEMUBHFunc *cb;
5618 void *opaque;
5619 int scheduled;
5620 QEMUBH *next;
5623 static QEMUBH *first_bh = NULL;
5625 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5627 QEMUBH *bh;
5628 bh = qemu_mallocz(sizeof(QEMUBH));
5629 if (!bh)
5630 return NULL;
5631 bh->cb = cb;
5632 bh->opaque = opaque;
5633 return bh;
5636 int qemu_bh_poll(void)
5638 QEMUBH *bh, **pbh;
5639 int ret;
5641 ret = 0;
5642 for(;;) {
5643 pbh = &first_bh;
5644 bh = *pbh;
5645 if (!bh)
5646 break;
5647 ret = 1;
5648 *pbh = bh->next;
5649 bh->scheduled = 0;
5650 bh->cb(bh->opaque);
5652 return ret;
5655 void qemu_bh_schedule(QEMUBH *bh)
5657 CPUState *env = cpu_single_env;
5658 if (bh->scheduled)
5659 return;
5660 bh->scheduled = 1;
5661 bh->next = first_bh;
5662 first_bh = bh;
5664 /* stop the currently executing CPU to execute the BH ASAP */
5665 if (env) {
5666 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5670 void qemu_bh_cancel(QEMUBH *bh)
5672 QEMUBH **pbh;
5673 if (bh->scheduled) {
5674 pbh = &first_bh;
5675 while (*pbh != bh)
5676 pbh = &(*pbh)->next;
5677 *pbh = bh->next;
5678 bh->scheduled = 0;
5682 void qemu_bh_delete(QEMUBH *bh)
5684 qemu_bh_cancel(bh);
5685 qemu_free(bh);
5688 /***********************************************************/
5689 /* machine registration */
5691 QEMUMachine *first_machine = NULL;
5693 int qemu_register_machine(QEMUMachine *m)
5695 QEMUMachine **pm;
5696 pm = &first_machine;
5697 while (*pm != NULL)
5698 pm = &(*pm)->next;
5699 m->next = NULL;
5700 *pm = m;
5701 return 0;
5704 QEMUMachine *find_machine(const char *name)
5706 QEMUMachine *m;
5708 for(m = first_machine; m != NULL; m = m->next) {
5709 if (!strcmp(m->name, name))
5710 return m;
5712 return NULL;
5715 /***********************************************************/
5716 /* main execution loop */
5718 void gui_update(void *opaque)
5720 display_state.dpy_refresh(&display_state);
5721 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5724 struct vm_change_state_entry {
5725 VMChangeStateHandler *cb;
5726 void *opaque;
5727 LIST_ENTRY (vm_change_state_entry) entries;
5730 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5732 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5733 void *opaque)
5735 VMChangeStateEntry *e;
5737 e = qemu_mallocz(sizeof (*e));
5738 if (!e)
5739 return NULL;
5741 e->cb = cb;
5742 e->opaque = opaque;
5743 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5744 return e;
5747 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5749 LIST_REMOVE (e, entries);
5750 qemu_free (e);
5753 static void vm_state_notify(int running)
5755 VMChangeStateEntry *e;
5757 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5758 e->cb(e->opaque, running);
5762 /* XXX: support several handlers */
5763 static VMStopHandler *vm_stop_cb;
5764 static void *vm_stop_opaque;
5766 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5768 vm_stop_cb = cb;
5769 vm_stop_opaque = opaque;
5770 return 0;
5773 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5775 vm_stop_cb = NULL;
5778 void vm_start(void)
5780 if (!vm_running) {
5781 cpu_enable_ticks();
5782 vm_running = 1;
5783 vm_state_notify(1);
5787 void vm_stop(int reason)
5789 if (vm_running) {
5790 cpu_disable_ticks();
5791 vm_running = 0;
5792 if (reason != 0) {
5793 if (vm_stop_cb) {
5794 vm_stop_cb(vm_stop_opaque, reason);
5797 vm_state_notify(0);
5801 /* reset/shutdown handler */
5803 typedef struct QEMUResetEntry {
5804 QEMUResetHandler *func;
5805 void *opaque;
5806 struct QEMUResetEntry *next;
5807 } QEMUResetEntry;
5809 static QEMUResetEntry *first_reset_entry;
5810 static int reset_requested;
5811 static int shutdown_requested;
5812 static int powerdown_requested;
5814 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5816 QEMUResetEntry **pre, *re;
5818 pre = &first_reset_entry;
5819 while (*pre != NULL)
5820 pre = &(*pre)->next;
5821 re = qemu_mallocz(sizeof(QEMUResetEntry));
5822 re->func = func;
5823 re->opaque = opaque;
5824 re->next = NULL;
5825 *pre = re;
5828 static void qemu_system_reset(void)
5830 QEMUResetEntry *re;
5832 /* reset all devices */
5833 for(re = first_reset_entry; re != NULL; re = re->next) {
5834 re->func(re->opaque);
5838 void qemu_system_reset_request(void)
5840 if (no_reboot) {
5841 shutdown_requested = 1;
5842 } else {
5843 reset_requested = 1;
5845 if (cpu_single_env)
5846 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5849 void qemu_system_shutdown_request(void)
5851 shutdown_requested = 1;
5852 if (cpu_single_env)
5853 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5856 void qemu_system_powerdown_request(void)
5858 powerdown_requested = 1;
5859 if (cpu_single_env)
5860 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5863 void main_loop_wait(int timeout)
5865 IOHandlerRecord *ioh, *ioh_next;
5866 fd_set rfds, wfds, xfds;
5867 int ret, nfds;
5868 struct timeval tv;
5869 PollingEntry *pe;
5872 /* XXX: need to suppress polling by better using win32 events */
5873 ret = 0;
5874 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5875 ret |= pe->func(pe->opaque);
5877 #ifdef _WIN32
5878 if (ret == 0 && timeout > 0) {
5879 int err;
5880 WaitObjects *w = &wait_objects;
5882 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5883 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5884 if (w->func[ret - WAIT_OBJECT_0])
5885 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5886 } else if (ret == WAIT_TIMEOUT) {
5887 } else {
5888 err = GetLastError();
5889 fprintf(stderr, "Wait error %d %d\n", ret, err);
5892 #endif
5893 /* poll any events */
5894 /* XXX: separate device handlers from system ones */
5895 nfds = -1;
5896 FD_ZERO(&rfds);
5897 FD_ZERO(&wfds);
5898 FD_ZERO(&xfds);
5899 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5900 if (ioh->fd_read &&
5901 (!ioh->fd_read_poll ||
5902 ioh->fd_read_poll(ioh->opaque) != 0)) {
5903 FD_SET(ioh->fd, &rfds);
5904 if (ioh->fd > nfds)
5905 nfds = ioh->fd;
5907 if (ioh->fd_write) {
5908 FD_SET(ioh->fd, &wfds);
5909 if (ioh->fd > nfds)
5910 nfds = ioh->fd;
5914 tv.tv_sec = 0;
5915 #ifdef _WIN32
5916 tv.tv_usec = 0;
5917 #else
5918 tv.tv_usec = timeout * 1000;
5919 #endif
5920 #if defined(CONFIG_SLIRP)
5921 if (slirp_inited) {
5922 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5924 #endif
5925 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5926 if (ret > 0) {
5927 /* XXX: better handling of removal */
5928 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5929 ioh_next = ioh->next;
5930 if (FD_ISSET(ioh->fd, &rfds)) {
5931 ioh->fd_read(ioh->opaque);
5933 if (FD_ISSET(ioh->fd, &wfds)) {
5934 ioh->fd_write(ioh->opaque);
5938 #if defined(CONFIG_SLIRP)
5939 if (slirp_inited) {
5940 if (ret < 0) {
5941 FD_ZERO(&rfds);
5942 FD_ZERO(&wfds);
5943 FD_ZERO(&xfds);
5945 slirp_select_poll(&rfds, &wfds, &xfds);
5947 #endif
5948 qemu_aio_poll();
5949 qemu_bh_poll();
5951 if (vm_running) {
5952 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5953 qemu_get_clock(vm_clock));
5954 /* run dma transfers, if any */
5955 DMA_run();
5958 /* real time timers */
5959 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5960 qemu_get_clock(rt_clock));
5963 static CPUState *cur_cpu;
5965 int main_loop(void)
5967 int ret, timeout;
5968 #ifdef CONFIG_PROFILER
5969 int64_t ti;
5970 #endif
5971 CPUState *env;
5973 cur_cpu = first_cpu;
5974 for(;;) {
5975 if (vm_running) {
5977 env = cur_cpu;
5978 for(;;) {
5979 /* get next cpu */
5980 env = env->next_cpu;
5981 if (!env)
5982 env = first_cpu;
5983 #ifdef CONFIG_PROFILER
5984 ti = profile_getclock();
5985 #endif
5986 ret = cpu_exec(env);
5987 #ifdef CONFIG_PROFILER
5988 qemu_time += profile_getclock() - ti;
5989 #endif
5990 if (ret != EXCP_HALTED)
5991 break;
5992 /* all CPUs are halted ? */
5993 if (env == cur_cpu) {
5994 ret = EXCP_HLT;
5995 break;
5998 cur_cpu = env;
6000 if (shutdown_requested) {
6001 ret = EXCP_INTERRUPT;
6002 break;
6004 if (reset_requested) {
6005 reset_requested = 0;
6006 qemu_system_reset();
6007 #ifdef USE_KVM
6008 if (kvm_allowed)
6009 kvm_load_registers(env);
6010 #endif
6011 ret = EXCP_INTERRUPT;
6013 if (powerdown_requested) {
6014 powerdown_requested = 0;
6015 qemu_system_powerdown();
6016 ret = EXCP_INTERRUPT;
6018 if (ret == EXCP_DEBUG) {
6019 vm_stop(EXCP_DEBUG);
6021 /* if hlt instruction, we wait until the next IRQ */
6022 /* XXX: use timeout computed from timers */
6023 if (ret == EXCP_HLT)
6024 timeout = 10;
6025 else
6026 timeout = 0;
6027 } else {
6028 timeout = 10;
6030 #ifdef CONFIG_PROFILER
6031 ti = profile_getclock();
6032 #endif
6033 main_loop_wait(timeout);
6034 #ifdef CONFIG_PROFILER
6035 dev_time += profile_getclock() - ti;
6036 #endif
6038 cpu_disable_ticks();
6039 return ret;
6042 void help(void)
6044 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6045 "usage: %s [options] [disk_image]\n"
6046 "\n"
6047 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6048 "\n"
6049 "Standard options:\n"
6050 "-M machine select emulated machine (-M ? for list)\n"
6051 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6052 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6053 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6054 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6055 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6056 "-snapshot write to temporary files instead of disk image files\n"
6057 #ifdef CONFIG_SDL
6058 "-no-quit disable SDL window close capability\n"
6059 #endif
6060 #ifdef TARGET_I386
6061 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6062 #endif
6063 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6064 "-smp n set the number of CPUs to 'n' [default=1]\n"
6065 "-nographic disable graphical output and redirect serial I/Os to console\n"
6066 #ifndef _WIN32
6067 "-k language use keyboard layout (for example \"fr\" for French)\n"
6068 #endif
6069 #ifdef HAS_AUDIO
6070 "-audio-help print list of audio drivers and their options\n"
6071 "-soundhw c1,... enable audio support\n"
6072 " and only specified sound cards (comma separated list)\n"
6073 " use -soundhw ? to get the list of supported cards\n"
6074 " use -soundhw all to enable all of them\n"
6075 #endif
6076 "-localtime set the real time clock to local time [default=utc]\n"
6077 "-full-screen start in full screen\n"
6078 #ifdef TARGET_I386
6079 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6080 #endif
6081 "-usb enable the USB driver (will be the default soon)\n"
6082 "-usbdevice name add the host or guest USB device 'name'\n"
6083 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6084 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6085 #endif
6086 "\n"
6087 "Network options:\n"
6088 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6089 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6090 #ifdef CONFIG_SLIRP
6091 "-net user[,vlan=n][,hostname=host]\n"
6092 " connect the user mode network stack to VLAN 'n' and send\n"
6093 " hostname 'host' to DHCP clients\n"
6094 #endif
6095 #ifdef _WIN32
6096 "-net tap[,vlan=n],ifname=name\n"
6097 " connect the host TAP network interface to VLAN 'n'\n"
6098 #else
6099 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6100 " connect the host TAP network interface to VLAN 'n' and use\n"
6101 " the network script 'file' (default=%s);\n"
6102 " use 'script=no' to disable script execution;\n"
6103 " use 'fd=h' to connect to an already opened TAP interface\n"
6104 #endif
6105 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6106 " connect the vlan 'n' to another VLAN using a socket connection\n"
6107 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6108 " connect the vlan 'n' to multicast maddr and port\n"
6109 "-net none use it alone to have zero network devices; if no -net option\n"
6110 " is provided, the default is '-net nic -net user'\n"
6111 "\n"
6112 #ifdef CONFIG_SLIRP
6113 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6114 #ifndef _WIN32
6115 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6116 #endif
6117 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6118 " redirect TCP or UDP connections from host to guest [-net user]\n"
6119 #endif
6120 "\n"
6121 "Linux boot specific:\n"
6122 "-kernel bzImage use 'bzImage' as kernel image\n"
6123 "-append cmdline use 'cmdline' as kernel command line\n"
6124 "-initrd file use 'file' as initial ram disk\n"
6125 "\n"
6126 "Debug/Expert options:\n"
6127 "-monitor dev redirect the monitor to char device 'dev'\n"
6128 "-serial dev redirect the serial port to char device 'dev'\n"
6129 "-parallel dev redirect the parallel port to char device 'dev'\n"
6130 "-pidfile file Write PID to 'file'\n"
6131 "-S freeze CPU at startup (use 'c' to start execution)\n"
6132 "-s wait gdb connection to port %d\n"
6133 "-p port change gdb connection port\n"
6134 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6135 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6136 " translation (t=none or lba) (usually qemu can guess them)\n"
6137 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6138 #ifdef USE_KQEMU
6139 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6140 "-no-kqemu disable KQEMU kernel module usage\n"
6141 #endif
6142 #ifdef USE_KVM
6143 "-no-kvm disable KVM hardware virtualization\n"
6144 #endif
6145 #ifdef USE_CODE_COPY
6146 "-no-code-copy disable code copy acceleration\n"
6147 #endif
6148 #ifdef TARGET_I386
6149 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6150 " (default is CL-GD5446 PCI VGA)\n"
6151 "-no-acpi disable ACPI\n"
6152 #endif
6153 "-no-reboot exit instead of rebooting\n"
6154 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6155 "-vnc display start a VNC server on display\n"
6156 #ifndef _WIN32
6157 "-daemonize daemonize QEMU after initializing\n"
6158 #endif
6159 "-option-rom rom load a file, rom, into the option ROM space\n"
6160 "\n"
6161 "During emulation, the following keys are useful:\n"
6162 "ctrl-alt-f toggle full screen\n"
6163 "ctrl-alt-n switch to virtual console 'n'\n"
6164 "ctrl-alt toggle mouse and keyboard grab\n"
6165 "\n"
6166 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6168 "qemu",
6169 DEFAULT_RAM_SIZE,
6170 #ifndef _WIN32
6171 DEFAULT_NETWORK_SCRIPT,
6172 #endif
6173 DEFAULT_GDBSTUB_PORT,
6174 "/tmp/qemu.log");
6175 exit(1);
6178 #define HAS_ARG 0x0001
6180 enum {
6181 QEMU_OPTION_h,
6183 QEMU_OPTION_M,
6184 QEMU_OPTION_fda,
6185 QEMU_OPTION_fdb,
6186 QEMU_OPTION_hda,
6187 QEMU_OPTION_hdb,
6188 QEMU_OPTION_hdc,
6189 QEMU_OPTION_hdd,
6190 QEMU_OPTION_cdrom,
6191 QEMU_OPTION_boot,
6192 QEMU_OPTION_snapshot,
6193 #ifdef TARGET_I386
6194 QEMU_OPTION_no_fd_bootchk,
6195 #endif
6196 QEMU_OPTION_m,
6197 QEMU_OPTION_nographic,
6198 #ifdef HAS_AUDIO
6199 QEMU_OPTION_audio_help,
6200 QEMU_OPTION_soundhw,
6201 #endif
6203 QEMU_OPTION_net,
6204 QEMU_OPTION_tftp,
6205 QEMU_OPTION_smb,
6206 QEMU_OPTION_redir,
6208 QEMU_OPTION_kernel,
6209 QEMU_OPTION_append,
6210 QEMU_OPTION_initrd,
6212 QEMU_OPTION_S,
6213 QEMU_OPTION_s,
6214 QEMU_OPTION_p,
6215 QEMU_OPTION_d,
6216 QEMU_OPTION_hdachs,
6217 QEMU_OPTION_L,
6218 QEMU_OPTION_no_code_copy,
6219 QEMU_OPTION_k,
6220 QEMU_OPTION_localtime,
6221 QEMU_OPTION_cirrusvga,
6222 QEMU_OPTION_g,
6223 QEMU_OPTION_std_vga,
6224 QEMU_OPTION_monitor,
6225 QEMU_OPTION_vmchannel,
6226 QEMU_OPTION_serial,
6227 QEMU_OPTION_parallel,
6228 QEMU_OPTION_loadvm,
6229 QEMU_OPTION_full_screen,
6230 QEMU_OPTION_no_quit,
6231 QEMU_OPTION_pidfile,
6232 QEMU_OPTION_no_kqemu,
6233 QEMU_OPTION_kernel_kqemu,
6234 QEMU_OPTION_win2k_hack,
6235 QEMU_OPTION_usb,
6236 QEMU_OPTION_usbdevice,
6237 QEMU_OPTION_smp,
6238 QEMU_OPTION_vnc,
6239 QEMU_OPTION_no_acpi,
6240 QEMU_OPTION_no_kvm,
6241 QEMU_OPTION_no_reboot,
6242 QEMU_OPTION_daemonize,
6243 QEMU_OPTION_option_rom,
6244 QEMU_OPTION_semihosting
6247 typedef struct QEMUOption {
6248 const char *name;
6249 int flags;
6250 int index;
6251 } QEMUOption;
6253 const QEMUOption qemu_options[] = {
6254 { "h", 0, QEMU_OPTION_h },
6255 { "help", 0, QEMU_OPTION_h },
6257 { "M", HAS_ARG, QEMU_OPTION_M },
6258 { "fda", HAS_ARG, QEMU_OPTION_fda },
6259 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6260 { "hda", HAS_ARG, QEMU_OPTION_hda },
6261 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6262 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6263 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6264 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6265 { "boot", HAS_ARG, QEMU_OPTION_boot },
6266 { "snapshot", 0, QEMU_OPTION_snapshot },
6267 #ifdef TARGET_I386
6268 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6269 #endif
6270 { "m", HAS_ARG, QEMU_OPTION_m },
6271 { "nographic", 0, QEMU_OPTION_nographic },
6272 { "k", HAS_ARG, QEMU_OPTION_k },
6273 #ifdef HAS_AUDIO
6274 { "audio-help", 0, QEMU_OPTION_audio_help },
6275 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6276 #endif
6278 { "net", HAS_ARG, QEMU_OPTION_net},
6279 #ifdef CONFIG_SLIRP
6280 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6281 #ifndef _WIN32
6282 { "smb", HAS_ARG, QEMU_OPTION_smb },
6283 #endif
6284 { "redir", HAS_ARG, QEMU_OPTION_redir },
6285 #endif
6287 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6288 { "append", HAS_ARG, QEMU_OPTION_append },
6289 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6291 { "S", 0, QEMU_OPTION_S },
6292 { "s", 0, QEMU_OPTION_s },
6293 { "p", HAS_ARG, QEMU_OPTION_p },
6294 { "d", HAS_ARG, QEMU_OPTION_d },
6295 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6296 { "L", HAS_ARG, QEMU_OPTION_L },
6297 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6298 #ifdef USE_KQEMU
6299 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6300 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6301 #endif
6302 #ifdef USE_KVM
6303 { "no-kvm", 0, QEMU_OPTION_no_kvm },
6304 #endif
6305 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6306 { "g", 1, QEMU_OPTION_g },
6307 #endif
6308 { "localtime", 0, QEMU_OPTION_localtime },
6309 { "std-vga", 0, QEMU_OPTION_std_vga },
6310 { "monitor", 1, QEMU_OPTION_monitor },
6311 { "vmchannel", 1, QEMU_OPTION_vmchannel },
6312 { "serial", 1, QEMU_OPTION_serial },
6313 { "parallel", 1, QEMU_OPTION_parallel },
6314 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6315 { "full-screen", 0, QEMU_OPTION_full_screen },
6316 #ifdef CONFIG_SDL
6317 { "no-quit", 0, QEMU_OPTION_no_quit },
6318 #endif
6319 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6320 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6321 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6322 { "smp", HAS_ARG, QEMU_OPTION_smp },
6323 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6325 /* temporary options */
6326 { "usb", 0, QEMU_OPTION_usb },
6327 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6328 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6329 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6330 { "daemonize", 0, QEMU_OPTION_daemonize },
6331 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6332 #if defined(TARGET_ARM)
6333 { "semihosting", 0, QEMU_OPTION_semihosting },
6334 #endif
6335 { NULL },
6338 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6340 /* this stack is only used during signal handling */
6341 #define SIGNAL_STACK_SIZE 32768
6343 static uint8_t *signal_stack;
6345 #endif
6347 /* password input */
6349 static BlockDriverState *get_bdrv(int index)
6351 BlockDriverState *bs;
6353 if (index < 4) {
6354 bs = bs_table[index];
6355 } else if (index < 6) {
6356 bs = fd_table[index - 4];
6357 } else {
6358 bs = NULL;
6360 return bs;
6363 static void read_passwords(void)
6365 BlockDriverState *bs;
6366 int i, j;
6367 char password[256];
6369 for(i = 0; i < 6; i++) {
6370 bs = get_bdrv(i);
6371 if (bs && bdrv_is_encrypted(bs)) {
6372 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6373 for(j = 0; j < 3; j++) {
6374 monitor_readline("Password: ",
6375 1, password, sizeof(password));
6376 if (bdrv_set_key(bs, password) == 0)
6377 break;
6378 term_printf("invalid password\n");
6384 /* XXX: currently we cannot use simultaneously different CPUs */
6385 void register_machines(void)
6387 #if defined(TARGET_I386)
6388 qemu_register_machine(&pc_machine);
6389 qemu_register_machine(&isapc_machine);
6390 #elif defined(TARGET_PPC)
6391 qemu_register_machine(&heathrow_machine);
6392 qemu_register_machine(&core99_machine);
6393 qemu_register_machine(&prep_machine);
6394 #elif defined(TARGET_MIPS)
6395 qemu_register_machine(&mips_machine);
6396 qemu_register_machine(&mips_malta_machine);
6397 #elif defined(TARGET_SPARC)
6398 #ifdef TARGET_SPARC64
6399 qemu_register_machine(&sun4u_machine);
6400 #else
6401 qemu_register_machine(&sun4m_machine);
6402 #endif
6403 #elif defined(TARGET_ARM)
6404 qemu_register_machine(&integratorcp926_machine);
6405 qemu_register_machine(&integratorcp1026_machine);
6406 qemu_register_machine(&versatilepb_machine);
6407 qemu_register_machine(&versatileab_machine);
6408 qemu_register_machine(&realview_machine);
6409 #elif defined(TARGET_SH4)
6410 qemu_register_machine(&shix_machine);
6411 #else
6412 #error unsupported CPU
6413 #endif
6416 #ifdef HAS_AUDIO
6417 struct soundhw soundhw[] = {
6418 #ifdef TARGET_I386
6420 "pcspk",
6421 "PC speaker",
6424 { .init_isa = pcspk_audio_init }
6426 #endif
6428 "sb16",
6429 "Creative Sound Blaster 16",
6432 { .init_isa = SB16_init }
6435 #ifdef CONFIG_ADLIB
6437 "adlib",
6438 #ifdef HAS_YMF262
6439 "Yamaha YMF262 (OPL3)",
6440 #else
6441 "Yamaha YM3812 (OPL2)",
6442 #endif
6445 { .init_isa = Adlib_init }
6447 #endif
6449 #ifdef CONFIG_GUS
6451 "gus",
6452 "Gravis Ultrasound GF1",
6455 { .init_isa = GUS_init }
6457 #endif
6460 "es1370",
6461 "ENSONIQ AudioPCI ES1370",
6464 { .init_pci = es1370_init }
6467 { NULL, NULL, 0, 0, { NULL } }
6470 static void select_soundhw (const char *optarg)
6472 struct soundhw *c;
6474 if (*optarg == '?') {
6475 show_valid_cards:
6477 printf ("Valid sound card names (comma separated):\n");
6478 for (c = soundhw; c->name; ++c) {
6479 printf ("%-11s %s\n", c->name, c->descr);
6481 printf ("\n-soundhw all will enable all of the above\n");
6482 exit (*optarg != '?');
6484 else {
6485 size_t l;
6486 const char *p;
6487 char *e;
6488 int bad_card = 0;
6490 if (!strcmp (optarg, "all")) {
6491 for (c = soundhw; c->name; ++c) {
6492 c->enabled = 1;
6494 return;
6497 p = optarg;
6498 while (*p) {
6499 e = strchr (p, ',');
6500 l = !e ? strlen (p) : (size_t) (e - p);
6502 for (c = soundhw; c->name; ++c) {
6503 if (!strncmp (c->name, p, l)) {
6504 c->enabled = 1;
6505 break;
6509 if (!c->name) {
6510 if (l > 80) {
6511 fprintf (stderr,
6512 "Unknown sound card name (too big to show)\n");
6514 else {
6515 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6516 (int) l, p);
6518 bad_card = 1;
6520 p += l + (e != NULL);
6523 if (bad_card)
6524 goto show_valid_cards;
6527 #endif
6529 #ifdef _WIN32
6530 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6532 exit(STATUS_CONTROL_C_EXIT);
6533 return TRUE;
6535 #endif
6537 #define MAX_NET_CLIENTS 32
6539 int main(int argc, char **argv)
6541 #ifdef CONFIG_GDBSTUB
6542 int use_gdbstub, gdbstub_port;
6543 #endif
6544 int i, cdrom_index;
6545 int snapshot, linux_boot;
6546 const char *initrd_filename;
6547 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6548 const char *kernel_filename, *kernel_cmdline;
6549 DisplayState *ds = &display_state;
6550 int cyls, heads, secs, translation;
6551 char net_clients[MAX_NET_CLIENTS][256];
6552 int nb_net_clients;
6553 int optind;
6554 const char *r, *optarg;
6555 CharDriverState *monitor_hd;
6556 char monitor_device[128];
6557 CharDriverState *vmchannel_hd;
6558 char vmchannel_device[128];
6559 char serial_devices[MAX_SERIAL_PORTS][128];
6560 int serial_device_index;
6561 char parallel_devices[MAX_PARALLEL_PORTS][128];
6562 int parallel_device_index;
6563 const char *loadvm = NULL;
6564 QEMUMachine *machine;
6565 char usb_devices[MAX_USB_CMDLINE][128];
6566 int usb_devices_index;
6567 int fds[2];
6569 LIST_INIT (&vm_change_state_head);
6570 #ifndef _WIN32
6572 struct sigaction act;
6573 sigfillset(&act.sa_mask);
6574 act.sa_flags = 0;
6575 act.sa_handler = SIG_IGN;
6576 sigaction(SIGPIPE, &act, NULL);
6578 #else
6579 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6580 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6581 QEMU to run on a single CPU */
6583 HANDLE h;
6584 DWORD mask, smask;
6585 int i;
6586 h = GetCurrentProcess();
6587 if (GetProcessAffinityMask(h, &mask, &smask)) {
6588 for(i = 0; i < 32; i++) {
6589 if (mask & (1 << i))
6590 break;
6592 if (i != 32) {
6593 mask = 1 << i;
6594 SetProcessAffinityMask(h, mask);
6598 #endif
6600 register_machines();
6601 machine = first_machine;
6602 initrd_filename = NULL;
6603 for(i = 0; i < MAX_FD; i++)
6604 fd_filename[i] = NULL;
6605 for(i = 0; i < MAX_DISKS; i++)
6606 hd_filename[i] = NULL;
6607 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6608 vga_ram_size = VGA_RAM_SIZE;
6609 bios_size = BIOS_SIZE;
6610 #ifdef CONFIG_GDBSTUB
6611 use_gdbstub = 0;
6612 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6613 #endif
6614 snapshot = 0;
6615 nographic = 0;
6616 kernel_filename = NULL;
6617 kernel_cmdline = "";
6618 #ifdef TARGET_PPC
6619 cdrom_index = 1;
6620 #else
6621 cdrom_index = 2;
6622 #endif
6623 cyls = heads = secs = 0;
6624 translation = BIOS_ATA_TRANSLATION_AUTO;
6625 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6627 vmchannel_device[0] = '\0';
6629 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6630 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6631 serial_devices[i][0] = '\0';
6632 serial_device_index = 0;
6634 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6635 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6636 parallel_devices[i][0] = '\0';
6637 parallel_device_index = 0;
6639 usb_devices_index = 0;
6641 nb_net_clients = 0;
6643 nb_nics = 0;
6644 /* default mac address of the first network interface */
6646 optind = 1;
6647 for(;;) {
6648 if (optind >= argc)
6649 break;
6650 r = argv[optind];
6651 if (r[0] != '-') {
6652 hd_filename[0] = argv[optind++];
6653 } else {
6654 const QEMUOption *popt;
6656 optind++;
6657 /* Treat --foo the same as -foo. */
6658 if (r[1] == '-')
6659 r++;
6660 popt = qemu_options;
6661 for(;;) {
6662 if (!popt->name) {
6663 fprintf(stderr, "%s: invalid option -- '%s'\n",
6664 argv[0], r);
6665 exit(1);
6667 if (!strcmp(popt->name, r + 1))
6668 break;
6669 popt++;
6671 if (popt->flags & HAS_ARG) {
6672 if (optind >= argc) {
6673 fprintf(stderr, "%s: option '%s' requires an argument\n",
6674 argv[0], r);
6675 exit(1);
6677 optarg = argv[optind++];
6678 } else {
6679 optarg = NULL;
6682 switch(popt->index) {
6683 case QEMU_OPTION_M:
6684 machine = find_machine(optarg);
6685 if (!machine) {
6686 QEMUMachine *m;
6687 printf("Supported machines are:\n");
6688 for(m = first_machine; m != NULL; m = m->next) {
6689 printf("%-10s %s%s\n",
6690 m->name, m->desc,
6691 m == first_machine ? " (default)" : "");
6693 exit(1);
6695 break;
6696 case QEMU_OPTION_initrd:
6697 initrd_filename = optarg;
6698 break;
6699 case QEMU_OPTION_hda:
6700 case QEMU_OPTION_hdb:
6701 case QEMU_OPTION_hdc:
6702 case QEMU_OPTION_hdd:
6704 int hd_index;
6705 hd_index = popt->index - QEMU_OPTION_hda;
6706 hd_filename[hd_index] = optarg;
6707 if (hd_index == cdrom_index)
6708 cdrom_index = -1;
6710 break;
6711 case QEMU_OPTION_snapshot:
6712 snapshot = 1;
6713 break;
6714 case QEMU_OPTION_hdachs:
6716 const char *p;
6717 p = optarg;
6718 cyls = strtol(p, (char **)&p, 0);
6719 if (cyls < 1 || cyls > 16383)
6720 goto chs_fail;
6721 if (*p != ',')
6722 goto chs_fail;
6723 p++;
6724 heads = strtol(p, (char **)&p, 0);
6725 if (heads < 1 || heads > 16)
6726 goto chs_fail;
6727 if (*p != ',')
6728 goto chs_fail;
6729 p++;
6730 secs = strtol(p, (char **)&p, 0);
6731 if (secs < 1 || secs > 63)
6732 goto chs_fail;
6733 if (*p == ',') {
6734 p++;
6735 if (!strcmp(p, "none"))
6736 translation = BIOS_ATA_TRANSLATION_NONE;
6737 else if (!strcmp(p, "lba"))
6738 translation = BIOS_ATA_TRANSLATION_LBA;
6739 else if (!strcmp(p, "auto"))
6740 translation = BIOS_ATA_TRANSLATION_AUTO;
6741 else
6742 goto chs_fail;
6743 } else if (*p != '\0') {
6744 chs_fail:
6745 fprintf(stderr, "qemu: invalid physical CHS format\n");
6746 exit(1);
6749 break;
6750 case QEMU_OPTION_nographic:
6751 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6752 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6753 nographic = 1;
6754 break;
6755 case QEMU_OPTION_kernel:
6756 kernel_filename = optarg;
6757 break;
6758 case QEMU_OPTION_append:
6759 kernel_cmdline = optarg;
6760 break;
6761 case QEMU_OPTION_cdrom:
6762 if (cdrom_index >= 0) {
6763 hd_filename[cdrom_index] = optarg;
6765 break;
6766 case QEMU_OPTION_boot:
6767 boot_device = optarg[0];
6768 if (boot_device != 'a' &&
6769 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6770 // Network boot
6771 boot_device != 'n' &&
6772 #endif
6773 boot_device != 'c' && boot_device != 'd') {
6774 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6775 exit(1);
6777 break;
6778 case QEMU_OPTION_fda:
6779 fd_filename[0] = optarg;
6780 break;
6781 case QEMU_OPTION_fdb:
6782 fd_filename[1] = optarg;
6783 break;
6784 #ifdef TARGET_I386
6785 case QEMU_OPTION_no_fd_bootchk:
6786 fd_bootchk = 0;
6787 break;
6788 #endif
6789 case QEMU_OPTION_no_code_copy:
6790 code_copy_enabled = 0;
6791 break;
6792 case QEMU_OPTION_net:
6793 if (nb_net_clients >= MAX_NET_CLIENTS) {
6794 fprintf(stderr, "qemu: too many network clients\n");
6795 exit(1);
6797 pstrcpy(net_clients[nb_net_clients],
6798 sizeof(net_clients[0]),
6799 optarg);
6800 nb_net_clients++;
6801 break;
6802 #ifdef CONFIG_SLIRP
6803 case QEMU_OPTION_tftp:
6804 tftp_prefix = optarg;
6805 break;
6806 #ifndef _WIN32
6807 case QEMU_OPTION_smb:
6808 net_slirp_smb(optarg);
6809 break;
6810 #endif
6811 case QEMU_OPTION_redir:
6812 net_slirp_redir(optarg);
6813 break;
6814 #endif
6815 #ifdef HAS_AUDIO
6816 case QEMU_OPTION_audio_help:
6817 AUD_help ();
6818 exit (0);
6819 break;
6820 case QEMU_OPTION_soundhw:
6821 select_soundhw (optarg);
6822 break;
6823 #endif
6824 case QEMU_OPTION_h:
6825 help();
6826 break;
6827 case QEMU_OPTION_m:
6828 ram_size = atoi(optarg) * 1024 * 1024;
6829 if (ram_size <= 0)
6830 help();
6831 if (ram_size > PHYS_RAM_MAX_SIZE) {
6832 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6833 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6834 exit(1);
6836 break;
6837 case QEMU_OPTION_d:
6839 int mask;
6840 CPULogItem *item;
6842 mask = cpu_str_to_log_mask(optarg);
6843 if (!mask) {
6844 printf("Log items (comma separated):\n");
6845 for(item = cpu_log_items; item->mask != 0; item++) {
6846 printf("%-10s %s\n", item->name, item->help);
6848 exit(1);
6850 cpu_set_log(mask);
6852 break;
6853 #ifdef CONFIG_GDBSTUB
6854 case QEMU_OPTION_s:
6855 use_gdbstub = 1;
6856 break;
6857 case QEMU_OPTION_p:
6858 gdbstub_port = atoi(optarg);
6859 break;
6860 #endif
6861 case QEMU_OPTION_L:
6862 bios_dir = optarg;
6863 break;
6864 case QEMU_OPTION_S:
6865 autostart = 0;
6866 break;
6867 case QEMU_OPTION_k:
6868 keyboard_layout = optarg;
6869 break;
6870 case QEMU_OPTION_localtime:
6871 rtc_utc = 0;
6872 break;
6873 case QEMU_OPTION_cirrusvga:
6874 cirrus_vga_enabled = 1;
6875 break;
6876 case QEMU_OPTION_std_vga:
6877 cirrus_vga_enabled = 0;
6878 break;
6879 case QEMU_OPTION_g:
6881 const char *p;
6882 int w, h, depth;
6883 p = optarg;
6884 w = strtol(p, (char **)&p, 10);
6885 if (w <= 0) {
6886 graphic_error:
6887 fprintf(stderr, "qemu: invalid resolution or depth\n");
6888 exit(1);
6890 if (*p != 'x')
6891 goto graphic_error;
6892 p++;
6893 h = strtol(p, (char **)&p, 10);
6894 if (h <= 0)
6895 goto graphic_error;
6896 if (*p == 'x') {
6897 p++;
6898 depth = strtol(p, (char **)&p, 10);
6899 if (depth != 8 && depth != 15 && depth != 16 &&
6900 depth != 24 && depth != 32)
6901 goto graphic_error;
6902 } else if (*p == '\0') {
6903 depth = graphic_depth;
6904 } else {
6905 goto graphic_error;
6908 graphic_width = w;
6909 graphic_height = h;
6910 graphic_depth = depth;
6912 break;
6913 case QEMU_OPTION_monitor:
6914 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6915 break;
6916 case QEMU_OPTION_vmchannel:
6917 pstrcpy(vmchannel_device, sizeof(vmchannel_device), optarg);
6918 break;
6919 case QEMU_OPTION_serial:
6920 if (serial_device_index >= MAX_SERIAL_PORTS) {
6921 fprintf(stderr, "qemu: too many serial ports\n");
6922 exit(1);
6924 pstrcpy(serial_devices[serial_device_index],
6925 sizeof(serial_devices[0]), optarg);
6926 serial_device_index++;
6927 break;
6928 case QEMU_OPTION_parallel:
6929 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6930 fprintf(stderr, "qemu: too many parallel ports\n");
6931 exit(1);
6933 pstrcpy(parallel_devices[parallel_device_index],
6934 sizeof(parallel_devices[0]), optarg);
6935 parallel_device_index++;
6936 break;
6937 case QEMU_OPTION_loadvm:
6938 loadvm = optarg;
6939 break;
6940 case QEMU_OPTION_full_screen:
6941 full_screen = 1;
6942 break;
6943 #ifdef CONFIG_SDL
6944 case QEMU_OPTION_no_quit:
6945 no_quit = 1;
6946 break;
6947 #endif
6948 case QEMU_OPTION_pidfile:
6949 create_pidfile(optarg);
6950 break;
6951 #ifdef TARGET_I386
6952 case QEMU_OPTION_win2k_hack:
6953 win2k_install_hack = 1;
6954 break;
6955 #endif
6956 #ifdef USE_KQEMU
6957 case QEMU_OPTION_no_kqemu:
6958 kqemu_allowed = 0;
6959 break;
6960 case QEMU_OPTION_kernel_kqemu:
6961 kqemu_allowed = 2;
6962 break;
6963 #endif
6964 #ifdef USE_KVM
6965 case QEMU_OPTION_no_kvm:
6966 kvm_allowed = 0;
6967 break;
6968 #endif
6969 case QEMU_OPTION_usb:
6970 usb_enabled = 1;
6971 break;
6972 case QEMU_OPTION_usbdevice:
6973 usb_enabled = 1;
6974 if (usb_devices_index >= MAX_USB_CMDLINE) {
6975 fprintf(stderr, "Too many USB devices\n");
6976 exit(1);
6978 pstrcpy(usb_devices[usb_devices_index],
6979 sizeof(usb_devices[usb_devices_index]),
6980 optarg);
6981 usb_devices_index++;
6982 break;
6983 case QEMU_OPTION_smp:
6984 smp_cpus = atoi(optarg);
6985 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6986 fprintf(stderr, "Invalid number of CPUs\n");
6987 exit(1);
6989 break;
6990 case QEMU_OPTION_vnc:
6991 vnc_display = optarg;
6992 break;
6993 case QEMU_OPTION_no_acpi:
6994 acpi_enabled = 0;
6995 break;
6996 case QEMU_OPTION_no_reboot:
6997 no_reboot = 1;
6998 break;
6999 case QEMU_OPTION_daemonize:
7000 daemonize = 1;
7001 break;
7002 case QEMU_OPTION_option_rom:
7003 if (nb_option_roms >= MAX_OPTION_ROMS) {
7004 fprintf(stderr, "Too many option ROMs\n");
7005 exit(1);
7007 option_rom[nb_option_roms] = optarg;
7008 nb_option_roms++;
7009 break;
7010 case QEMU_OPTION_semihosting:
7011 semihosting_enabled = 1;
7012 break;
7017 #ifndef _WIN32
7018 if (daemonize && !nographic && vnc_display == NULL) {
7019 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7020 daemonize = 0;
7023 if (daemonize) {
7024 pid_t pid;
7026 if (pipe(fds) == -1)
7027 exit(1);
7029 pid = fork();
7030 if (pid > 0) {
7031 uint8_t status;
7032 ssize_t len;
7034 close(fds[1]);
7036 again:
7037 len = read(fds[0], &status, 1);
7038 if (len == -1 && (errno == EINTR))
7039 goto again;
7041 if (len != 1 || status != 0)
7042 exit(1);
7043 else
7044 exit(0);
7045 } else if (pid < 0)
7046 exit(1);
7048 setsid();
7050 pid = fork();
7051 if (pid > 0)
7052 exit(0);
7053 else if (pid < 0)
7054 exit(1);
7056 umask(027);
7057 chdir("/");
7059 signal(SIGTSTP, SIG_IGN);
7060 signal(SIGTTOU, SIG_IGN);
7061 signal(SIGTTIN, SIG_IGN);
7063 #endif
7065 #if USE_KVM
7066 if (kvm_allowed) {
7067 if (kvm_qemu_init() < 0) {
7068 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
7069 kvm_allowed = 0;
7072 #endif
7074 #ifdef USE_KQEMU
7075 if (smp_cpus > 1)
7076 kqemu_allowed = 0;
7077 #endif
7078 linux_boot = (kernel_filename != NULL);
7080 if (!linux_boot &&
7081 hd_filename[0] == '\0' &&
7082 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7083 fd_filename[0] == '\0')
7084 help();
7086 /* boot to floppy or the default cd if no hard disk defined yet */
7087 if (hd_filename[0] == '\0' && boot_device == 'c') {
7088 if (fd_filename[0] != '\0')
7089 boot_device = 'a';
7090 else
7091 boot_device = 'd';
7094 setvbuf(stdout, NULL, _IOLBF, 0);
7096 init_timers();
7097 init_timer_alarm();
7098 qemu_aio_init();
7100 #ifdef _WIN32
7101 socket_init();
7102 #endif
7104 /* init network clients */
7105 if (nb_net_clients == 0) {
7106 /* if no clients, we use a default config */
7107 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7108 "nic");
7109 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7110 "user");
7111 nb_net_clients = 2;
7114 for(i = 0;i < nb_net_clients; i++) {
7115 if (net_client_init(net_clients[i]) < 0)
7116 exit(1);
7119 #ifdef TARGET_I386
7120 if (boot_device == 'n') {
7121 for (i = 0; i < nb_nics; i++) {
7122 const char *model = nd_table[i].model;
7123 char buf[1024];
7124 if (model == NULL)
7125 model = "ne2k_pci";
7126 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7127 if (get_image_size(buf) > 0) {
7128 option_rom[nb_option_roms] = strdup(buf);
7129 nb_option_roms++;
7130 break;
7133 if (i == nb_nics) {
7134 fprintf(stderr, "No valid PXE rom found for network device\n");
7135 exit(1);
7137 boot_device = 'c'; /* to prevent confusion by the BIOS */
7139 #endif
7141 /* init the memory */
7142 phys_ram_size = ram_size + vga_ram_size + bios_size;
7145 for (i = 0; i < nb_option_roms; i++) {
7146 int ret = get_image_size(option_rom[i]);
7147 if (ret == -1) {
7148 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7149 exit(1);
7151 phys_ram_size += ret;
7154 #if USE_KVM
7155 /* Initialize kvm */
7156 if (kvm_allowed) {
7157 phys_ram_size += KVM_EXTRA_PAGES * 4096;
7158 if (kvm_qemu_create_context() < 0) {
7159 fprintf(stderr, "Could not create KVM context\n");
7160 exit(1);
7162 } else {
7163 phys_ram_base = qemu_vmalloc(phys_ram_size);
7164 if (!phys_ram_base) {
7165 fprintf(stderr, "Could not allocate physical memory\n");
7166 exit(1);
7169 #else
7170 phys_ram_base = qemu_vmalloc(phys_ram_size);
7171 if (!phys_ram_base) {
7172 fprintf(stderr, "Could not allocate physical memory\n");
7173 exit(1);
7175 #endif
7177 /* we always create the cdrom drive, even if no disk is there */
7178 bdrv_init();
7179 if (cdrom_index >= 0) {
7180 bs_table[cdrom_index] = bdrv_new("cdrom");
7181 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7184 /* open the virtual block devices */
7185 for(i = 0; i < MAX_DISKS; i++) {
7186 if (hd_filename[i]) {
7187 if (!bs_table[i]) {
7188 char buf[64];
7189 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7190 bs_table[i] = bdrv_new(buf);
7192 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7193 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7194 hd_filename[i]);
7195 exit(1);
7197 if (i == 0 && cyls != 0) {
7198 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7199 bdrv_set_translation_hint(bs_table[i], translation);
7204 /* we always create at least one floppy disk */
7205 fd_table[0] = bdrv_new("fda");
7206 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7208 for(i = 0; i < MAX_FD; i++) {
7209 if (fd_filename[i]) {
7210 if (!fd_table[i]) {
7211 char buf[64];
7212 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7213 fd_table[i] = bdrv_new(buf);
7214 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7216 if (fd_filename[i] != '\0') {
7217 if (bdrv_open(fd_table[i], fd_filename[i],
7218 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7219 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7220 fd_filename[i]);
7221 exit(1);
7227 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7228 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7230 init_ioports();
7232 /* terminal init */
7233 if (nographic) {
7234 dumb_display_init(ds);
7235 } else if (vnc_display != NULL) {
7236 vnc_display_init(ds, vnc_display);
7237 } else {
7238 #if defined(CONFIG_SDL)
7239 sdl_display_init(ds, full_screen);
7240 #elif defined(CONFIG_COCOA)
7241 cocoa_display_init(ds, full_screen);
7242 #else
7243 dumb_display_init(ds);
7244 #endif
7247 monitor_hd = qemu_chr_open(monitor_device);
7248 if (!monitor_hd) {
7249 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7250 exit(1);
7252 monitor_init(monitor_hd, !nographic);
7254 if (*vmchannel_device) {
7255 vmchannel_hd = qemu_chr_open(vmchannel_device);
7256 if (!vmchannel_hd) {
7257 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n", vmchannel_device);
7258 exit(1);
7260 vmchannel_init(vmchannel_hd);
7263 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7264 const char *devname = serial_devices[i];
7265 if (devname[0] != '\0' && strcmp(devname, "none")) {
7266 serial_hds[i] = qemu_chr_open(devname);
7267 if (!serial_hds[i]) {
7268 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7269 devname);
7270 exit(1);
7272 if (!strcmp(devname, "vc"))
7273 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7277 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7278 const char *devname = parallel_devices[i];
7279 if (devname[0] != '\0' && strcmp(devname, "none")) {
7280 parallel_hds[i] = qemu_chr_open(devname);
7281 if (!parallel_hds[i]) {
7282 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7283 devname);
7284 exit(1);
7286 if (!strcmp(devname, "vc"))
7287 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7291 machine->init(ram_size, vga_ram_size, boot_device,
7292 ds, fd_filename, snapshot,
7293 kernel_filename, kernel_cmdline, initrd_filename);
7295 /* init USB devices */
7296 if (usb_enabled) {
7297 for(i = 0; i < usb_devices_index; i++) {
7298 if (usb_device_add(usb_devices[i]) < 0) {
7299 fprintf(stderr, "Warning: could not add USB device %s\n",
7300 usb_devices[i]);
7305 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7306 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7308 #ifdef CONFIG_GDBSTUB
7309 if (use_gdbstub) {
7310 /* XXX: use standard host:port notation and modify options
7311 accordingly. */
7312 if (gdbserver_start_port(gdbstub_port) < 0) {
7313 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7314 gdbstub_port);
7315 exit(1);
7317 } else
7318 #endif
7319 if (loadvm)
7320 do_loadvm(loadvm);
7323 /* XXX: simplify init */
7324 read_passwords();
7325 if (autostart) {
7326 vm_start();
7330 if (daemonize) {
7331 uint8_t status = 0;
7332 ssize_t len;
7333 int fd;
7335 again1:
7336 len = write(fds[1], &status, 1);
7337 if (len == -1 && (errno == EINTR))
7338 goto again1;
7340 if (len != 1)
7341 exit(1);
7343 fd = open("/dev/null", O_RDWR);
7344 if (fd == -1)
7345 exit(1);
7347 dup2(fd, 0);
7348 dup2(fd, 1);
7349 dup2(fd, 2);
7351 close(fd);
7354 main_loop();
7355 quit_timers();
7356 return 0;