kvm: libkvm: remove some unused parameters
[qemu-kvm/fedora.git] / vl.c
blob7df1c809b4653c978a663333c71b7b02599c22e6
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 int balloon_used = 0;
157 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
158 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
159 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
160 #ifdef TARGET_I386
161 int win2k_install_hack = 0;
162 #endif
163 int usb_enabled = 0;
164 static VLANState *first_vlan;
165 int smp_cpus = 1;
166 const char *vnc_display;
167 #if defined(TARGET_SPARC)
168 #define MAX_CPUS 16
169 #elif defined(TARGET_I386)
170 #define MAX_CPUS 255
171 #else
172 #define MAX_CPUS 1
173 #endif
174 int acpi_enabled = 1;
175 int fd_bootchk = 1;
176 int no_reboot = 0;
177 int daemonize = 0;
178 const char *incoming;
179 const char *option_rom[MAX_OPTION_ROMS];
180 int nb_option_roms;
181 int semihosting_enabled = 0;
182 int autostart = 1;
183 int time_drift_fix = 0;
184 const char *cpu_vendor_string;
186 /***********************************************************/
187 /* x86 ISA bus support */
189 target_phys_addr_t isa_mem_base = 0;
190 PicState2 *isa_pic;
192 uint32_t default_ioport_readb(void *opaque, uint32_t address)
194 #ifdef DEBUG_UNUSED_IOPORT
195 fprintf(stderr, "inb: port=0x%04x\n", address);
196 #endif
197 return 0xff;
200 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
204 #endif
207 /* default is to make two byte accesses */
208 uint32_t default_ioport_readw(void *opaque, uint32_t address)
210 uint32_t data;
211 data = ioport_read_table[0][address](ioport_opaque[address], address);
212 address = (address + 1) & (MAX_IOPORTS - 1);
213 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
214 return data;
217 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
219 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
220 address = (address + 1) & (MAX_IOPORTS - 1);
221 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
224 uint32_t default_ioport_readl(void *opaque, uint32_t address)
226 #ifdef DEBUG_UNUSED_IOPORT
227 fprintf(stderr, "inl: port=0x%04x\n", address);
228 #endif
229 return 0xffffffff;
232 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
234 #ifdef DEBUG_UNUSED_IOPORT
235 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
236 #endif
239 void init_ioports(void)
241 int i;
243 for(i = 0; i < MAX_IOPORTS; i++) {
244 ioport_read_table[0][i] = default_ioport_readb;
245 ioport_write_table[0][i] = default_ioport_writeb;
246 ioport_read_table[1][i] = default_ioport_readw;
247 ioport_write_table[1][i] = default_ioport_writew;
248 ioport_read_table[2][i] = default_ioport_readl;
249 ioport_write_table[2][i] = default_ioport_writel;
253 /* size is the word size in byte */
254 int register_ioport_read(int start, int length, int size,
255 IOPortReadFunc *func, void *opaque)
257 int i, bsize;
259 if (size == 1) {
260 bsize = 0;
261 } else if (size == 2) {
262 bsize = 1;
263 } else if (size == 4) {
264 bsize = 2;
265 } else {
266 hw_error("register_ioport_read: invalid size");
267 return -1;
269 for(i = start; i < start + length; i += size) {
270 ioport_read_table[bsize][i] = func;
271 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
272 hw_error("register_ioport_read: invalid opaque");
273 ioport_opaque[i] = opaque;
275 return 0;
278 /* size is the word size in byte */
279 int register_ioport_write(int start, int length, int size,
280 IOPortWriteFunc *func, void *opaque)
282 int i, bsize;
284 if (size == 1) {
285 bsize = 0;
286 } else if (size == 2) {
287 bsize = 1;
288 } else if (size == 4) {
289 bsize = 2;
290 } else {
291 hw_error("register_ioport_write: invalid size");
292 return -1;
294 for(i = start; i < start + length; i += size) {
295 ioport_write_table[bsize][i] = func;
296 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
297 hw_error("register_ioport_write: invalid opaque");
298 ioport_opaque[i] = opaque;
300 return 0;
303 void isa_unassign_ioport(int start, int length)
305 int i;
307 for(i = start; i < start + length; i++) {
308 ioport_read_table[0][i] = default_ioport_readb;
309 ioport_read_table[1][i] = default_ioport_readw;
310 ioport_read_table[2][i] = default_ioport_readl;
312 ioport_write_table[0][i] = default_ioport_writeb;
313 ioport_write_table[1][i] = default_ioport_writew;
314 ioport_write_table[2][i] = default_ioport_writel;
318 /***********************************************************/
320 void cpu_outb(CPUState *env, int addr, int val)
322 #ifdef DEBUG_IOPORT
323 if (loglevel & CPU_LOG_IOPORT)
324 fprintf(logfile, "outb: %04x %02x\n", addr, val);
325 #endif
326 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
327 #ifdef USE_KQEMU
328 if (env)
329 env->last_io_time = cpu_get_time_fast();
330 #endif
333 void cpu_outw(CPUState *env, int addr, int val)
335 #ifdef DEBUG_IOPORT
336 if (loglevel & CPU_LOG_IOPORT)
337 fprintf(logfile, "outw: %04x %04x\n", addr, val);
338 #endif
339 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
340 #ifdef USE_KQEMU
341 if (env)
342 env->last_io_time = cpu_get_time_fast();
343 #endif
346 void cpu_outl(CPUState *env, int addr, int val)
348 #ifdef DEBUG_IOPORT
349 if (loglevel & CPU_LOG_IOPORT)
350 fprintf(logfile, "outl: %04x %08x\n", addr, val);
351 #endif
352 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
353 #ifdef USE_KQEMU
354 if (env)
355 env->last_io_time = cpu_get_time_fast();
356 #endif
359 int cpu_inb(CPUState *env, int addr)
361 int val;
362 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
363 #ifdef DEBUG_IOPORT
364 if (loglevel & CPU_LOG_IOPORT)
365 fprintf(logfile, "inb : %04x %02x\n", addr, val);
366 #endif
367 #ifdef USE_KQEMU
368 if (env)
369 env->last_io_time = cpu_get_time_fast();
370 #endif
371 return val;
374 int cpu_inw(CPUState *env, int addr)
376 int val;
377 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "inw : %04x %04x\n", addr, val);
381 #endif
382 #ifdef USE_KQEMU
383 if (env)
384 env->last_io_time = cpu_get_time_fast();
385 #endif
386 return val;
389 int cpu_inl(CPUState *env, int addr)
391 int val;
392 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inl : %04x %08x\n", addr, val);
396 #endif
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
401 return val;
404 /***********************************************************/
405 void hw_error(const char *fmt, ...)
407 va_list ap;
408 CPUState *env;
410 va_start(ap, fmt);
411 fprintf(stderr, "qemu: hardware error: ");
412 vfprintf(stderr, fmt, ap);
413 fprintf(stderr, "\n");
414 for(env = first_cpu; env != NULL; env = env->next_cpu) {
415 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
416 #ifdef TARGET_I386
417 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
418 #else
419 cpu_dump_state(env, stderr, fprintf, 0);
420 #endif
422 va_end(ap);
423 abort();
426 /***********************************************************/
427 /* keyboard/mouse */
429 static QEMUPutKBDEvent *qemu_put_kbd_event;
430 static void *qemu_put_kbd_event_opaque;
431 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
432 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
434 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
436 qemu_put_kbd_event_opaque = opaque;
437 qemu_put_kbd_event = func;
440 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
441 void *opaque, int absolute,
442 const char *name)
444 QEMUPutMouseEntry *s, *cursor;
446 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
447 if (!s)
448 return NULL;
450 s->qemu_put_mouse_event = func;
451 s->qemu_put_mouse_event_opaque = opaque;
452 s->qemu_put_mouse_event_absolute = absolute;
453 s->qemu_put_mouse_event_name = qemu_strdup(name);
454 s->next = NULL;
456 if (!qemu_put_mouse_event_head) {
457 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
458 return s;
461 cursor = qemu_put_mouse_event_head;
462 while (cursor->next != NULL)
463 cursor = cursor->next;
465 cursor->next = s;
466 qemu_put_mouse_event_current = s;
468 return s;
471 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
473 QEMUPutMouseEntry *prev = NULL, *cursor;
475 if (!qemu_put_mouse_event_head || entry == NULL)
476 return;
478 cursor = qemu_put_mouse_event_head;
479 while (cursor != NULL && cursor != entry) {
480 prev = cursor;
481 cursor = cursor->next;
484 if (cursor == NULL) // does not exist or list empty
485 return;
486 else if (prev == NULL) { // entry is head
487 qemu_put_mouse_event_head = cursor->next;
488 if (qemu_put_mouse_event_current == entry)
489 qemu_put_mouse_event_current = cursor->next;
490 qemu_free(entry->qemu_put_mouse_event_name);
491 qemu_free(entry);
492 return;
495 prev->next = entry->next;
497 if (qemu_put_mouse_event_current == entry)
498 qemu_put_mouse_event_current = prev;
500 qemu_free(entry->qemu_put_mouse_event_name);
501 qemu_free(entry);
504 void kbd_put_keycode(int keycode)
506 if (qemu_put_kbd_event) {
507 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
511 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
513 QEMUPutMouseEvent *mouse_event;
514 void *mouse_event_opaque;
516 if (!qemu_put_mouse_event_current) {
517 return;
520 mouse_event =
521 qemu_put_mouse_event_current->qemu_put_mouse_event;
522 mouse_event_opaque =
523 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
525 if (mouse_event) {
526 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
530 int kbd_mouse_is_absolute(void)
532 if (!qemu_put_mouse_event_current)
533 return 0;
535 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
538 void do_info_mice(void)
540 QEMUPutMouseEntry *cursor;
541 int index = 0;
543 if (!qemu_put_mouse_event_head) {
544 term_printf("No mouse devices connected\n");
545 return;
548 term_printf("Mouse devices available:\n");
549 cursor = qemu_put_mouse_event_head;
550 while (cursor != NULL) {
551 term_printf("%c Mouse #%d: %s\n",
552 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
553 index, cursor->qemu_put_mouse_event_name);
554 index++;
555 cursor = cursor->next;
559 void do_mouse_set(int index)
561 QEMUPutMouseEntry *cursor;
562 int i = 0;
564 if (!qemu_put_mouse_event_head) {
565 term_printf("No mouse devices connected\n");
566 return;
569 cursor = qemu_put_mouse_event_head;
570 while (cursor != NULL && index != i) {
571 i++;
572 cursor = cursor->next;
575 if (cursor != NULL)
576 qemu_put_mouse_event_current = cursor;
577 else
578 term_printf("Mouse at given index not found\n");
581 /* compute with 96 bit intermediate result: (a*b)/c */
582 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
584 union {
585 uint64_t ll;
586 struct {
587 #ifdef WORDS_BIGENDIAN
588 uint32_t high, low;
589 #else
590 uint32_t low, high;
591 #endif
592 } l;
593 } u, res;
594 uint64_t rl, rh;
596 u.ll = a;
597 rl = (uint64_t)u.l.low * (uint64_t)b;
598 rh = (uint64_t)u.l.high * (uint64_t)b;
599 rh += (rl >> 32);
600 res.l.high = rh / c;
601 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
602 return res.ll;
605 /***********************************************************/
606 /* real time host monotonic timer */
608 #define QEMU_TIMER_BASE 1000000000LL
610 #ifdef WIN32
612 static int64_t clock_freq;
614 static void init_get_clock(void)
616 LARGE_INTEGER freq;
617 int ret;
618 ret = QueryPerformanceFrequency(&freq);
619 if (ret == 0) {
620 fprintf(stderr, "Could not calibrate ticks\n");
621 exit(1);
623 clock_freq = freq.QuadPart;
626 static int64_t get_clock(void)
628 LARGE_INTEGER ti;
629 QueryPerformanceCounter(&ti);
630 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
633 #else
635 static int use_rt_clock;
637 static void init_get_clock(void)
639 use_rt_clock = 0;
640 #if defined(__linux__)
642 struct timespec ts;
643 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
644 use_rt_clock = 1;
647 #endif
650 static int64_t get_clock(void)
652 #if defined(__linux__)
653 if (use_rt_clock) {
654 struct timespec ts;
655 clock_gettime(CLOCK_MONOTONIC, &ts);
656 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
657 } else
658 #endif
660 /* XXX: using gettimeofday leads to problems if the date
661 changes, so it should be avoided. */
662 struct timeval tv;
663 gettimeofday(&tv, NULL);
664 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
668 #endif
670 /***********************************************************/
671 /* guest cycle counter */
673 static int64_t cpu_ticks_prev;
674 static int64_t cpu_ticks_offset;
675 static int64_t cpu_clock_offset;
676 static int cpu_ticks_enabled;
678 /* return the host CPU cycle counter and handle stop/restart */
679 int64_t cpu_get_ticks(void)
681 if (!cpu_ticks_enabled) {
682 return cpu_ticks_offset;
683 } else {
684 int64_t ticks;
685 ticks = cpu_get_real_ticks();
686 if (cpu_ticks_prev > ticks) {
687 /* Note: non increasing ticks may happen if the host uses
688 software suspend */
689 cpu_ticks_offset += cpu_ticks_prev - ticks;
691 cpu_ticks_prev = ticks;
692 return ticks + cpu_ticks_offset;
696 /* return the host CPU monotonic timer and handle stop/restart */
697 static int64_t cpu_get_clock(void)
699 int64_t ti;
700 if (!cpu_ticks_enabled) {
701 return cpu_clock_offset;
702 } else {
703 ti = get_clock();
704 return ti + cpu_clock_offset;
708 /* enable cpu_get_ticks() */
709 void cpu_enable_ticks(void)
711 if (!cpu_ticks_enabled) {
712 cpu_ticks_offset -= cpu_get_real_ticks();
713 cpu_clock_offset -= get_clock();
714 cpu_ticks_enabled = 1;
718 /* disable cpu_get_ticks() : the clock is stopped. You must not call
719 cpu_get_ticks() after that. */
720 void cpu_disable_ticks(void)
722 if (cpu_ticks_enabled) {
723 cpu_ticks_offset = cpu_get_ticks();
724 cpu_clock_offset = cpu_get_clock();
725 cpu_ticks_enabled = 0;
729 /***********************************************************/
730 /* timers */
732 #define QEMU_TIMER_REALTIME 0
733 #define QEMU_TIMER_VIRTUAL 1
735 struct QEMUClock {
736 int type;
737 /* XXX: add frequency */
740 struct QEMUTimer {
741 QEMUClock *clock;
742 int64_t expire_time;
743 QEMUTimerCB *cb;
744 void *opaque;
745 struct QEMUTimer *next;
748 QEMUClock *rt_clock;
749 QEMUClock *vm_clock;
751 static QEMUTimer *active_timers[2];
752 #ifdef _WIN32
753 static MMRESULT timerID;
754 static HANDLE host_alarm = NULL;
755 static unsigned int period = 1;
756 #else
757 /* frequency of the times() clock tick */
758 static int timer_freq;
759 #endif
761 QEMUClock *qemu_new_clock(int type)
763 QEMUClock *clock;
764 clock = qemu_mallocz(sizeof(QEMUClock));
765 if (!clock)
766 return NULL;
767 clock->type = type;
768 return clock;
771 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
773 QEMUTimer *ts;
775 ts = qemu_mallocz(sizeof(QEMUTimer));
776 ts->clock = clock;
777 ts->cb = cb;
778 ts->opaque = opaque;
779 return ts;
782 void qemu_free_timer(QEMUTimer *ts)
784 qemu_free(ts);
787 /* stop a timer, but do not dealloc it */
788 void qemu_del_timer(QEMUTimer *ts)
790 QEMUTimer **pt, *t;
792 /* NOTE: this code must be signal safe because
793 qemu_timer_expired() can be called from a signal. */
794 pt = &active_timers[ts->clock->type];
795 for(;;) {
796 t = *pt;
797 if (!t)
798 break;
799 if (t == ts) {
800 *pt = t->next;
801 break;
803 pt = &t->next;
807 /* modify the current timer so that it will be fired when current_time
808 >= expire_time. The corresponding callback will be called. */
809 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
811 QEMUTimer **pt, *t;
813 qemu_del_timer(ts);
815 /* add the timer in the sorted list */
816 /* NOTE: this code must be signal safe because
817 qemu_timer_expired() can be called from a signal. */
818 pt = &active_timers[ts->clock->type];
819 for(;;) {
820 t = *pt;
821 if (!t)
822 break;
823 if (t->expire_time > expire_time)
824 break;
825 pt = &t->next;
827 ts->expire_time = expire_time;
828 ts->next = *pt;
829 *pt = ts;
832 int qemu_timer_pending(QEMUTimer *ts)
834 QEMUTimer *t;
835 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
836 if (t == ts)
837 return 1;
839 return 0;
842 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
844 if (!timer_head)
845 return 0;
846 return (timer_head->expire_time <= current_time);
849 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
851 QEMUTimer *ts;
853 for(;;) {
854 ts = *ptimer_head;
855 if (!ts || ts->expire_time > current_time)
856 break;
857 /* remove timer from the list before calling the callback */
858 *ptimer_head = ts->next;
859 ts->next = NULL;
861 /* run the callback (the timer list can be modified) */
862 ts->cb(ts->opaque);
866 int64_t qemu_get_clock(QEMUClock *clock)
868 switch(clock->type) {
869 case QEMU_TIMER_REALTIME:
870 return get_clock() / 1000000;
871 default:
872 case QEMU_TIMER_VIRTUAL:
873 return cpu_get_clock();
877 static void init_timers(void)
879 init_get_clock();
880 ticks_per_sec = QEMU_TIMER_BASE;
881 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
882 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
885 /* save a timer */
886 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
888 uint64_t expire_time;
890 if (qemu_timer_pending(ts)) {
891 expire_time = ts->expire_time;
892 } else {
893 expire_time = -1;
895 qemu_put_be64(f, expire_time);
898 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
900 uint64_t expire_time;
902 expire_time = qemu_get_be64(f);
903 if (expire_time != -1) {
904 qemu_mod_timer(ts, expire_time);
905 } else {
906 qemu_del_timer(ts);
910 static void timer_save(QEMUFile *f, void *opaque)
912 if (cpu_ticks_enabled) {
913 hw_error("cannot save state if virtual timers are running");
915 qemu_put_be64s(f, &cpu_ticks_offset);
916 qemu_put_be64s(f, &ticks_per_sec);
917 qemu_put_be64s(f, &cpu_clock_offset);
920 static int timer_load(QEMUFile *f, void *opaque, int version_id)
922 if (version_id != 1 && version_id != 2)
923 return -EINVAL;
924 if (cpu_ticks_enabled) {
925 return -EINVAL;
927 qemu_get_be64s(f, &cpu_ticks_offset);
928 qemu_get_be64s(f, &ticks_per_sec);
929 if (version_id == 2) {
930 qemu_get_be64s(f, &cpu_clock_offset);
932 return 0;
935 #ifdef _WIN32
936 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
937 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
938 #else
939 static void host_alarm_handler(int host_signum)
940 #endif
942 #if 0
943 #define DISP_FREQ 1000
945 static int64_t delta_min = INT64_MAX;
946 static int64_t delta_max, delta_cum, last_clock, delta, ti;
947 static int count;
948 ti = qemu_get_clock(vm_clock);
949 if (last_clock != 0) {
950 delta = ti - last_clock;
951 if (delta < delta_min)
952 delta_min = delta;
953 if (delta > delta_max)
954 delta_max = delta;
955 delta_cum += delta;
956 if (++count == DISP_FREQ) {
957 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
958 muldiv64(delta_min, 1000000, ticks_per_sec),
959 muldiv64(delta_max, 1000000, ticks_per_sec),
960 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
961 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
962 count = 0;
963 delta_min = INT64_MAX;
964 delta_max = 0;
965 delta_cum = 0;
968 last_clock = ti;
970 #endif
971 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
972 qemu_get_clock(vm_clock)) ||
973 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
974 qemu_get_clock(rt_clock))) {
975 #ifdef _WIN32
976 SetEvent(host_alarm);
977 #endif
978 CPUState *env = cpu_single_env;
979 if (env) {
980 /* stop the currently executing cpu because a timer occured */
981 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
982 #ifdef USE_KQEMU
983 if (env->kqemu_enabled) {
984 kqemu_cpu_interrupt(env);
986 #endif
991 #ifndef _WIN32
993 #if defined(__linux__)
995 #define RTC_FREQ 1024
997 static int use_rtc = 1;
998 static int rtc_fd;
1000 static int start_rtc_timer(void)
1002 rtc_fd = open("/dev/rtc", O_RDONLY);
1003 if (rtc_fd < 0)
1004 return -1;
1005 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1006 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1007 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1008 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1009 goto fail;
1011 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1012 fail:
1013 close(rtc_fd);
1014 return -1;
1016 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1017 return 0;
1020 #else
1022 static int start_rtc_timer(void)
1024 return -1;
1027 #endif /* !defined(__linux__) */
1029 #endif /* !defined(_WIN32) */
1031 static void init_timer_alarm(void)
1033 #ifdef _WIN32
1035 int count=0;
1036 TIMECAPS tc;
1038 ZeroMemory(&tc, sizeof(TIMECAPS));
1039 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1040 if (period < tc.wPeriodMin)
1041 period = tc.wPeriodMin;
1042 timeBeginPeriod(period);
1043 timerID = timeSetEvent(1, // interval (ms)
1044 period, // resolution
1045 host_alarm_handler, // function
1046 (DWORD)&count, // user parameter
1047 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1048 if( !timerID ) {
1049 perror("failed timer alarm");
1050 exit(1);
1052 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1053 if (!host_alarm) {
1054 perror("failed CreateEvent");
1055 exit(1);
1057 qemu_add_wait_object(host_alarm, NULL, NULL);
1059 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1060 #else
1062 struct sigaction act;
1063 struct itimerval itv;
1065 /* get times() syscall frequency */
1066 timer_freq = sysconf(_SC_CLK_TCK);
1068 /* timer signal */
1069 sigfillset(&act.sa_mask);
1070 act.sa_flags = 0;
1071 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1072 act.sa_flags |= SA_ONSTACK;
1073 #endif
1074 act.sa_handler = host_alarm_handler;
1075 sigaction(SIGALRM, &act, NULL);
1077 itv.it_interval.tv_sec = 0;
1078 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1079 itv.it_value.tv_sec = 0;
1080 itv.it_value.tv_usec = 10 * 1000;
1081 setitimer(ITIMER_REAL, &itv, NULL);
1082 /* we probe the tick duration of the kernel to inform the user if
1083 the emulated kernel requested a too high timer frequency */
1084 getitimer(ITIMER_REAL, &itv);
1086 #if defined(__linux__)
1087 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1088 have timers with 1 ms resolution. The correct solution will
1089 be to use the POSIX real time timers available in recent
1090 2.6 kernels */
1091 if (itv.it_interval.tv_usec > 1000 || 1) {
1092 /* try to use /dev/rtc to have a faster timer */
1093 if (!use_rtc || (start_rtc_timer() < 0))
1094 goto use_itimer;
1095 /* disable itimer */
1096 itv.it_interval.tv_sec = 0;
1097 itv.it_interval.tv_usec = 0;
1098 itv.it_value.tv_sec = 0;
1099 itv.it_value.tv_usec = 0;
1100 setitimer(ITIMER_REAL, &itv, NULL);
1102 /* use the RTC */
1103 sigaction(SIGIO, &act, NULL);
1104 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1105 fcntl(rtc_fd, F_SETOWN, getpid());
1106 } else
1107 #endif /* defined(__linux__) */
1109 use_itimer:
1110 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1111 PIT_FREQ) / 1000000;
1114 #endif
1117 void quit_timers(void)
1119 #ifdef _WIN32
1120 timeKillEvent(timerID);
1121 timeEndPeriod(period);
1122 if (host_alarm) {
1123 CloseHandle(host_alarm);
1124 host_alarm = NULL;
1126 #endif
1129 /***********************************************************/
1130 /* character device */
1132 static void qemu_chr_event(CharDriverState *s, int event)
1134 if (!s->chr_event)
1135 return;
1136 s->chr_event(s->handler_opaque, event);
1139 static void qemu_chr_reset_bh(void *opaque)
1141 CharDriverState *s = opaque;
1142 qemu_chr_event(s, CHR_EVENT_RESET);
1143 qemu_bh_delete(s->bh);
1144 s->bh = NULL;
1147 void qemu_chr_reset(CharDriverState *s)
1149 if (s->bh == NULL) {
1150 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1151 qemu_bh_schedule(s->bh);
1155 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1157 return s->chr_write(s, buf, len);
1160 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1162 if (!s->chr_ioctl)
1163 return -ENOTSUP;
1164 return s->chr_ioctl(s, cmd, arg);
1167 int qemu_chr_can_read(CharDriverState *s)
1169 if (!s->chr_can_read)
1170 return 0;
1171 return s->chr_can_read(s->handler_opaque);
1174 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1176 s->chr_read(s->handler_opaque, buf, len);
1180 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1182 char buf[4096];
1183 va_list ap;
1184 va_start(ap, fmt);
1185 vsnprintf(buf, sizeof(buf), fmt, ap);
1186 qemu_chr_write(s, buf, strlen(buf));
1187 va_end(ap);
1190 void qemu_chr_send_event(CharDriverState *s, int event)
1192 if (s->chr_send_event)
1193 s->chr_send_event(s, event);
1196 void qemu_chr_add_handlers(CharDriverState *s,
1197 IOCanRWHandler *fd_can_read,
1198 IOReadHandler *fd_read,
1199 IOEventHandler *fd_event,
1200 void *opaque)
1202 s->chr_can_read = fd_can_read;
1203 s->chr_read = fd_read;
1204 s->chr_event = fd_event;
1205 s->handler_opaque = opaque;
1206 if (s->chr_update_read_handler)
1207 s->chr_update_read_handler(s);
1210 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1212 return len;
1215 static CharDriverState *qemu_chr_open_null(void)
1217 CharDriverState *chr;
1219 chr = qemu_mallocz(sizeof(CharDriverState));
1220 if (!chr)
1221 return NULL;
1222 chr->chr_write = null_chr_write;
1223 return chr;
1226 #ifdef _WIN32
1228 static void socket_cleanup(void)
1230 WSACleanup();
1233 static int socket_init(void)
1235 WSADATA Data;
1236 int ret, err;
1238 ret = WSAStartup(MAKEWORD(2,2), &Data);
1239 if (ret != 0) {
1240 err = WSAGetLastError();
1241 fprintf(stderr, "WSAStartup: %d\n", err);
1242 return -1;
1244 atexit(socket_cleanup);
1245 return 0;
1248 static int send_all(int fd, const uint8_t *buf, int len1)
1250 int ret, len;
1252 len = len1;
1253 while (len > 0) {
1254 ret = send(fd, buf, len, 0);
1255 if (ret < 0) {
1256 int errno;
1257 errno = WSAGetLastError();
1258 if (errno != WSAEWOULDBLOCK) {
1259 return -1;
1261 } else if (ret == 0) {
1262 break;
1263 } else {
1264 buf += ret;
1265 len -= ret;
1268 return len1 - len;
1271 void socket_set_nonblock(int fd)
1273 unsigned long opt = 1;
1274 ioctlsocket(fd, FIONBIO, &opt);
1277 #else
1279 static int unix_write(int fd, const uint8_t *buf, int len1)
1281 int ret, len;
1283 len = len1;
1284 while (len > 0) {
1285 ret = write(fd, buf, len);
1286 if (ret < 0) {
1287 if (errno != EINTR && errno != EAGAIN)
1288 return -1;
1289 } else if (ret == 0) {
1290 break;
1291 } else {
1292 buf += ret;
1293 len -= ret;
1296 return len1 - len;
1299 static inline int send_all(int fd, const uint8_t *buf, int len1)
1301 return unix_write(fd, buf, len1);
1304 void socket_set_nonblock(int fd)
1306 fcntl(fd, F_SETFL, O_NONBLOCK);
1308 #endif /* !_WIN32 */
1310 #ifndef _WIN32
1312 typedef struct {
1313 int fd_in, fd_out;
1314 int max_size;
1315 } FDCharDriver;
1317 #define STDIO_MAX_CLIENTS 2
1319 static int stdio_nb_clients;
1320 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1322 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1324 FDCharDriver *s = chr->opaque;
1325 return unix_write(s->fd_out, buf, len);
1328 static int fd_chr_read_poll(void *opaque)
1330 CharDriverState *chr = opaque;
1331 FDCharDriver *s = chr->opaque;
1333 s->max_size = qemu_chr_can_read(chr);
1334 return s->max_size;
1337 static void fd_chr_read(void *opaque)
1339 CharDriverState *chr = opaque;
1340 FDCharDriver *s = chr->opaque;
1341 int size, len;
1342 uint8_t buf[1024];
1344 len = sizeof(buf);
1345 if (len > s->max_size)
1346 len = s->max_size;
1347 if (len == 0)
1348 return;
1349 size = read(s->fd_in, buf, len);
1350 if (size == 0) {
1351 /* FD has been closed. Remove it from the active list. */
1352 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1353 return;
1355 if (size > 0) {
1356 qemu_chr_read(chr, buf, size);
1360 static void fd_chr_update_read_handler(CharDriverState *chr)
1362 FDCharDriver *s = chr->opaque;
1364 if (s->fd_in >= 0) {
1365 if (nographic && s->fd_in == 0) {
1366 } else {
1367 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1368 fd_chr_read, NULL, chr);
1373 /* open a character device to a unix fd */
1374 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1376 CharDriverState *chr;
1377 FDCharDriver *s;
1379 chr = qemu_mallocz(sizeof(CharDriverState));
1380 if (!chr)
1381 return NULL;
1382 s = qemu_mallocz(sizeof(FDCharDriver));
1383 if (!s) {
1384 free(chr);
1385 return NULL;
1387 s->fd_in = fd_in;
1388 s->fd_out = fd_out;
1389 chr->opaque = s;
1390 chr->chr_write = fd_chr_write;
1391 chr->chr_update_read_handler = fd_chr_update_read_handler;
1393 qemu_chr_reset(chr);
1395 return chr;
1398 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1400 int fd_out;
1402 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1403 if (fd_out < 0)
1404 return NULL;
1405 return qemu_chr_open_fd(-1, fd_out);
1408 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1410 int fd_in, fd_out;
1411 char filename_in[256], filename_out[256];
1413 snprintf(filename_in, 256, "%s.in", filename);
1414 snprintf(filename_out, 256, "%s.out", filename);
1415 fd_in = open(filename_in, O_RDWR | O_BINARY);
1416 fd_out = open(filename_out, O_RDWR | O_BINARY);
1417 if (fd_in < 0 || fd_out < 0) {
1418 if (fd_in >= 0)
1419 close(fd_in);
1420 if (fd_out >= 0)
1421 close(fd_out);
1422 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1423 if (fd_in < 0)
1424 return NULL;
1426 return qemu_chr_open_fd(fd_in, fd_out);
1430 /* for STDIO, we handle the case where several clients use it
1431 (nographic mode) */
1433 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1435 #define TERM_FIFO_MAX_SIZE 1
1437 static int term_got_escape, client_index;
1438 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1439 static int term_fifo_size;
1440 static int term_timestamps;
1441 static int64_t term_timestamps_start;
1443 void term_print_help(void)
1445 printf("\n"
1446 "C-a h print this help\n"
1447 "C-a x exit emulator\n"
1448 "C-a s save disk data back to file (if -snapshot)\n"
1449 "C-a b send break (magic sysrq)\n"
1450 "C-a t toggle console timestamps\n"
1451 "C-a c switch between console and monitor\n"
1452 "C-a C-a send C-a\n"
1456 /* called when a char is received */
1457 static void stdio_received_byte(int ch)
1459 if (term_got_escape) {
1460 term_got_escape = 0;
1461 switch(ch) {
1462 case 'h':
1463 term_print_help();
1464 break;
1465 case 'x':
1466 exit(0);
1467 break;
1468 case 's':
1470 int i;
1471 for (i = 0; i < MAX_DISKS; i++) {
1472 if (bs_table[i])
1473 bdrv_commit(bs_table[i]);
1476 break;
1477 case 'b':
1478 if (client_index < stdio_nb_clients) {
1479 CharDriverState *chr;
1480 FDCharDriver *s;
1482 chr = stdio_clients[client_index];
1483 s = chr->opaque;
1484 qemu_chr_event(chr, CHR_EVENT_BREAK);
1486 break;
1487 case 'c':
1488 client_index++;
1489 if (client_index >= stdio_nb_clients)
1490 client_index = 0;
1491 if (client_index == 0) {
1492 /* send a new line in the monitor to get the prompt */
1493 ch = '\r';
1494 goto send_char;
1496 break;
1497 case 't':
1498 term_timestamps = !term_timestamps;
1499 term_timestamps_start = -1;
1500 break;
1501 case TERM_ESCAPE:
1502 goto send_char;
1504 } else if (ch == TERM_ESCAPE) {
1505 term_got_escape = 1;
1506 } else {
1507 send_char:
1508 if (client_index < stdio_nb_clients) {
1509 uint8_t buf[1];
1510 CharDriverState *chr;
1512 chr = stdio_clients[client_index];
1513 if (qemu_chr_can_read(chr) > 0) {
1514 buf[0] = ch;
1515 qemu_chr_read(chr, buf, 1);
1516 } else if (term_fifo_size == 0) {
1517 term_fifo[term_fifo_size++] = ch;
1523 static int stdio_read_poll(void *opaque)
1525 CharDriverState *chr;
1527 if (client_index < stdio_nb_clients) {
1528 chr = stdio_clients[client_index];
1529 /* try to flush the queue if needed */
1530 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1531 qemu_chr_read(chr, term_fifo, 1);
1532 term_fifo_size = 0;
1534 /* see if we can absorb more chars */
1535 if (term_fifo_size == 0)
1536 return 1;
1537 else
1538 return 0;
1539 } else {
1540 return 1;
1544 static void stdio_read(void *opaque)
1546 int size;
1547 uint8_t buf[1];
1549 size = read(0, buf, 1);
1550 if (size == 0) {
1551 /* stdin has been closed. Remove it from the active list. */
1552 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1553 return;
1555 if (size > 0)
1556 stdio_received_byte(buf[0]);
1559 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1561 FDCharDriver *s = chr->opaque;
1562 if (!term_timestamps) {
1563 return unix_write(s->fd_out, buf, len);
1564 } else {
1565 int i;
1566 char buf1[64];
1568 for(i = 0; i < len; i++) {
1569 unix_write(s->fd_out, buf + i, 1);
1570 if (buf[i] == '\n') {
1571 int64_t ti;
1572 int secs;
1574 ti = get_clock();
1575 if (term_timestamps_start == -1)
1576 term_timestamps_start = ti;
1577 ti -= term_timestamps_start;
1578 secs = ti / 1000000000;
1579 snprintf(buf1, sizeof(buf1),
1580 "[%02d:%02d:%02d.%03d] ",
1581 secs / 3600,
1582 (secs / 60) % 60,
1583 secs % 60,
1584 (int)((ti / 1000000) % 1000));
1585 unix_write(s->fd_out, buf1, strlen(buf1));
1588 return len;
1592 /* init terminal so that we can grab keys */
1593 static struct termios oldtty;
1594 static int old_fd0_flags;
1596 static void term_exit(void)
1598 tcsetattr (0, TCSANOW, &oldtty);
1599 fcntl(0, F_SETFL, old_fd0_flags);
1602 static void term_init(void)
1604 struct termios tty;
1606 tcgetattr (0, &tty);
1607 oldtty = tty;
1608 old_fd0_flags = fcntl(0, F_GETFL);
1610 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1611 |INLCR|IGNCR|ICRNL|IXON);
1612 tty.c_oflag |= OPOST;
1613 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1614 /* if graphical mode, we allow Ctrl-C handling */
1615 if (nographic)
1616 tty.c_lflag &= ~ISIG;
1617 tty.c_cflag &= ~(CSIZE|PARENB);
1618 tty.c_cflag |= CS8;
1619 tty.c_cc[VMIN] = 1;
1620 tty.c_cc[VTIME] = 0;
1622 tcsetattr (0, TCSANOW, &tty);
1624 atexit(term_exit);
1626 fcntl(0, F_SETFL, O_NONBLOCK);
1629 static CharDriverState *qemu_chr_open_stdio(void)
1631 CharDriverState *chr;
1633 if (nographic) {
1634 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1635 return NULL;
1636 chr = qemu_chr_open_fd(0, 1);
1637 chr->chr_write = stdio_write;
1638 if (stdio_nb_clients == 0)
1639 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1640 client_index = stdio_nb_clients;
1641 } else {
1642 if (stdio_nb_clients != 0)
1643 return NULL;
1644 chr = qemu_chr_open_fd(0, 1);
1646 stdio_clients[stdio_nb_clients++] = chr;
1647 if (stdio_nb_clients == 1) {
1648 /* set the terminal in raw mode */
1649 term_init();
1651 return chr;
1654 #if defined(__linux__)
1655 static CharDriverState *qemu_chr_open_pty(void)
1657 struct termios tty;
1658 char slave_name[1024];
1659 int master_fd, slave_fd;
1661 /* Not satisfying */
1662 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1663 return NULL;
1666 /* Disabling local echo and line-buffered output */
1667 tcgetattr (master_fd, &tty);
1668 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1669 tty.c_cc[VMIN] = 1;
1670 tty.c_cc[VTIME] = 0;
1671 tcsetattr (master_fd, TCSAFLUSH, &tty);
1673 fprintf(stderr, "char device redirected to %s\n", slave_name);
1674 return qemu_chr_open_fd(master_fd, master_fd);
1677 static void tty_serial_init(int fd, int speed,
1678 int parity, int data_bits, int stop_bits)
1680 struct termios tty;
1681 speed_t spd;
1683 #if 0
1684 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1685 speed, parity, data_bits, stop_bits);
1686 #endif
1687 tcgetattr (fd, &tty);
1689 switch(speed) {
1690 case 50:
1691 spd = B50;
1692 break;
1693 case 75:
1694 spd = B75;
1695 break;
1696 case 300:
1697 spd = B300;
1698 break;
1699 case 600:
1700 spd = B600;
1701 break;
1702 case 1200:
1703 spd = B1200;
1704 break;
1705 case 2400:
1706 spd = B2400;
1707 break;
1708 case 4800:
1709 spd = B4800;
1710 break;
1711 case 9600:
1712 spd = B9600;
1713 break;
1714 case 19200:
1715 spd = B19200;
1716 break;
1717 case 38400:
1718 spd = B38400;
1719 break;
1720 case 57600:
1721 spd = B57600;
1722 break;
1723 default:
1724 case 115200:
1725 spd = B115200;
1726 break;
1729 cfsetispeed(&tty, spd);
1730 cfsetospeed(&tty, spd);
1732 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1733 |INLCR|IGNCR|ICRNL|IXON);
1734 tty.c_oflag |= OPOST;
1735 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1736 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1737 switch(data_bits) {
1738 default:
1739 case 8:
1740 tty.c_cflag |= CS8;
1741 break;
1742 case 7:
1743 tty.c_cflag |= CS7;
1744 break;
1745 case 6:
1746 tty.c_cflag |= CS6;
1747 break;
1748 case 5:
1749 tty.c_cflag |= CS5;
1750 break;
1752 switch(parity) {
1753 default:
1754 case 'N':
1755 break;
1756 case 'E':
1757 tty.c_cflag |= PARENB;
1758 break;
1759 case 'O':
1760 tty.c_cflag |= PARENB | PARODD;
1761 break;
1763 if (stop_bits == 2)
1764 tty.c_cflag |= CSTOPB;
1766 tcsetattr (fd, TCSANOW, &tty);
1769 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1771 FDCharDriver *s = chr->opaque;
1773 switch(cmd) {
1774 case CHR_IOCTL_SERIAL_SET_PARAMS:
1776 QEMUSerialSetParams *ssp = arg;
1777 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1778 ssp->data_bits, ssp->stop_bits);
1780 break;
1781 case CHR_IOCTL_SERIAL_SET_BREAK:
1783 int enable = *(int *)arg;
1784 if (enable)
1785 tcsendbreak(s->fd_in, 1);
1787 break;
1788 default:
1789 return -ENOTSUP;
1791 return 0;
1794 static CharDriverState *qemu_chr_open_tty(const char *filename)
1796 CharDriverState *chr;
1797 int fd;
1799 fd = open(filename, O_RDWR | O_NONBLOCK);
1800 if (fd < 0)
1801 return NULL;
1802 fcntl(fd, F_SETFL, O_NONBLOCK);
1803 tty_serial_init(fd, 115200, 'N', 8, 1);
1804 chr = qemu_chr_open_fd(fd, fd);
1805 if (!chr)
1806 return NULL;
1807 chr->chr_ioctl = tty_serial_ioctl;
1808 qemu_chr_reset(chr);
1809 return chr;
1812 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1814 int fd = (int)chr->opaque;
1815 uint8_t b;
1817 switch(cmd) {
1818 case CHR_IOCTL_PP_READ_DATA:
1819 if (ioctl(fd, PPRDATA, &b) < 0)
1820 return -ENOTSUP;
1821 *(uint8_t *)arg = b;
1822 break;
1823 case CHR_IOCTL_PP_WRITE_DATA:
1824 b = *(uint8_t *)arg;
1825 if (ioctl(fd, PPWDATA, &b) < 0)
1826 return -ENOTSUP;
1827 break;
1828 case CHR_IOCTL_PP_READ_CONTROL:
1829 if (ioctl(fd, PPRCONTROL, &b) < 0)
1830 return -ENOTSUP;
1831 *(uint8_t *)arg = b;
1832 break;
1833 case CHR_IOCTL_PP_WRITE_CONTROL:
1834 b = *(uint8_t *)arg;
1835 if (ioctl(fd, PPWCONTROL, &b) < 0)
1836 return -ENOTSUP;
1837 break;
1838 case CHR_IOCTL_PP_READ_STATUS:
1839 if (ioctl(fd, PPRSTATUS, &b) < 0)
1840 return -ENOTSUP;
1841 *(uint8_t *)arg = b;
1842 break;
1843 default:
1844 return -ENOTSUP;
1846 return 0;
1849 static CharDriverState *qemu_chr_open_pp(const char *filename)
1851 CharDriverState *chr;
1852 int fd;
1854 fd = open(filename, O_RDWR);
1855 if (fd < 0)
1856 return NULL;
1858 if (ioctl(fd, PPCLAIM) < 0) {
1859 close(fd);
1860 return NULL;
1863 chr = qemu_mallocz(sizeof(CharDriverState));
1864 if (!chr) {
1865 close(fd);
1866 return NULL;
1868 chr->opaque = (void *)fd;
1869 chr->chr_write = null_chr_write;
1870 chr->chr_ioctl = pp_ioctl;
1872 qemu_chr_reset(chr);
1874 return chr;
1877 #else
1878 static CharDriverState *qemu_chr_open_pty(void)
1880 return NULL;
1882 #endif
1884 #endif /* !defined(_WIN32) */
1886 #ifdef _WIN32
1887 typedef struct {
1888 CharDriverState *chr;
1889 int max_size;
1890 HANDLE hcom, hrecv, hsend;
1891 OVERLAPPED orecv, osend;
1892 BOOL fpipe;
1893 DWORD len;
1894 } WinCharState;
1896 #define NSENDBUF 2048
1897 #define NRECVBUF 2048
1898 #define MAXCONNECT 1
1899 #define NTIMEOUT 5000
1901 static int win_chr_poll(void *opaque);
1902 static int win_chr_pipe_poll(void *opaque);
1904 static void win_chr_close2(WinCharState *s)
1906 if (s->hsend) {
1907 CloseHandle(s->hsend);
1908 s->hsend = NULL;
1910 if (s->hrecv) {
1911 CloseHandle(s->hrecv);
1912 s->hrecv = NULL;
1914 if (s->hcom) {
1915 CloseHandle(s->hcom);
1916 s->hcom = NULL;
1918 if (s->fpipe)
1919 qemu_del_polling_cb(win_chr_pipe_poll, s);
1920 else
1921 qemu_del_polling_cb(win_chr_poll, s);
1924 static void win_chr_close(CharDriverState *chr)
1926 WinCharState *s = chr->opaque;
1927 win_chr_close2(s);
1930 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
1932 COMMCONFIG comcfg;
1933 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1934 COMSTAT comstat;
1935 DWORD size;
1936 DWORD err;
1938 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1939 if (!s->hsend) {
1940 fprintf(stderr, "Failed CreateEvent\n");
1941 goto fail;
1943 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1944 if (!s->hrecv) {
1945 fprintf(stderr, "Failed CreateEvent\n");
1946 goto fail;
1949 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1950 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1951 if (s->hcom == INVALID_HANDLE_VALUE) {
1952 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1953 s->hcom = NULL;
1954 goto fail;
1957 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1958 fprintf(stderr, "Failed SetupComm\n");
1959 goto fail;
1962 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1963 size = sizeof(COMMCONFIG);
1964 GetDefaultCommConfig(filename, &comcfg, &size);
1965 comcfg.dcb.DCBlength = sizeof(DCB);
1966 CommConfigDialog(filename, NULL, &comcfg);
1968 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1969 fprintf(stderr, "Failed SetCommState\n");
1970 goto fail;
1973 if (!SetCommMask(s->hcom, EV_ERR)) {
1974 fprintf(stderr, "Failed SetCommMask\n");
1975 goto fail;
1978 cto.ReadIntervalTimeout = MAXDWORD;
1979 if (!SetCommTimeouts(s->hcom, &cto)) {
1980 fprintf(stderr, "Failed SetCommTimeouts\n");
1981 goto fail;
1984 if (!ClearCommError(s->hcom, &err, &comstat)) {
1985 fprintf(stderr, "Failed ClearCommError\n");
1986 goto fail;
1988 s->chr = chr;
1989 qemu_add_polling_cb(win_chr_poll, s);
1990 return 0;
1992 fail:
1993 win_chr_close2(s);
1994 return -1;
1997 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1999 WinCharState *s = chr->opaque;
2000 DWORD len, ret, size, err;
2002 len = len1;
2003 ZeroMemory(&s->osend, sizeof(s->osend));
2004 s->osend.hEvent = s->hsend;
2005 while (len > 0) {
2006 if (s->hsend)
2007 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2008 else
2009 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2010 if (!ret) {
2011 err = GetLastError();
2012 if (err == ERROR_IO_PENDING) {
2013 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2014 if (ret) {
2015 buf += size;
2016 len -= size;
2017 } else {
2018 break;
2020 } else {
2021 break;
2023 } else {
2024 buf += size;
2025 len -= size;
2028 return len1 - len;
2031 static int win_chr_read_poll(WinCharState *s)
2033 s->max_size = qemu_chr_can_read(s->chr);
2034 return s->max_size;
2037 static void win_chr_readfile(WinCharState *s)
2039 int ret, err;
2040 uint8_t buf[1024];
2041 DWORD size;
2043 ZeroMemory(&s->orecv, sizeof(s->orecv));
2044 s->orecv.hEvent = s->hrecv;
2045 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2046 if (!ret) {
2047 err = GetLastError();
2048 if (err == ERROR_IO_PENDING) {
2049 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2053 if (size > 0) {
2054 qemu_chr_read(s->chr, buf, size);
2058 static void win_chr_read(WinCharState *s)
2060 if (s->len > s->max_size)
2061 s->len = s->max_size;
2062 if (s->len == 0)
2063 return;
2065 win_chr_readfile(s);
2068 static int win_chr_poll(void *opaque)
2070 WinCharState *s = opaque;
2071 COMSTAT status;
2072 DWORD comerr;
2074 ClearCommError(s->hcom, &comerr, &status);
2075 if (status.cbInQue > 0) {
2076 s->len = status.cbInQue;
2077 win_chr_read_poll(s);
2078 win_chr_read(s);
2079 return 1;
2081 return 0;
2084 static CharDriverState *qemu_chr_open_win(const char *filename)
2086 CharDriverState *chr;
2087 WinCharState *s;
2089 chr = qemu_mallocz(sizeof(CharDriverState));
2090 if (!chr)
2091 return NULL;
2092 s = qemu_mallocz(sizeof(WinCharState));
2093 if (!s) {
2094 free(chr);
2095 return NULL;
2097 chr->opaque = s;
2098 chr->chr_write = win_chr_write;
2099 chr->chr_close = win_chr_close;
2101 if (win_chr_init(s, chr, filename) < 0) {
2102 free(s);
2103 free(chr);
2104 return NULL;
2106 qemu_chr_reset(chr);
2107 return chr;
2110 static int win_chr_pipe_poll(void *opaque)
2112 WinCharState *s = opaque;
2113 DWORD size;
2115 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2116 if (size > 0) {
2117 s->len = size;
2118 win_chr_read_poll(s);
2119 win_chr_read(s);
2120 return 1;
2122 return 0;
2125 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2127 OVERLAPPED ov;
2128 int ret;
2129 DWORD size;
2130 char openname[256];
2132 s->fpipe = TRUE;
2134 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2135 if (!s->hsend) {
2136 fprintf(stderr, "Failed CreateEvent\n");
2137 goto fail;
2139 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2140 if (!s->hrecv) {
2141 fprintf(stderr, "Failed CreateEvent\n");
2142 goto fail;
2145 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2146 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2147 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2148 PIPE_WAIT,
2149 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2150 if (s->hcom == INVALID_HANDLE_VALUE) {
2151 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2152 s->hcom = NULL;
2153 goto fail;
2156 ZeroMemory(&ov, sizeof(ov));
2157 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2158 ret = ConnectNamedPipe(s->hcom, &ov);
2159 if (ret) {
2160 fprintf(stderr, "Failed ConnectNamedPipe\n");
2161 goto fail;
2164 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2165 if (!ret) {
2166 fprintf(stderr, "Failed GetOverlappedResult\n");
2167 if (ov.hEvent) {
2168 CloseHandle(ov.hEvent);
2169 ov.hEvent = NULL;
2171 goto fail;
2174 if (ov.hEvent) {
2175 CloseHandle(ov.hEvent);
2176 ov.hEvent = NULL;
2178 qemu_add_polling_cb(win_chr_pipe_poll, s);
2179 return 0;
2181 fail:
2182 win_chr_close2(s);
2183 return -1;
2187 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2189 CharDriverState *chr;
2190 WinCharState *s;
2192 chr = qemu_mallocz(sizeof(CharDriverState));
2193 if (!chr)
2194 return NULL;
2195 s = qemu_mallocz(sizeof(WinCharState));
2196 if (!s) {
2197 free(chr);
2198 return NULL;
2200 chr->opaque = s;
2201 chr->chr_write = win_chr_write;
2202 chr->chr_close = win_chr_close;
2204 if (win_chr_pipe_init(s, filename) < 0) {
2205 free(s);
2206 free(chr);
2207 return NULL;
2209 qemu_chr_reset(chr);
2210 return chr;
2213 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2215 CharDriverState *chr;
2216 WinCharState *s;
2218 chr = qemu_mallocz(sizeof(CharDriverState));
2219 if (!chr)
2220 return NULL;
2221 s = qemu_mallocz(sizeof(WinCharState));
2222 if (!s) {
2223 free(chr);
2224 return NULL;
2226 s->hcom = fd_out;
2227 chr->opaque = s;
2228 chr->chr_write = win_chr_write;
2229 qemu_chr_reset(chr);
2230 return chr;
2233 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2235 HANDLE fd_out;
2237 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2238 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2239 if (fd_out == INVALID_HANDLE_VALUE)
2240 return NULL;
2242 return qemu_chr_open_win_file(fd_out);
2244 #endif
2246 /***********************************************************/
2247 /* UDP Net console */
2249 typedef struct {
2250 int fd;
2251 struct sockaddr_in daddr;
2252 char buf[1024];
2253 int bufcnt;
2254 int bufptr;
2255 int max_size;
2256 } NetCharDriver;
2258 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2260 NetCharDriver *s = chr->opaque;
2262 return sendto(s->fd, buf, len, 0,
2263 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2266 static int udp_chr_read_poll(void *opaque)
2268 CharDriverState *chr = opaque;
2269 NetCharDriver *s = chr->opaque;
2271 s->max_size = qemu_chr_can_read(chr);
2273 /* If there were any stray characters in the queue process them
2274 * first
2276 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2277 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2278 s->bufptr++;
2279 s->max_size = qemu_chr_can_read(chr);
2281 return s->max_size;
2284 static void udp_chr_read(void *opaque)
2286 CharDriverState *chr = opaque;
2287 NetCharDriver *s = chr->opaque;
2289 if (s->max_size == 0)
2290 return;
2291 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2292 s->bufptr = s->bufcnt;
2293 if (s->bufcnt <= 0)
2294 return;
2296 s->bufptr = 0;
2297 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2298 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2299 s->bufptr++;
2300 s->max_size = qemu_chr_can_read(chr);
2304 static void udp_chr_update_read_handler(CharDriverState *chr)
2306 NetCharDriver *s = chr->opaque;
2308 if (s->fd >= 0) {
2309 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2310 udp_chr_read, NULL, chr);
2314 #ifndef _WIN32
2315 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2316 #endif
2317 int parse_host_src_port(struct sockaddr_in *haddr,
2318 struct sockaddr_in *saddr,
2319 const char *str);
2321 static CharDriverState *qemu_chr_open_udp(const char *def)
2323 CharDriverState *chr = NULL;
2324 NetCharDriver *s = NULL;
2325 int fd = -1;
2326 struct sockaddr_in saddr;
2328 chr = qemu_mallocz(sizeof(CharDriverState));
2329 if (!chr)
2330 goto return_err;
2331 s = qemu_mallocz(sizeof(NetCharDriver));
2332 if (!s)
2333 goto return_err;
2335 fd = socket(PF_INET, SOCK_DGRAM, 0);
2336 if (fd < 0) {
2337 perror("socket(PF_INET, SOCK_DGRAM)");
2338 goto return_err;
2341 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2342 printf("Could not parse: %s\n", def);
2343 goto return_err;
2346 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2348 perror("bind");
2349 goto return_err;
2352 s->fd = fd;
2353 s->bufcnt = 0;
2354 s->bufptr = 0;
2355 chr->opaque = s;
2356 chr->chr_write = udp_chr_write;
2357 chr->chr_update_read_handler = udp_chr_update_read_handler;
2358 return chr;
2360 return_err:
2361 if (chr)
2362 free(chr);
2363 if (s)
2364 free(s);
2365 if (fd >= 0)
2366 closesocket(fd);
2367 return NULL;
2370 /***********************************************************/
2371 /* TCP Net console */
2373 typedef struct {
2374 int fd, listen_fd;
2375 int connected;
2376 int max_size;
2377 int do_telnetopt;
2378 int do_nodelay;
2379 int is_unix;
2380 } TCPCharDriver;
2382 static void tcp_chr_accept(void *opaque);
2384 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2386 TCPCharDriver *s = chr->opaque;
2387 if (s->connected) {
2388 return send_all(s->fd, buf, len);
2389 } else {
2390 /* XXX: indicate an error ? */
2391 return len;
2395 static int tcp_chr_read_poll(void *opaque)
2397 CharDriverState *chr = opaque;
2398 TCPCharDriver *s = chr->opaque;
2399 if (!s->connected)
2400 return 0;
2401 s->max_size = qemu_chr_can_read(chr);
2402 return s->max_size;
2405 #define IAC 255
2406 #define IAC_BREAK 243
2407 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2408 TCPCharDriver *s,
2409 char *buf, int *size)
2411 /* Handle any telnet client's basic IAC options to satisfy char by
2412 * char mode with no echo. All IAC options will be removed from
2413 * the buf and the do_telnetopt variable will be used to track the
2414 * state of the width of the IAC information.
2416 * IAC commands come in sets of 3 bytes with the exception of the
2417 * "IAC BREAK" command and the double IAC.
2420 int i;
2421 int j = 0;
2423 for (i = 0; i < *size; i++) {
2424 if (s->do_telnetopt > 1) {
2425 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2426 /* Double IAC means send an IAC */
2427 if (j != i)
2428 buf[j] = buf[i];
2429 j++;
2430 s->do_telnetopt = 1;
2431 } else {
2432 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2433 /* Handle IAC break commands by sending a serial break */
2434 qemu_chr_event(chr, CHR_EVENT_BREAK);
2435 s->do_telnetopt++;
2437 s->do_telnetopt++;
2439 if (s->do_telnetopt >= 4) {
2440 s->do_telnetopt = 1;
2442 } else {
2443 if ((unsigned char)buf[i] == IAC) {
2444 s->do_telnetopt = 2;
2445 } else {
2446 if (j != i)
2447 buf[j] = buf[i];
2448 j++;
2452 *size = j;
2455 static void tcp_chr_read(void *opaque)
2457 CharDriverState *chr = opaque;
2458 TCPCharDriver *s = chr->opaque;
2459 uint8_t buf[1024];
2460 int len, size;
2462 if (!s->connected || s->max_size <= 0)
2463 return;
2464 len = sizeof(buf);
2465 if (len > s->max_size)
2466 len = s->max_size;
2467 size = recv(s->fd, buf, len, 0);
2468 if (size == 0) {
2469 /* connection closed */
2470 s->connected = 0;
2471 if (s->listen_fd >= 0) {
2472 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2474 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2475 closesocket(s->fd);
2476 s->fd = -1;
2477 } else if (size > 0) {
2478 if (s->do_telnetopt)
2479 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2480 if (size > 0)
2481 qemu_chr_read(chr, buf, size);
2485 static void tcp_chr_connect(void *opaque)
2487 CharDriverState *chr = opaque;
2488 TCPCharDriver *s = chr->opaque;
2490 s->connected = 1;
2491 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2492 tcp_chr_read, NULL, chr);
2493 qemu_chr_reset(chr);
2496 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2497 static void tcp_chr_telnet_init(int fd)
2499 char buf[3];
2500 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2501 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2502 send(fd, (char *)buf, 3, 0);
2503 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2504 send(fd, (char *)buf, 3, 0);
2505 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2506 send(fd, (char *)buf, 3, 0);
2507 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2508 send(fd, (char *)buf, 3, 0);
2511 static void socket_set_nodelay(int fd)
2513 int val = 1;
2514 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2517 static void tcp_chr_accept(void *opaque)
2519 CharDriverState *chr = opaque;
2520 TCPCharDriver *s = chr->opaque;
2521 struct sockaddr_in saddr;
2522 #ifndef _WIN32
2523 struct sockaddr_un uaddr;
2524 #endif
2525 struct sockaddr *addr;
2526 socklen_t len;
2527 int fd;
2529 for(;;) {
2530 #ifndef _WIN32
2531 if (s->is_unix) {
2532 len = sizeof(uaddr);
2533 addr = (struct sockaddr *)&uaddr;
2534 } else
2535 #endif
2537 len = sizeof(saddr);
2538 addr = (struct sockaddr *)&saddr;
2540 fd = accept(s->listen_fd, addr, &len);
2541 if (fd < 0 && errno != EINTR) {
2542 return;
2543 } else if (fd >= 0) {
2544 if (s->do_telnetopt)
2545 tcp_chr_telnet_init(fd);
2546 break;
2549 socket_set_nonblock(fd);
2550 if (s->do_nodelay)
2551 socket_set_nodelay(fd);
2552 s->fd = fd;
2553 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2554 tcp_chr_connect(chr);
2557 static void tcp_chr_close(CharDriverState *chr)
2559 TCPCharDriver *s = chr->opaque;
2560 if (s->fd >= 0)
2561 closesocket(s->fd);
2562 if (s->listen_fd >= 0)
2563 closesocket(s->listen_fd);
2564 qemu_free(s);
2567 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2568 int is_telnet,
2569 int is_unix)
2571 CharDriverState *chr = NULL;
2572 TCPCharDriver *s = NULL;
2573 int fd = -1, ret, err, val;
2574 int is_listen = 0;
2575 int is_waitconnect = 1;
2576 int do_nodelay = 0;
2577 const char *ptr;
2578 struct sockaddr_in saddr;
2579 #ifndef _WIN32
2580 struct sockaddr_un uaddr;
2581 #endif
2582 struct sockaddr *addr;
2583 socklen_t addrlen;
2585 #ifndef _WIN32
2586 if (is_unix) {
2587 addr = (struct sockaddr *)&uaddr;
2588 addrlen = sizeof(uaddr);
2589 if (parse_unix_path(&uaddr, host_str) < 0)
2590 goto fail;
2591 } else
2592 #endif
2594 addr = (struct sockaddr *)&saddr;
2595 addrlen = sizeof(saddr);
2596 if (parse_host_port(&saddr, host_str) < 0)
2597 goto fail;
2600 ptr = host_str;
2601 while((ptr = strchr(ptr,','))) {
2602 ptr++;
2603 if (!strncmp(ptr,"server",6)) {
2604 is_listen = 1;
2605 } else if (!strncmp(ptr,"nowait",6)) {
2606 is_waitconnect = 0;
2607 } else if (!strncmp(ptr,"nodelay",6)) {
2608 do_nodelay = 1;
2609 } else {
2610 printf("Unknown option: %s\n", ptr);
2611 goto fail;
2614 if (!is_listen)
2615 is_waitconnect = 0;
2617 chr = qemu_mallocz(sizeof(CharDriverState));
2618 if (!chr)
2619 goto fail;
2620 s = qemu_mallocz(sizeof(TCPCharDriver));
2621 if (!s)
2622 goto fail;
2624 #ifndef _WIN32
2625 if (is_unix)
2626 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2627 else
2628 #endif
2629 fd = socket(PF_INET, SOCK_STREAM, 0);
2631 if (fd < 0)
2632 goto fail;
2634 if (!is_waitconnect)
2635 socket_set_nonblock(fd);
2637 s->connected = 0;
2638 s->fd = -1;
2639 s->listen_fd = -1;
2640 s->is_unix = is_unix;
2641 s->do_nodelay = do_nodelay && !is_unix;
2643 chr->opaque = s;
2644 chr->chr_write = tcp_chr_write;
2645 chr->chr_close = tcp_chr_close;
2647 if (is_listen) {
2648 /* allow fast reuse */
2649 #ifndef _WIN32
2650 if (is_unix) {
2651 char path[109];
2652 strncpy(path, uaddr.sun_path, 108);
2653 path[108] = 0;
2654 unlink(path);
2655 } else
2656 #endif
2658 val = 1;
2659 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2662 ret = bind(fd, addr, addrlen);
2663 if (ret < 0)
2664 goto fail;
2666 ret = listen(fd, 0);
2667 if (ret < 0)
2668 goto fail;
2670 s->listen_fd = fd;
2671 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2672 if (is_telnet)
2673 s->do_telnetopt = 1;
2674 } else {
2675 for(;;) {
2676 ret = connect(fd, addr, addrlen);
2677 if (ret < 0) {
2678 err = socket_error();
2679 if (err == EINTR || err == EWOULDBLOCK) {
2680 } else if (err == EINPROGRESS) {
2681 break;
2682 } else {
2683 goto fail;
2685 } else {
2686 s->connected = 1;
2687 break;
2690 s->fd = fd;
2691 socket_set_nodelay(fd);
2692 if (s->connected)
2693 tcp_chr_connect(chr);
2694 else
2695 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2698 if (is_listen && is_waitconnect) {
2699 printf("QEMU waiting for connection on: %s\n", host_str);
2700 tcp_chr_accept(chr);
2701 socket_set_nonblock(s->listen_fd);
2704 return chr;
2705 fail:
2706 if (fd >= 0)
2707 closesocket(fd);
2708 qemu_free(s);
2709 qemu_free(chr);
2710 return NULL;
2713 CharDriverState *qemu_chr_open(const char *filename)
2715 const char *p;
2717 if (!strcmp(filename, "vc")) {
2718 return text_console_init(&display_state);
2719 } else if (!strcmp(filename, "null")) {
2720 return qemu_chr_open_null();
2721 } else
2722 if (strstart(filename, "tcp:", &p)) {
2723 return qemu_chr_open_tcp(p, 0, 0);
2724 } else
2725 if (strstart(filename, "telnet:", &p)) {
2726 return qemu_chr_open_tcp(p, 1, 0);
2727 } else
2728 if (strstart(filename, "udp:", &p)) {
2729 return qemu_chr_open_udp(p);
2730 } else
2731 #ifndef _WIN32
2732 if (strstart(filename, "unix:", &p)) {
2733 return qemu_chr_open_tcp(p, 0, 1);
2734 } else if (strstart(filename, "file:", &p)) {
2735 return qemu_chr_open_file_out(p);
2736 } else if (strstart(filename, "pipe:", &p)) {
2737 return qemu_chr_open_pipe(p);
2738 } else if (!strcmp(filename, "pty")) {
2739 return qemu_chr_open_pty();
2740 } else if (!strcmp(filename, "stdio")) {
2741 return qemu_chr_open_stdio();
2742 } else
2743 #endif
2744 #if defined(__linux__)
2745 if (strstart(filename, "/dev/parport", NULL)) {
2746 return qemu_chr_open_pp(filename);
2747 } else
2748 if (strstart(filename, "/dev/", NULL)) {
2749 return qemu_chr_open_tty(filename);
2750 } else
2751 #endif
2752 #ifdef _WIN32
2753 if (strstart(filename, "COM", NULL)) {
2754 return qemu_chr_open_win(filename);
2755 } else
2756 if (strstart(filename, "pipe:", &p)) {
2757 return qemu_chr_open_win_pipe(p);
2758 } else
2759 if (strstart(filename, "file:", &p)) {
2760 return qemu_chr_open_win_file_out(p);
2762 #endif
2764 return NULL;
2768 void qemu_chr_close(CharDriverState *chr)
2770 if (chr->chr_close)
2771 chr->chr_close(chr);
2774 /***********************************************************/
2775 /* network device redirectors */
2777 void hex_dump(FILE *f, const uint8_t *buf, int size)
2779 int len, i, j, c;
2781 for(i=0;i<size;i+=16) {
2782 len = size - i;
2783 if (len > 16)
2784 len = 16;
2785 fprintf(f, "%08x ", i);
2786 for(j=0;j<16;j++) {
2787 if (j < len)
2788 fprintf(f, " %02x", buf[i+j]);
2789 else
2790 fprintf(f, " ");
2792 fprintf(f, " ");
2793 for(j=0;j<len;j++) {
2794 c = buf[i+j];
2795 if (c < ' ' || c > '~')
2796 c = '.';
2797 fprintf(f, "%c", c);
2799 fprintf(f, "\n");
2803 static int parse_macaddr(uint8_t *macaddr, const char *p)
2805 int i;
2806 for(i = 0; i < 6; i++) {
2807 macaddr[i] = strtol(p, (char **)&p, 16);
2808 if (i == 5) {
2809 if (*p != '\0')
2810 return -1;
2811 } else {
2812 if (*p != ':')
2813 return -1;
2814 p++;
2817 return 0;
2820 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2822 const char *p, *p1;
2823 int len;
2824 p = *pp;
2825 p1 = strchr(p, sep);
2826 if (!p1)
2827 return -1;
2828 len = p1 - p;
2829 p1++;
2830 if (buf_size > 0) {
2831 if (len > buf_size - 1)
2832 len = buf_size - 1;
2833 memcpy(buf, p, len);
2834 buf[len] = '\0';
2836 *pp = p1;
2837 return 0;
2840 int parse_host_src_port(struct sockaddr_in *haddr,
2841 struct sockaddr_in *saddr,
2842 const char *input_str)
2844 char *str = strdup(input_str);
2845 char *host_str = str;
2846 char *src_str;
2847 char *ptr;
2850 * Chop off any extra arguments at the end of the string which
2851 * would start with a comma, then fill in the src port information
2852 * if it was provided else use the "any address" and "any port".
2854 if ((ptr = strchr(str,',')))
2855 *ptr = '\0';
2857 if ((src_str = strchr(input_str,'@'))) {
2858 *src_str = '\0';
2859 src_str++;
2862 if (parse_host_port(haddr, host_str) < 0)
2863 goto fail;
2865 if (!src_str || *src_str == '\0')
2866 src_str = ":0";
2868 if (parse_host_port(saddr, src_str) < 0)
2869 goto fail;
2871 free(str);
2872 return(0);
2874 fail:
2875 free(str);
2876 return -1;
2879 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2881 char buf[512];
2882 struct hostent *he;
2883 const char *p, *r;
2884 int port;
2886 p = str;
2887 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2888 return -1;
2889 saddr->sin_family = AF_INET;
2890 if (buf[0] == '\0') {
2891 saddr->sin_addr.s_addr = 0;
2892 } else {
2893 if (isdigit(buf[0])) {
2894 if (!inet_aton(buf, &saddr->sin_addr))
2895 return -1;
2896 } else {
2897 if ((he = gethostbyname(buf)) == NULL)
2898 return - 1;
2899 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2902 port = strtol(p, (char **)&r, 0);
2903 if (r == p)
2904 return -1;
2905 saddr->sin_port = htons(port);
2906 return 0;
2909 #ifndef _WIN32
2910 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2912 const char *p;
2913 int len;
2915 len = MIN(108, strlen(str));
2916 p = strchr(str, ',');
2917 if (p)
2918 len = MIN(len, p - str);
2920 memset(uaddr, 0, sizeof(*uaddr));
2922 uaddr->sun_family = AF_UNIX;
2923 memcpy(uaddr->sun_path, str, len);
2925 return 0;
2927 #endif
2929 /* find or alloc a new VLAN */
2930 VLANState *qemu_find_vlan(int id)
2932 VLANState **pvlan, *vlan;
2933 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2934 if (vlan->id == id)
2935 return vlan;
2937 vlan = qemu_mallocz(sizeof(VLANState));
2938 if (!vlan)
2939 return NULL;
2940 vlan->id = id;
2941 vlan->next = NULL;
2942 pvlan = &first_vlan;
2943 while (*pvlan != NULL)
2944 pvlan = &(*pvlan)->next;
2945 *pvlan = vlan;
2946 return vlan;
2949 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2950 IOReadHandler *fd_read,
2951 IOCanRWHandler *fd_can_read,
2952 void *opaque)
2954 VLANClientState *vc, **pvc;
2955 vc = qemu_mallocz(sizeof(VLANClientState));
2956 if (!vc)
2957 return NULL;
2958 vc->fd_read = fd_read;
2959 vc->fd_can_read = fd_can_read;
2960 vc->opaque = opaque;
2961 vc->vlan = vlan;
2963 vc->next = NULL;
2964 pvc = &vlan->first_client;
2965 while (*pvc != NULL)
2966 pvc = &(*pvc)->next;
2967 *pvc = vc;
2968 return vc;
2971 int qemu_can_send_packet(VLANClientState *vc1)
2973 VLANState *vlan = vc1->vlan;
2974 VLANClientState *vc;
2976 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2977 if (vc != vc1) {
2978 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2979 return 0;
2982 return 1;
2985 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2987 VLANState *vlan = vc1->vlan;
2988 VLANClientState *vc;
2990 #if 0
2991 printf("vlan %d send:\n", vlan->id);
2992 hex_dump(stdout, buf, size);
2993 #endif
2994 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2995 if (vc != vc1) {
2996 vc->fd_read(vc->opaque, buf, size);
3001 #if defined(CONFIG_SLIRP)
3003 /* slirp network adapter */
3005 static int slirp_inited;
3006 static VLANClientState *slirp_vc;
3008 int slirp_can_output(void)
3010 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3013 void slirp_output(const uint8_t *pkt, int pkt_len)
3015 #if 0
3016 printf("slirp output:\n");
3017 hex_dump(stdout, pkt, pkt_len);
3018 #endif
3019 if (!slirp_vc)
3020 return;
3021 qemu_send_packet(slirp_vc, pkt, pkt_len);
3024 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3026 #if 0
3027 printf("slirp input:\n");
3028 hex_dump(stdout, buf, size);
3029 #endif
3030 slirp_input(buf, size);
3033 static int net_slirp_init(VLANState *vlan)
3035 if (!slirp_inited) {
3036 slirp_inited = 1;
3037 slirp_init();
3039 slirp_vc = qemu_new_vlan_client(vlan,
3040 slirp_receive, NULL, NULL);
3041 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3042 return 0;
3045 static void net_slirp_redir(const char *redir_str)
3047 int is_udp;
3048 char buf[256], *r;
3049 const char *p;
3050 struct in_addr guest_addr;
3051 int host_port, guest_port;
3053 if (!slirp_inited) {
3054 slirp_inited = 1;
3055 slirp_init();
3058 p = redir_str;
3059 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3060 goto fail;
3061 if (!strcmp(buf, "tcp")) {
3062 is_udp = 0;
3063 } else if (!strcmp(buf, "udp")) {
3064 is_udp = 1;
3065 } else {
3066 goto fail;
3069 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3070 goto fail;
3071 host_port = strtol(buf, &r, 0);
3072 if (r == buf)
3073 goto fail;
3075 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3076 goto fail;
3077 if (buf[0] == '\0') {
3078 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3080 if (!inet_aton(buf, &guest_addr))
3081 goto fail;
3083 guest_port = strtol(p, &r, 0);
3084 if (r == p)
3085 goto fail;
3087 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3088 fprintf(stderr, "qemu: could not set up redirection\n");
3089 exit(1);
3091 return;
3092 fail:
3093 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3094 exit(1);
3097 #ifndef _WIN32
3099 char smb_dir[1024];
3101 static void smb_exit(void)
3103 DIR *d;
3104 struct dirent *de;
3105 char filename[1024];
3107 /* erase all the files in the directory */
3108 d = opendir(smb_dir);
3109 for(;;) {
3110 de = readdir(d);
3111 if (!de)
3112 break;
3113 if (strcmp(de->d_name, ".") != 0 &&
3114 strcmp(de->d_name, "..") != 0) {
3115 snprintf(filename, sizeof(filename), "%s/%s",
3116 smb_dir, de->d_name);
3117 unlink(filename);
3120 closedir(d);
3121 rmdir(smb_dir);
3124 /* automatic user mode samba server configuration */
3125 void net_slirp_smb(const char *exported_dir)
3127 char smb_conf[1024];
3128 char smb_cmdline[1024];
3129 FILE *f;
3131 if (!slirp_inited) {
3132 slirp_inited = 1;
3133 slirp_init();
3136 /* XXX: better tmp dir construction */
3137 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3138 if (mkdir(smb_dir, 0700) < 0) {
3139 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3140 exit(1);
3142 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3144 f = fopen(smb_conf, "w");
3145 if (!f) {
3146 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3147 exit(1);
3149 fprintf(f,
3150 "[global]\n"
3151 "private dir=%s\n"
3152 "smb ports=0\n"
3153 "socket address=127.0.0.1\n"
3154 "pid directory=%s\n"
3155 "lock directory=%s\n"
3156 "log file=%s/log.smbd\n"
3157 "smb passwd file=%s/smbpasswd\n"
3158 "security = share\n"
3159 "[qemu]\n"
3160 "path=%s\n"
3161 "read only=no\n"
3162 "guest ok=yes\n",
3163 smb_dir,
3164 smb_dir,
3165 smb_dir,
3166 smb_dir,
3167 smb_dir,
3168 exported_dir
3170 fclose(f);
3171 atexit(smb_exit);
3173 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3174 SMBD_COMMAND, smb_conf);
3176 slirp_add_exec(0, smb_cmdline, 4, 139);
3179 #endif /* !defined(_WIN32) */
3181 #endif /* CONFIG_SLIRP */
3183 #if !defined(_WIN32)
3185 typedef struct TAPState {
3186 VLANClientState *vc;
3187 int fd;
3188 } TAPState;
3190 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3192 TAPState *s = opaque;
3193 int ret;
3194 for(;;) {
3195 ret = write(s->fd, buf, size);
3196 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3197 } else {
3198 break;
3203 static void tap_send(void *opaque)
3205 TAPState *s = opaque;
3206 uint8_t buf[4096];
3207 int size;
3209 size = read(s->fd, buf, sizeof(buf));
3210 if (size > 0) {
3211 qemu_send_packet(s->vc, buf, size);
3215 /* fd support */
3217 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3219 TAPState *s;
3221 s = qemu_mallocz(sizeof(TAPState));
3222 if (!s)
3223 return NULL;
3224 s->fd = fd;
3225 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3226 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3227 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3228 return s;
3231 #ifdef _BSD
3232 static int tap_open(char *ifname, int ifname_size)
3234 int fd;
3235 char *dev;
3236 struct stat s;
3238 fd = open("/dev/tap", O_RDWR);
3239 if (fd < 0) {
3240 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3241 return -1;
3244 fstat(fd, &s);
3245 dev = devname(s.st_rdev, S_IFCHR);
3246 pstrcpy(ifname, ifname_size, dev);
3248 fcntl(fd, F_SETFL, O_NONBLOCK);
3249 return fd;
3251 #elif defined(__sun__)
3252 static int tap_open(char *ifname, int ifname_size)
3254 fprintf(stderr, "warning: tap_open not yet implemented\n");
3255 return -1;
3257 #else
3258 static int tap_open(char *ifname, int ifname_size)
3260 struct ifreq ifr;
3261 int fd, ret;
3263 fd = open("/dev/net/tun", O_RDWR);
3264 if (fd < 0) {
3265 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3266 return -1;
3268 memset(&ifr, 0, sizeof(ifr));
3269 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3270 if (ifname[0] != '\0')
3271 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3272 else
3273 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3274 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3275 if (ret != 0) {
3276 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3277 close(fd);
3278 return -1;
3280 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3281 fcntl(fd, F_SETFL, O_NONBLOCK);
3282 return fd;
3284 #endif
3286 static int net_tap_init(VLANState *vlan, const char *ifname1,
3287 const char *setup_script)
3289 TAPState *s;
3290 int pid, status, fd;
3291 char *args[3];
3292 char **parg;
3293 char ifname[128];
3295 if (ifname1 != NULL)
3296 pstrcpy(ifname, sizeof(ifname), ifname1);
3297 else
3298 ifname[0] = '\0';
3299 fd = tap_open(ifname, sizeof(ifname));
3300 if (fd < 0)
3301 return -1;
3303 if (!setup_script || !strcmp(setup_script, "no"))
3304 setup_script = "";
3305 if (setup_script[0] != '\0') {
3306 /* try to launch network init script */
3307 pid = fork();
3308 if (pid >= 0) {
3309 if (pid == 0) {
3310 parg = args;
3311 *parg++ = (char *)setup_script;
3312 *parg++ = ifname;
3313 *parg++ = NULL;
3314 execv(setup_script, args);
3315 _exit(1);
3317 while (waitpid(pid, &status, 0) != pid);
3318 if (!WIFEXITED(status) ||
3319 WEXITSTATUS(status) != 0) {
3320 fprintf(stderr, "%s: could not launch network script\n",
3321 setup_script);
3322 return -1;
3326 s = net_tap_fd_init(vlan, fd);
3327 if (!s)
3328 return -1;
3329 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3330 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3331 return 0;
3334 #endif /* !_WIN32 */
3336 /* network connection */
3337 typedef struct NetSocketState {
3338 VLANClientState *vc;
3339 int fd;
3340 int state; /* 0 = getting length, 1 = getting data */
3341 int index;
3342 int packet_len;
3343 uint8_t buf[4096];
3344 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3345 } NetSocketState;
3347 typedef struct NetSocketListenState {
3348 VLANState *vlan;
3349 int fd;
3350 } NetSocketListenState;
3352 /* XXX: we consider we can send the whole packet without blocking */
3353 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3355 NetSocketState *s = opaque;
3356 uint32_t len;
3357 len = htonl(size);
3359 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3360 send_all(s->fd, buf, size);
3363 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3365 NetSocketState *s = opaque;
3366 sendto(s->fd, buf, size, 0,
3367 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3370 static void net_socket_send(void *opaque)
3372 NetSocketState *s = opaque;
3373 int l, size, err;
3374 uint8_t buf1[4096];
3375 const uint8_t *buf;
3377 size = recv(s->fd, buf1, sizeof(buf1), 0);
3378 if (size < 0) {
3379 err = socket_error();
3380 if (err != EWOULDBLOCK)
3381 goto eoc;
3382 } else if (size == 0) {
3383 /* end of connection */
3384 eoc:
3385 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3386 closesocket(s->fd);
3387 return;
3389 buf = buf1;
3390 while (size > 0) {
3391 /* reassemble a packet from the network */
3392 switch(s->state) {
3393 case 0:
3394 l = 4 - s->index;
3395 if (l > size)
3396 l = size;
3397 memcpy(s->buf + s->index, buf, l);
3398 buf += l;
3399 size -= l;
3400 s->index += l;
3401 if (s->index == 4) {
3402 /* got length */
3403 s->packet_len = ntohl(*(uint32_t *)s->buf);
3404 s->index = 0;
3405 s->state = 1;
3407 break;
3408 case 1:
3409 l = s->packet_len - s->index;
3410 if (l > size)
3411 l = size;
3412 memcpy(s->buf + s->index, buf, l);
3413 s->index += l;
3414 buf += l;
3415 size -= l;
3416 if (s->index >= s->packet_len) {
3417 qemu_send_packet(s->vc, s->buf, s->packet_len);
3418 s->index = 0;
3419 s->state = 0;
3421 break;
3426 static void net_socket_send_dgram(void *opaque)
3428 NetSocketState *s = opaque;
3429 int size;
3431 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3432 if (size < 0)
3433 return;
3434 if (size == 0) {
3435 /* end of connection */
3436 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3437 return;
3439 qemu_send_packet(s->vc, s->buf, size);
3442 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3444 struct ip_mreq imr;
3445 int fd;
3446 int val, ret;
3447 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3448 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3449 inet_ntoa(mcastaddr->sin_addr),
3450 (int)ntohl(mcastaddr->sin_addr.s_addr));
3451 return -1;
3454 fd = socket(PF_INET, SOCK_DGRAM, 0);
3455 if (fd < 0) {
3456 perror("socket(PF_INET, SOCK_DGRAM)");
3457 return -1;
3460 val = 1;
3461 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3462 (const char *)&val, sizeof(val));
3463 if (ret < 0) {
3464 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3465 goto fail;
3468 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3469 if (ret < 0) {
3470 perror("bind");
3471 goto fail;
3474 /* Add host to multicast group */
3475 imr.imr_multiaddr = mcastaddr->sin_addr;
3476 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3478 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3479 (const char *)&imr, sizeof(struct ip_mreq));
3480 if (ret < 0) {
3481 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3482 goto fail;
3485 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3486 val = 1;
3487 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3488 (const char *)&val, sizeof(val));
3489 if (ret < 0) {
3490 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3491 goto fail;
3494 socket_set_nonblock(fd);
3495 return fd;
3496 fail:
3497 if (fd >= 0)
3498 closesocket(fd);
3499 return -1;
3502 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3503 int is_connected)
3505 struct sockaddr_in saddr;
3506 int newfd;
3507 socklen_t saddr_len;
3508 NetSocketState *s;
3510 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3511 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3512 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3515 if (is_connected) {
3516 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3517 /* must be bound */
3518 if (saddr.sin_addr.s_addr==0) {
3519 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3520 fd);
3521 return NULL;
3523 /* clone dgram socket */
3524 newfd = net_socket_mcast_create(&saddr);
3525 if (newfd < 0) {
3526 /* error already reported by net_socket_mcast_create() */
3527 close(fd);
3528 return NULL;
3530 /* clone newfd to fd, close newfd */
3531 dup2(newfd, fd);
3532 close(newfd);
3534 } else {
3535 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3536 fd, strerror(errno));
3537 return NULL;
3541 s = qemu_mallocz(sizeof(NetSocketState));
3542 if (!s)
3543 return NULL;
3544 s->fd = fd;
3546 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3547 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3549 /* mcast: save bound address as dst */
3550 if (is_connected) s->dgram_dst=saddr;
3552 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3553 "socket: fd=%d (%s mcast=%s:%d)",
3554 fd, is_connected? "cloned" : "",
3555 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3556 return s;
3559 static void net_socket_connect(void *opaque)
3561 NetSocketState *s = opaque;
3562 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3565 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3566 int is_connected)
3568 NetSocketState *s;
3569 s = qemu_mallocz(sizeof(NetSocketState));
3570 if (!s)
3571 return NULL;
3572 s->fd = fd;
3573 s->vc = qemu_new_vlan_client(vlan,
3574 net_socket_receive, NULL, s);
3575 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3576 "socket: fd=%d", fd);
3577 if (is_connected) {
3578 net_socket_connect(s);
3579 } else {
3580 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3582 return s;
3585 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3586 int is_connected)
3588 int so_type=-1, optlen=sizeof(so_type);
3590 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3591 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3592 return NULL;
3594 switch(so_type) {
3595 case SOCK_DGRAM:
3596 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3597 case SOCK_STREAM:
3598 return net_socket_fd_init_stream(vlan, fd, is_connected);
3599 default:
3600 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3601 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3602 return net_socket_fd_init_stream(vlan, fd, is_connected);
3604 return NULL;
3607 static void net_socket_accept(void *opaque)
3609 NetSocketListenState *s = opaque;
3610 NetSocketState *s1;
3611 struct sockaddr_in saddr;
3612 socklen_t len;
3613 int fd;
3615 for(;;) {
3616 len = sizeof(saddr);
3617 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3618 if (fd < 0 && errno != EINTR) {
3619 return;
3620 } else if (fd >= 0) {
3621 break;
3624 s1 = net_socket_fd_init(s->vlan, fd, 1);
3625 if (!s1) {
3626 closesocket(fd);
3627 } else {
3628 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3629 "socket: connection from %s:%d",
3630 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3634 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3636 NetSocketListenState *s;
3637 int fd, val, ret;
3638 struct sockaddr_in saddr;
3640 if (parse_host_port(&saddr, host_str) < 0)
3641 return -1;
3643 s = qemu_mallocz(sizeof(NetSocketListenState));
3644 if (!s)
3645 return -1;
3647 fd = socket(PF_INET, SOCK_STREAM, 0);
3648 if (fd < 0) {
3649 perror("socket");
3650 return -1;
3652 socket_set_nonblock(fd);
3654 /* allow fast reuse */
3655 val = 1;
3656 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3658 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3659 if (ret < 0) {
3660 perror("bind");
3661 return -1;
3663 ret = listen(fd, 0);
3664 if (ret < 0) {
3665 perror("listen");
3666 return -1;
3668 s->vlan = vlan;
3669 s->fd = fd;
3670 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3671 return 0;
3674 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3676 NetSocketState *s;
3677 int fd, connected, ret, err;
3678 struct sockaddr_in saddr;
3680 if (parse_host_port(&saddr, host_str) < 0)
3681 return -1;
3683 fd = socket(PF_INET, SOCK_STREAM, 0);
3684 if (fd < 0) {
3685 perror("socket");
3686 return -1;
3688 socket_set_nonblock(fd);
3690 connected = 0;
3691 for(;;) {
3692 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3693 if (ret < 0) {
3694 err = socket_error();
3695 if (err == EINTR || err == EWOULDBLOCK) {
3696 } else if (err == EINPROGRESS) {
3697 break;
3698 } else {
3699 perror("connect");
3700 closesocket(fd);
3701 return -1;
3703 } else {
3704 connected = 1;
3705 break;
3708 s = net_socket_fd_init(vlan, fd, connected);
3709 if (!s)
3710 return -1;
3711 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3712 "socket: connect to %s:%d",
3713 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3714 return 0;
3717 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3719 NetSocketState *s;
3720 int fd;
3721 struct sockaddr_in saddr;
3723 if (parse_host_port(&saddr, host_str) < 0)
3724 return -1;
3727 fd = net_socket_mcast_create(&saddr);
3728 if (fd < 0)
3729 return -1;
3731 s = net_socket_fd_init(vlan, fd, 0);
3732 if (!s)
3733 return -1;
3735 s->dgram_dst = saddr;
3737 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3738 "socket: mcast=%s:%d",
3739 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3740 return 0;
3744 static int get_param_value(char *buf, int buf_size,
3745 const char *tag, const char *str)
3747 const char *p;
3748 char *q;
3749 char option[128];
3751 p = str;
3752 for(;;) {
3753 q = option;
3754 while (*p != '\0' && *p != '=') {
3755 if ((q - option) < sizeof(option) - 1)
3756 *q++ = *p;
3757 p++;
3759 *q = '\0';
3760 if (*p != '=')
3761 break;
3762 p++;
3763 if (!strcmp(tag, option)) {
3764 q = buf;
3765 while (*p != '\0' && *p != ',') {
3766 if ((q - buf) < buf_size - 1)
3767 *q++ = *p;
3768 p++;
3770 *q = '\0';
3771 return q - buf;
3772 } else {
3773 while (*p != '\0' && *p != ',') {
3774 p++;
3777 if (*p != ',')
3778 break;
3779 p++;
3781 return 0;
3784 static int net_client_init(const char *str)
3786 const char *p;
3787 char *q;
3788 char device[64];
3789 char buf[1024];
3790 int vlan_id, ret;
3791 VLANState *vlan;
3793 p = str;
3794 q = device;
3795 while (*p != '\0' && *p != ',') {
3796 if ((q - device) < sizeof(device) - 1)
3797 *q++ = *p;
3798 p++;
3800 *q = '\0';
3801 if (*p == ',')
3802 p++;
3803 vlan_id = 0;
3804 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3805 vlan_id = strtol(buf, NULL, 0);
3807 vlan = qemu_find_vlan(vlan_id);
3808 if (!vlan) {
3809 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3810 return -1;
3812 if (!strcmp(device, "nic")) {
3813 NICInfo *nd;
3814 uint8_t *macaddr;
3816 if (nb_nics >= MAX_NICS) {
3817 fprintf(stderr, "Too Many NICs\n");
3818 return -1;
3820 nd = &nd_table[nb_nics];
3821 macaddr = nd->macaddr;
3822 macaddr[0] = 0x52;
3823 macaddr[1] = 0x54;
3824 macaddr[2] = 0x00;
3825 macaddr[3] = 0x12;
3826 macaddr[4] = 0x34;
3827 macaddr[5] = 0x56 + nb_nics;
3829 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3830 if (parse_macaddr(macaddr, buf) < 0) {
3831 fprintf(stderr, "invalid syntax for ethernet address\n");
3832 return -1;
3835 if (get_param_value(buf, sizeof(buf), "model", p)) {
3836 nd->model = strdup(buf);
3838 nd->vlan = vlan;
3839 nb_nics++;
3840 ret = 0;
3841 } else
3842 if (!strcmp(device, "none")) {
3843 /* does nothing. It is needed to signal that no network cards
3844 are wanted */
3845 ret = 0;
3846 } else
3847 #ifdef CONFIG_SLIRP
3848 if (!strcmp(device, "user")) {
3849 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3850 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3852 ret = net_slirp_init(vlan);
3853 } else
3854 #endif
3855 #ifdef _WIN32
3856 if (!strcmp(device, "tap")) {
3857 char ifname[64];
3858 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3859 fprintf(stderr, "tap: no interface name\n");
3860 return -1;
3862 ret = tap_win32_init(vlan, ifname);
3863 } else
3864 #else
3865 if (!strcmp(device, "tap")) {
3866 char ifname[64];
3867 char setup_script[1024];
3868 int fd;
3869 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3870 fd = strtol(buf, NULL, 0);
3871 ret = -1;
3872 if (net_tap_fd_init(vlan, fd))
3873 ret = 0;
3874 } else {
3875 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3876 ifname[0] = '\0';
3878 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3879 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3881 ret = net_tap_init(vlan, ifname, setup_script);
3883 } else
3884 #endif
3885 if (!strcmp(device, "socket")) {
3886 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3887 int fd;
3888 fd = strtol(buf, NULL, 0);
3889 ret = -1;
3890 if (net_socket_fd_init(vlan, fd, 1))
3891 ret = 0;
3892 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3893 ret = net_socket_listen_init(vlan, buf);
3894 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3895 ret = net_socket_connect_init(vlan, buf);
3896 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3897 ret = net_socket_mcast_init(vlan, buf);
3898 } else {
3899 fprintf(stderr, "Unknown socket options: %s\n", p);
3900 return -1;
3902 } else
3904 fprintf(stderr, "Unknown network device: %s\n", device);
3905 return -1;
3907 if (ret < 0) {
3908 fprintf(stderr, "Could not initialize device '%s'\n", device);
3911 return ret;
3914 void do_info_network(void)
3916 VLANState *vlan;
3917 VLANClientState *vc;
3919 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3920 term_printf("VLAN %d devices:\n", vlan->id);
3921 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3922 term_printf(" %s\n", vc->info_str);
3926 /***********************************************************/
3927 /* USB devices */
3929 static USBPort *used_usb_ports;
3930 static USBPort *free_usb_ports;
3932 /* ??? Maybe change this to register a hub to keep track of the topology. */
3933 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3934 usb_attachfn attach)
3936 port->opaque = opaque;
3937 port->index = index;
3938 port->attach = attach;
3939 port->next = free_usb_ports;
3940 free_usb_ports = port;
3943 static int usb_device_add(const char *devname)
3945 const char *p;
3946 USBDevice *dev;
3947 USBPort *port;
3949 if (!free_usb_ports)
3950 return -1;
3952 if (strstart(devname, "host:", &p)) {
3953 dev = usb_host_device_open(p);
3954 } else if (!strcmp(devname, "mouse")) {
3955 dev = usb_mouse_init();
3956 } else if (!strcmp(devname, "tablet")) {
3957 dev = usb_tablet_init();
3958 } else if (strstart(devname, "disk:", &p)) {
3959 dev = usb_msd_init(p);
3960 } else {
3961 return -1;
3963 if (!dev)
3964 return -1;
3966 /* Find a USB port to add the device to. */
3967 port = free_usb_ports;
3968 if (!port->next) {
3969 USBDevice *hub;
3971 /* Create a new hub and chain it on. */
3972 free_usb_ports = NULL;
3973 port->next = used_usb_ports;
3974 used_usb_ports = port;
3976 hub = usb_hub_init(VM_USB_HUB_SIZE);
3977 usb_attach(port, hub);
3978 port = free_usb_ports;
3981 free_usb_ports = port->next;
3982 port->next = used_usb_ports;
3983 used_usb_ports = port;
3984 usb_attach(port, dev);
3985 return 0;
3988 static int usb_device_del(const char *devname)
3990 USBPort *port;
3991 USBPort **lastp;
3992 USBDevice *dev;
3993 int bus_num, addr;
3994 const char *p;
3996 if (!used_usb_ports)
3997 return -1;
3999 p = strchr(devname, '.');
4000 if (!p)
4001 return -1;
4002 bus_num = strtoul(devname, NULL, 0);
4003 addr = strtoul(p + 1, NULL, 0);
4004 if (bus_num != 0)
4005 return -1;
4007 lastp = &used_usb_ports;
4008 port = used_usb_ports;
4009 while (port && port->dev->addr != addr) {
4010 lastp = &port->next;
4011 port = port->next;
4014 if (!port)
4015 return -1;
4017 dev = port->dev;
4018 *lastp = port->next;
4019 usb_attach(port, NULL);
4020 dev->handle_destroy(dev);
4021 port->next = free_usb_ports;
4022 free_usb_ports = port;
4023 return 0;
4026 void do_usb_add(const char *devname)
4028 int ret;
4029 ret = usb_device_add(devname);
4030 if (ret < 0)
4031 term_printf("Could not add USB device '%s'\n", devname);
4034 void do_usb_del(const char *devname)
4036 int ret;
4037 ret = usb_device_del(devname);
4038 if (ret < 0)
4039 term_printf("Could not remove USB device '%s'\n", devname);
4042 void usb_info(void)
4044 USBDevice *dev;
4045 USBPort *port;
4046 const char *speed_str;
4048 if (!usb_enabled) {
4049 term_printf("USB support not enabled\n");
4050 return;
4053 for (port = used_usb_ports; port; port = port->next) {
4054 dev = port->dev;
4055 if (!dev)
4056 continue;
4057 switch(dev->speed) {
4058 case USB_SPEED_LOW:
4059 speed_str = "1.5";
4060 break;
4061 case USB_SPEED_FULL:
4062 speed_str = "12";
4063 break;
4064 case USB_SPEED_HIGH:
4065 speed_str = "480";
4066 break;
4067 default:
4068 speed_str = "?";
4069 break;
4071 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4072 0, dev->addr, speed_str, dev->devname);
4076 /***********************************************************/
4077 /* pid file */
4079 static char *pid_filename;
4081 /* Remove PID file. Called on normal exit */
4083 static void remove_pidfile(void)
4085 unlink (pid_filename);
4088 static void create_pidfile(const char *filename)
4090 struct stat pidstat;
4091 FILE *f;
4093 /* Try to write our PID to the named file */
4094 if (stat(filename, &pidstat) < 0) {
4095 if (errno == ENOENT) {
4096 if ((f = fopen (filename, "w")) == NULL) {
4097 perror("Opening pidfile");
4098 exit(1);
4100 fprintf(f, "%d\n", getpid());
4101 fclose(f);
4102 pid_filename = qemu_strdup(filename);
4103 if (!pid_filename) {
4104 fprintf(stderr, "Could not save PID filename");
4105 exit(1);
4107 atexit(remove_pidfile);
4109 } else {
4110 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4111 filename);
4112 exit(1);
4116 /***********************************************************/
4117 /* dumb display */
4119 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4123 static void dumb_resize(DisplayState *ds, int w, int h)
4127 static void dumb_refresh(DisplayState *ds)
4129 vga_hw_update();
4132 void dumb_display_init(DisplayState *ds)
4134 ds->data = NULL;
4135 ds->linesize = 0;
4136 ds->depth = 0;
4137 ds->dpy_update = dumb_update;
4138 ds->dpy_resize = dumb_resize;
4139 ds->dpy_refresh = dumb_refresh;
4142 /***********************************************************/
4143 /* I/O handling */
4145 #define MAX_IO_HANDLERS 64
4147 typedef struct IOHandlerRecord {
4148 int fd;
4149 IOCanRWHandler *fd_read_poll;
4150 IOHandler *fd_read;
4151 IOHandler *fd_write;
4152 int deleted;
4153 void *opaque;
4154 /* temporary data */
4155 struct pollfd *ufd;
4156 struct IOHandlerRecord *next;
4157 } IOHandlerRecord;
4159 static IOHandlerRecord *first_io_handler;
4161 /* XXX: fd_read_poll should be suppressed, but an API change is
4162 necessary in the character devices to suppress fd_can_read(). */
4163 int qemu_set_fd_handler2(int fd,
4164 IOCanRWHandler *fd_read_poll,
4165 IOHandler *fd_read,
4166 IOHandler *fd_write,
4167 void *opaque)
4169 IOHandlerRecord **pioh, *ioh;
4171 if (!fd_read && !fd_write) {
4172 pioh = &first_io_handler;
4173 for(;;) {
4174 ioh = *pioh;
4175 if (ioh == NULL)
4176 break;
4177 if (ioh->fd == fd) {
4178 ioh->deleted = 1;
4179 break;
4181 pioh = &ioh->next;
4183 } else {
4184 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4185 if (ioh->fd == fd)
4186 goto found;
4188 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4189 if (!ioh)
4190 return -1;
4191 ioh->next = first_io_handler;
4192 first_io_handler = ioh;
4193 found:
4194 ioh->fd = fd;
4195 ioh->fd_read_poll = fd_read_poll;
4196 ioh->fd_read = fd_read;
4197 ioh->fd_write = fd_write;
4198 ioh->opaque = opaque;
4199 ioh->deleted = 0;
4201 return 0;
4204 int qemu_set_fd_handler(int fd,
4205 IOHandler *fd_read,
4206 IOHandler *fd_write,
4207 void *opaque)
4209 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4212 /***********************************************************/
4213 /* Polling handling */
4215 typedef struct PollingEntry {
4216 PollingFunc *func;
4217 void *opaque;
4218 struct PollingEntry *next;
4219 } PollingEntry;
4221 static PollingEntry *first_polling_entry;
4223 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4225 PollingEntry **ppe, *pe;
4226 pe = qemu_mallocz(sizeof(PollingEntry));
4227 if (!pe)
4228 return -1;
4229 pe->func = func;
4230 pe->opaque = opaque;
4231 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4232 *ppe = pe;
4233 return 0;
4236 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4238 PollingEntry **ppe, *pe;
4239 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4240 pe = *ppe;
4241 if (pe->func == func && pe->opaque == opaque) {
4242 *ppe = pe->next;
4243 qemu_free(pe);
4244 break;
4249 #ifdef _WIN32
4250 /***********************************************************/
4251 /* Wait objects support */
4252 typedef struct WaitObjects {
4253 int num;
4254 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4255 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4256 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4257 } WaitObjects;
4259 static WaitObjects wait_objects = {0};
4261 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4263 WaitObjects *w = &wait_objects;
4265 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4266 return -1;
4267 w->events[w->num] = handle;
4268 w->func[w->num] = func;
4269 w->opaque[w->num] = opaque;
4270 w->num++;
4271 return 0;
4274 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4276 int i, found;
4277 WaitObjects *w = &wait_objects;
4279 found = 0;
4280 for (i = 0; i < w->num; i++) {
4281 if (w->events[i] == handle)
4282 found = 1;
4283 if (found) {
4284 w->events[i] = w->events[i + 1];
4285 w->func[i] = w->func[i + 1];
4286 w->opaque[i] = w->opaque[i + 1];
4289 if (found)
4290 w->num--;
4292 #endif
4294 #define SELF_ANNOUNCE_ROUNDS 5
4295 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4296 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4297 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4299 static int announce_self_create(uint8_t *buf,
4300 uint8_t *mac_addr)
4302 uint32_t magic = EXPERIMENTAL_MAGIC;
4303 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
4305 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4307 memset(buf, 0xff, 6); /* h_dst */
4308 memcpy(buf + 6, mac_addr, 6); /* h_src */
4309 memcpy(buf + 12, &proto, 2); /* h_proto */
4310 memcpy(buf + 14, &magic, 4); /* magic */
4312 return 18; /* len */
4315 static void qemu_announce_self(void)
4317 int i, j, len;
4318 VLANState *vlan;
4319 VLANClientState *vc;
4320 uint8_t buf[256];
4322 for (i = 0; i < nb_nics; i++) {
4323 len = announce_self_create(buf, nd_table[i].macaddr);
4324 vlan = nd_table[i].vlan;
4325 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4326 if (vc->fd_read == tap_receive) /* send only if tap */
4327 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
4328 vc->fd_read(vc->opaque, buf, len);
4333 /***********************************************************/
4334 /* savevm/loadvm support */
4336 #define IO_BUF_SIZE 32768
4338 struct QEMUFile {
4339 QEMUFilePutBufferFunc *put_buffer;
4340 QEMUFileGetBufferFunc *get_buffer;
4341 QEMUFileCloseFunc *close;
4342 void *opaque;
4344 int64_t buf_offset; /* start of buffer when writing, end of buffer
4345 when reading */
4346 int buf_index;
4347 int buf_size; /* 0 when writing */
4348 uint8_t buf[IO_BUF_SIZE];
4351 typedef struct QEMUFileFD
4353 int fd;
4354 } QEMUFileFD;
4356 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4358 QEMUFileFD *s = opaque;
4359 int offset = 0;
4360 ssize_t len;
4362 again:
4363 len = read(s->fd, buf + offset, size - offset);
4364 if (len == -1) {
4365 if (errno == EINTR || errno == EAGAIN)
4366 goto again;
4369 return len;
4372 QEMUFile *qemu_fopen_fd(int fd)
4374 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
4375 s->fd = fd;
4376 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
4379 typedef struct QEMUFileUnix
4381 FILE *outfile;
4382 } QEMUFileUnix;
4384 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4386 QEMUFileUnix *s = opaque;
4387 fseek(s->outfile, pos, SEEK_SET);
4388 fwrite(buf, 1, size, s->outfile);
4391 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4393 QEMUFileUnix *s = opaque;
4394 fseek(s->outfile, pos, SEEK_SET);
4395 return fread(buf, 1, size, s->outfile);
4398 static void file_close(void *opaque)
4400 QEMUFileUnix *s = opaque;
4401 fclose(s->outfile);
4402 qemu_free(s);
4405 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
4407 QEMUFileUnix *s;
4409 s = qemu_mallocz(sizeof(QEMUFileUnix));
4410 if (!s)
4411 return NULL;
4413 s->outfile = fopen(filename, mode);
4414 if (!s->outfile)
4415 goto fail;
4417 if (!strcmp(mode, "wb"))
4418 return qemu_fopen(s, file_put_buffer, NULL, file_close);
4419 else if (!strcmp(mode, "rb"))
4420 return qemu_fopen(s, NULL, file_get_buffer, file_close);
4422 fail:
4423 if (s->outfile)
4424 fclose(s->outfile);
4425 qemu_free(s);
4426 return NULL;
4429 typedef struct QEMUFileBdrv
4431 BlockDriverState *bs;
4432 int64_t base_offset;
4433 } QEMUFileBdrv;
4435 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
4437 QEMUFileBdrv *s = opaque;
4438 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
4441 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
4443 QEMUFileBdrv *s = opaque;
4444 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
4447 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4449 QEMUFileBdrv *s;
4451 s = qemu_mallocz(sizeof(QEMUFileBdrv));
4452 if (!s)
4453 return NULL;
4455 s->bs = bs;
4456 s->base_offset = offset;
4458 if (is_writable)
4459 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
4461 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
4464 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
4465 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
4467 QEMUFile *f;
4469 f = qemu_mallocz(sizeof(QEMUFile));
4470 if (!f)
4471 return NULL;
4473 f->opaque = opaque;
4474 f->put_buffer = put_buffer;
4475 f->get_buffer = get_buffer;
4476 f->close = close;
4478 return f;
4481 void qemu_fflush(QEMUFile *f)
4483 if (!f->put_buffer)
4484 return;
4486 if (f->buf_index > 0) {
4487 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
4488 f->buf_offset += f->buf_index;
4489 f->buf_index = 0;
4493 static void qemu_fill_buffer(QEMUFile *f)
4495 int len;
4497 if (!f->get_buffer)
4498 return;
4500 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
4501 if (len < 0)
4502 len = 0;
4504 f->buf_index = 0;
4505 f->buf_size = len;
4506 f->buf_offset += len;
4509 void qemu_fclose(QEMUFile *f)
4511 qemu_fflush(f);
4512 if (f->close)
4513 f->close(f->opaque);
4514 qemu_free(f);
4517 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4519 int l;
4520 while (size > 0) {
4521 l = IO_BUF_SIZE - f->buf_index;
4522 if (l > size)
4523 l = size;
4524 memcpy(f->buf + f->buf_index, buf, l);
4525 f->buf_index += l;
4526 buf += l;
4527 size -= l;
4528 if (f->buf_index >= IO_BUF_SIZE)
4529 qemu_fflush(f);
4533 void qemu_put_byte(QEMUFile *f, int v)
4535 f->buf[f->buf_index++] = v;
4536 if (f->buf_index >= IO_BUF_SIZE)
4537 qemu_fflush(f);
4540 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4542 int size, l;
4544 size = size1;
4545 while (size > 0) {
4546 l = f->buf_size - f->buf_index;
4547 if (l == 0) {
4548 qemu_fill_buffer(f);
4549 l = f->buf_size - f->buf_index;
4550 if (l == 0)
4551 break;
4553 if (l > size)
4554 l = size;
4555 memcpy(buf, f->buf + f->buf_index, l);
4556 f->buf_index += l;
4557 buf += l;
4558 size -= l;
4560 return size1 - size;
4563 int qemu_get_byte(QEMUFile *f)
4565 if (f->buf_index >= f->buf_size) {
4566 qemu_fill_buffer(f);
4567 if (f->buf_index >= f->buf_size)
4568 return 0;
4570 return f->buf[f->buf_index++];
4573 int64_t qemu_ftell(QEMUFile *f)
4575 return f->buf_offset - f->buf_size + f->buf_index;
4578 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4580 if (whence == SEEK_SET) {
4581 /* nothing to do */
4582 } else if (whence == SEEK_CUR) {
4583 pos += qemu_ftell(f);
4584 } else {
4585 /* SEEK_END not supported */
4586 return -1;
4588 if (f->put_buffer) {
4589 qemu_fflush(f);
4590 f->buf_offset = pos;
4591 } else {
4592 f->buf_offset = pos;
4593 f->buf_index = 0;
4594 f->buf_size = 0;
4596 return pos;
4599 void qemu_put_be16(QEMUFile *f, unsigned int v)
4601 qemu_put_byte(f, v >> 8);
4602 qemu_put_byte(f, v);
4605 void qemu_put_be32(QEMUFile *f, unsigned int v)
4607 qemu_put_byte(f, v >> 24);
4608 qemu_put_byte(f, v >> 16);
4609 qemu_put_byte(f, v >> 8);
4610 qemu_put_byte(f, v);
4613 void qemu_put_be64(QEMUFile *f, uint64_t v)
4615 qemu_put_be32(f, v >> 32);
4616 qemu_put_be32(f, v);
4619 unsigned int qemu_get_be16(QEMUFile *f)
4621 unsigned int v;
4622 v = qemu_get_byte(f) << 8;
4623 v |= qemu_get_byte(f);
4624 return v;
4627 unsigned int qemu_get_be32(QEMUFile *f)
4629 unsigned int v;
4630 v = qemu_get_byte(f) << 24;
4631 v |= qemu_get_byte(f) << 16;
4632 v |= qemu_get_byte(f) << 8;
4633 v |= qemu_get_byte(f);
4634 return v;
4637 uint64_t qemu_get_be64(QEMUFile *f)
4639 uint64_t v;
4640 v = (uint64_t)qemu_get_be32(f) << 32;
4641 v |= qemu_get_be32(f);
4642 return v;
4645 typedef struct SaveStateEntry {
4646 char idstr[256];
4647 int instance_id;
4648 int version_id;
4649 SaveStateHandler *save_state;
4650 LoadStateHandler *load_state;
4651 void *opaque;
4652 struct SaveStateEntry *next;
4653 } SaveStateEntry;
4655 static SaveStateEntry *first_se;
4657 int register_savevm(const char *idstr,
4658 int instance_id,
4659 int version_id,
4660 SaveStateHandler *save_state,
4661 LoadStateHandler *load_state,
4662 void *opaque)
4664 SaveStateEntry *se, **pse;
4666 se = qemu_malloc(sizeof(SaveStateEntry));
4667 if (!se)
4668 return -1;
4669 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4670 se->instance_id = instance_id;
4671 se->version_id = version_id;
4672 se->save_state = save_state;
4673 se->load_state = load_state;
4674 se->opaque = opaque;
4675 se->next = NULL;
4677 /* add at the end of list */
4678 pse = &first_se;
4679 while (*pse != NULL)
4680 pse = &(*pse)->next;
4681 *pse = se;
4682 return 0;
4685 #define QEMU_VM_FILE_MAGIC 0x5145564d
4686 #define QEMU_VM_FILE_VERSION 0x00000002
4688 int qemu_savevm_state(QEMUFile *f)
4690 SaveStateEntry *se;
4691 int len, ret;
4692 int64_t cur_pos, len_pos, total_len_pos;
4694 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4695 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4696 total_len_pos = qemu_ftell(f);
4697 qemu_put_be64(f, 0); /* total size */
4699 for(se = first_se; se != NULL; se = se->next) {
4700 /* ID string */
4701 len = strlen(se->idstr);
4702 qemu_put_byte(f, len);
4703 qemu_put_buffer(f, se->idstr, len);
4705 qemu_put_be32(f, se->instance_id);
4706 qemu_put_be32(f, se->version_id);
4708 /* record size: filled later */
4709 len_pos = qemu_ftell(f);
4710 qemu_put_be32(f, 0);
4712 se->save_state(f, se->opaque);
4714 /* fill record size */
4715 cur_pos = qemu_ftell(f);
4716 len = cur_pos - len_pos - 4;
4717 qemu_fseek(f, len_pos, SEEK_SET);
4718 qemu_put_be32(f, len);
4719 qemu_fseek(f, cur_pos, SEEK_SET);
4721 cur_pos = qemu_ftell(f);
4722 qemu_fseek(f, total_len_pos, SEEK_SET);
4723 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4724 qemu_fseek(f, cur_pos, SEEK_SET);
4726 ret = 0;
4727 return ret;
4730 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4732 SaveStateEntry *se;
4734 for(se = first_se; se != NULL; se = se->next) {
4735 if (!strcmp(se->idstr, idstr) &&
4736 instance_id == se->instance_id)
4737 return se;
4739 return NULL;
4742 int qemu_loadvm_state(QEMUFile *f)
4744 SaveStateEntry *se;
4745 int len, ret, instance_id, record_len, version_id;
4746 int64_t total_len, end_pos, cur_pos;
4747 unsigned int v;
4748 char idstr[256];
4750 v = qemu_get_be32(f);
4751 if (v != QEMU_VM_FILE_MAGIC)
4752 goto fail;
4753 v = qemu_get_be32(f);
4754 if (v != QEMU_VM_FILE_VERSION) {
4755 fail:
4756 ret = -1;
4757 goto the_end;
4759 total_len = qemu_get_be64(f);
4760 end_pos = total_len + qemu_ftell(f);
4761 for(;;) {
4762 if (qemu_ftell(f) >= end_pos)
4763 break;
4764 len = qemu_get_byte(f);
4765 qemu_get_buffer(f, idstr, len);
4766 idstr[len] = '\0';
4767 instance_id = qemu_get_be32(f);
4768 version_id = qemu_get_be32(f);
4769 record_len = qemu_get_be32(f);
4770 #if 0
4771 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4772 idstr, instance_id, version_id, record_len);
4773 #endif
4774 cur_pos = qemu_ftell(f);
4775 se = find_se(idstr, instance_id);
4776 if (!se) {
4777 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4778 instance_id, idstr);
4779 } else {
4780 ret = se->load_state(f, se->opaque, version_id);
4781 if (ret < 0) {
4782 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4783 instance_id, idstr);
4784 goto the_end;
4787 /* always seek to exact end of record */
4788 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4790 ret = 0;
4791 the_end:
4792 return ret;
4795 int qemu_live_savevm_state(QEMUFile *f)
4797 SaveStateEntry *se;
4798 int len, ret;
4800 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4801 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4803 for(se = first_se; se != NULL; se = se->next) {
4804 len = strlen(se->idstr);
4806 qemu_put_byte(f, len);
4807 qemu_put_buffer(f, se->idstr, len);
4808 qemu_put_be32(f, se->instance_id);
4809 qemu_put_be32(f, se->version_id);
4811 se->save_state(f, se->opaque);
4814 qemu_put_byte(f, 0);
4816 ret = 0;
4817 return ret;
4820 int qemu_live_loadvm_state(QEMUFile *f)
4822 SaveStateEntry *se;
4823 int len, ret, instance_id, version_id;
4824 unsigned int v;
4825 char idstr[256];
4827 v = qemu_get_be32(f);
4828 if (v != QEMU_VM_FILE_MAGIC)
4829 goto fail;
4830 v = qemu_get_be32(f);
4831 if (v != QEMU_VM_FILE_VERSION) {
4832 fail:
4833 ret = -1;
4834 goto the_end;
4837 for(;;) {
4838 len = qemu_get_byte(f);
4839 if (len == 0)
4840 break;
4841 qemu_get_buffer(f, idstr, len);
4842 idstr[len] = '\0';
4843 instance_id = qemu_get_be32(f);
4844 version_id = qemu_get_be32(f);
4845 se = find_se(idstr, instance_id);
4846 if (!se) {
4847 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4848 instance_id, idstr);
4849 } else {
4850 ret = se->load_state(f, se->opaque, version_id);
4851 if (ret < 0) {
4852 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4853 instance_id, idstr);
4854 goto the_end;
4858 ret = 0;
4860 qemu_announce_self();
4862 the_end:
4863 return ret;
4866 /* device can contain snapshots */
4867 static int bdrv_can_snapshot(BlockDriverState *bs)
4869 return (bs &&
4870 !bdrv_is_removable(bs) &&
4871 !bdrv_is_read_only(bs));
4874 /* device must be snapshots in order to have a reliable snapshot */
4875 static int bdrv_has_snapshot(BlockDriverState *bs)
4877 return (bs &&
4878 !bdrv_is_removable(bs) &&
4879 !bdrv_is_read_only(bs));
4882 static BlockDriverState *get_bs_snapshots(void)
4884 BlockDriverState *bs;
4885 int i;
4887 if (bs_snapshots)
4888 return bs_snapshots;
4889 for(i = 0; i <= MAX_DISKS; i++) {
4890 bs = bs_table[i];
4891 if (bdrv_can_snapshot(bs))
4892 goto ok;
4894 return NULL;
4896 bs_snapshots = bs;
4897 return bs;
4900 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4901 const char *name)
4903 QEMUSnapshotInfo *sn_tab, *sn;
4904 int nb_sns, i, ret;
4906 ret = -ENOENT;
4907 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4908 if (nb_sns < 0)
4909 return ret;
4910 for(i = 0; i < nb_sns; i++) {
4911 sn = &sn_tab[i];
4912 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4913 *sn_info = *sn;
4914 ret = 0;
4915 break;
4918 qemu_free(sn_tab);
4919 return ret;
4922 void do_savevm(const char *name)
4924 BlockDriverState *bs, *bs1;
4925 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4926 int must_delete, ret, i;
4927 BlockDriverInfo bdi1, *bdi = &bdi1;
4928 QEMUFile *f;
4929 int saved_vm_running;
4930 #ifdef _WIN32
4931 struct _timeb tb;
4932 #else
4933 struct timeval tv;
4934 #endif
4936 bs = get_bs_snapshots();
4937 if (!bs) {
4938 term_printf("No block device can accept snapshots\n");
4939 return;
4942 /* ??? Should this occur after vm_stop? */
4943 qemu_aio_flush();
4945 saved_vm_running = vm_running;
4946 vm_stop(0);
4948 must_delete = 0;
4949 if (name) {
4950 ret = bdrv_snapshot_find(bs, old_sn, name);
4951 if (ret >= 0) {
4952 must_delete = 1;
4955 memset(sn, 0, sizeof(*sn));
4956 if (must_delete) {
4957 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4958 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4959 } else {
4960 if (name)
4961 pstrcpy(sn->name, sizeof(sn->name), name);
4964 /* fill auxiliary fields */
4965 #ifdef _WIN32
4966 _ftime(&tb);
4967 sn->date_sec = tb.time;
4968 sn->date_nsec = tb.millitm * 1000000;
4969 #else
4970 gettimeofday(&tv, NULL);
4971 sn->date_sec = tv.tv_sec;
4972 sn->date_nsec = tv.tv_usec * 1000;
4973 #endif
4974 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4976 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4977 term_printf("Device %s does not support VM state snapshots\n",
4978 bdrv_get_device_name(bs));
4979 goto the_end;
4982 /* save the VM state */
4983 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4984 if (!f) {
4985 term_printf("Could not open VM state file\n");
4986 goto the_end;
4988 ret = qemu_savevm_state(f);
4989 sn->vm_state_size = qemu_ftell(f);
4990 qemu_fclose(f);
4991 if (ret < 0) {
4992 term_printf("Error %d while writing VM\n", ret);
4993 goto the_end;
4996 /* create the snapshots */
4998 for(i = 0; i < MAX_DISKS; i++) {
4999 bs1 = bs_table[i];
5000 if (bdrv_has_snapshot(bs1)) {
5001 if (must_delete) {
5002 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5003 if (ret < 0) {
5004 term_printf("Error while deleting snapshot on '%s'\n",
5005 bdrv_get_device_name(bs1));
5008 ret = bdrv_snapshot_create(bs1, sn);
5009 if (ret < 0) {
5010 term_printf("Error while creating snapshot on '%s'\n",
5011 bdrv_get_device_name(bs1));
5016 the_end:
5017 if (saved_vm_running)
5018 vm_start();
5021 void do_loadvm(const char *name)
5023 BlockDriverState *bs, *bs1;
5024 BlockDriverInfo bdi1, *bdi = &bdi1;
5025 QEMUFile *f;
5026 int i, ret;
5027 int saved_vm_running;
5029 bs = get_bs_snapshots();
5030 if (!bs) {
5031 term_printf("No block device supports snapshots\n");
5032 return;
5035 /* Flush all IO requests so they don't interfere with the new state. */
5036 qemu_aio_flush();
5038 saved_vm_running = vm_running;
5039 vm_stop(0);
5041 for(i = 0; i <= MAX_DISKS; i++) {
5042 bs1 = bs_table[i];
5043 if (bdrv_has_snapshot(bs1)) {
5044 ret = bdrv_snapshot_goto(bs1, name);
5045 if (ret < 0) {
5046 if (bs != bs1)
5047 term_printf("Warning: ");
5048 switch(ret) {
5049 case -ENOTSUP:
5050 term_printf("Snapshots not supported on device '%s'\n",
5051 bdrv_get_device_name(bs1));
5052 break;
5053 case -ENOENT:
5054 term_printf("Could not find snapshot '%s' on device '%s'\n",
5055 name, bdrv_get_device_name(bs1));
5056 break;
5057 default:
5058 term_printf("Error %d while activating snapshot on '%s'\n",
5059 ret, bdrv_get_device_name(bs1));
5060 break;
5062 /* fatal on snapshot block device */
5063 if (bs == bs1)
5064 goto the_end;
5069 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5070 term_printf("Device %s does not support VM state snapshots\n",
5071 bdrv_get_device_name(bs));
5072 return;
5075 /* restore the VM state */
5076 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5077 if (!f) {
5078 term_printf("Could not open VM state file\n");
5079 goto the_end;
5081 ret = qemu_loadvm_state(f);
5082 qemu_fclose(f);
5083 if (ret < 0) {
5084 term_printf("Error %d while loading VM state\n", ret);
5086 the_end:
5087 if (saved_vm_running)
5088 vm_start();
5091 void do_delvm(const char *name)
5093 BlockDriverState *bs, *bs1;
5094 int i, ret;
5096 bs = get_bs_snapshots();
5097 if (!bs) {
5098 term_printf("No block device supports snapshots\n");
5099 return;
5102 for(i = 0; i <= MAX_DISKS; i++) {
5103 bs1 = bs_table[i];
5104 if (bdrv_has_snapshot(bs1)) {
5105 ret = bdrv_snapshot_delete(bs1, name);
5106 if (ret < 0) {
5107 if (ret == -ENOTSUP)
5108 term_printf("Snapshots not supported on device '%s'\n",
5109 bdrv_get_device_name(bs1));
5110 else
5111 term_printf("Error %d while deleting snapshot on '%s'\n",
5112 ret, bdrv_get_device_name(bs1));
5118 void do_info_snapshots(void)
5120 BlockDriverState *bs, *bs1;
5121 QEMUSnapshotInfo *sn_tab, *sn;
5122 int nb_sns, i;
5123 char buf[256];
5125 bs = get_bs_snapshots();
5126 if (!bs) {
5127 term_printf("No available block device supports snapshots\n");
5128 return;
5130 term_printf("Snapshot devices:");
5131 for(i = 0; i <= MAX_DISKS; i++) {
5132 bs1 = bs_table[i];
5133 if (bdrv_has_snapshot(bs1)) {
5134 if (bs == bs1)
5135 term_printf(" %s", bdrv_get_device_name(bs1));
5138 term_printf("\n");
5140 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5141 if (nb_sns < 0) {
5142 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5143 return;
5145 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5146 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5147 for(i = 0; i < nb_sns; i++) {
5148 sn = &sn_tab[i];
5149 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5151 qemu_free(sn_tab);
5154 /***********************************************************/
5155 /* cpu save/restore */
5157 #if defined(TARGET_I386)
5159 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5161 qemu_put_be32(f, dt->selector);
5162 qemu_put_betl(f, dt->base);
5163 qemu_put_be32(f, dt->limit);
5164 qemu_put_be32(f, dt->flags);
5167 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5169 dt->selector = qemu_get_be32(f);
5170 dt->base = qemu_get_betl(f);
5171 dt->limit = qemu_get_be32(f);
5172 dt->flags = qemu_get_be32(f);
5175 void cpu_save(QEMUFile *f, void *opaque)
5177 CPUState *env = opaque;
5178 uint16_t fptag, fpus, fpuc, fpregs_format;
5179 uint32_t hflags;
5180 int i;
5182 #ifdef USE_KVM
5183 if (kvm_allowed)
5184 kvm_save_registers(env);
5185 #endif
5187 for(i = 0; i < CPU_NB_REGS; i++)
5188 qemu_put_betls(f, &env->regs[i]);
5189 qemu_put_betls(f, &env->eip);
5190 qemu_put_betls(f, &env->eflags);
5191 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5192 qemu_put_be32s(f, &hflags);
5194 /* FPU */
5195 fpuc = env->fpuc;
5196 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5197 fptag = 0;
5198 for(i = 0; i < 8; i++) {
5199 fptag |= ((!env->fptags[i]) << i);
5202 qemu_put_be16s(f, &fpuc);
5203 qemu_put_be16s(f, &fpus);
5204 qemu_put_be16s(f, &fptag);
5206 #ifdef USE_X86LDOUBLE
5207 fpregs_format = 0;
5208 #else
5209 fpregs_format = 1;
5210 #endif
5211 qemu_put_be16s(f, &fpregs_format);
5213 for(i = 0; i < 8; i++) {
5214 #ifdef USE_X86LDOUBLE
5216 uint64_t mant;
5217 uint16_t exp;
5218 /* we save the real CPU data (in case of MMX usage only 'mant'
5219 contains the MMX register */
5220 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5221 qemu_put_be64(f, mant);
5222 qemu_put_be16(f, exp);
5224 #else
5225 /* if we use doubles for float emulation, we save the doubles to
5226 avoid losing information in case of MMX usage. It can give
5227 problems if the image is restored on a CPU where long
5228 doubles are used instead. */
5229 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5230 #endif
5233 for(i = 0; i < 6; i++)
5234 cpu_put_seg(f, &env->segs[i]);
5235 cpu_put_seg(f, &env->ldt);
5236 cpu_put_seg(f, &env->tr);
5237 cpu_put_seg(f, &env->gdt);
5238 cpu_put_seg(f, &env->idt);
5240 qemu_put_be32s(f, &env->sysenter_cs);
5241 qemu_put_be32s(f, &env->sysenter_esp);
5242 qemu_put_be32s(f, &env->sysenter_eip);
5244 qemu_put_betls(f, &env->cr[0]);
5245 qemu_put_betls(f, &env->cr[2]);
5246 qemu_put_betls(f, &env->cr[3]);
5247 qemu_put_betls(f, &env->cr[4]);
5249 for(i = 0; i < 8; i++)
5250 qemu_put_betls(f, &env->dr[i]);
5252 /* MMU */
5253 qemu_put_be32s(f, &env->a20_mask);
5255 /* XMM */
5256 qemu_put_be32s(f, &env->mxcsr);
5257 for(i = 0; i < CPU_NB_REGS; i++) {
5258 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5259 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5262 #ifdef TARGET_X86_64
5263 qemu_put_be64s(f, &env->efer);
5264 qemu_put_be64s(f, &env->star);
5265 qemu_put_be64s(f, &env->lstar);
5266 qemu_put_be64s(f, &env->cstar);
5267 qemu_put_be64s(f, &env->fmask);
5268 qemu_put_be64s(f, &env->kernelgsbase);
5269 #endif
5270 qemu_put_be32s(f, &env->smbase);
5272 #ifdef USE_KVM
5273 if (kvm_allowed) {
5274 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5275 qemu_put_betls(f, &env->kvm_interrupt_bitmap[i]);
5277 qemu_put_be64s(f, &env->tsc);
5279 #endif
5283 #ifdef USE_X86LDOUBLE
5284 /* XXX: add that in a FPU generic layer */
5285 union x86_longdouble {
5286 uint64_t mant;
5287 uint16_t exp;
5290 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5291 #define EXPBIAS1 1023
5292 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5293 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5295 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5297 int e;
5298 /* mantissa */
5299 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5300 /* exponent + sign */
5301 e = EXPD1(temp) - EXPBIAS1 + 16383;
5302 e |= SIGND1(temp) >> 16;
5303 p->exp = e;
5305 #endif
5307 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5309 CPUState *env = opaque;
5310 int i, guess_mmx;
5311 uint32_t hflags;
5312 uint16_t fpus, fpuc, fptag, fpregs_format;
5314 if (version_id != 3 && version_id != 4)
5315 return -EINVAL;
5316 for(i = 0; i < CPU_NB_REGS; i++)
5317 qemu_get_betls(f, &env->regs[i]);
5318 qemu_get_betls(f, &env->eip);
5319 qemu_get_betls(f, &env->eflags);
5320 qemu_get_be32s(f, &hflags);
5322 qemu_get_be16s(f, &fpuc);
5323 qemu_get_be16s(f, &fpus);
5324 qemu_get_be16s(f, &fptag);
5325 qemu_get_be16s(f, &fpregs_format);
5327 /* NOTE: we cannot always restore the FPU state if the image come
5328 from a host with a different 'USE_X86LDOUBLE' define. We guess
5329 if we are in an MMX state to restore correctly in that case. */
5330 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5331 for(i = 0; i < 8; i++) {
5332 uint64_t mant;
5333 uint16_t exp;
5335 switch(fpregs_format) {
5336 case 0:
5337 mant = qemu_get_be64(f);
5338 exp = qemu_get_be16(f);
5339 #ifdef USE_X86LDOUBLE
5340 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5341 #else
5342 /* difficult case */
5343 if (guess_mmx)
5344 env->fpregs[i].mmx.MMX_Q(0) = mant;
5345 else
5346 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5347 #endif
5348 break;
5349 case 1:
5350 mant = qemu_get_be64(f);
5351 #ifdef USE_X86LDOUBLE
5353 union x86_longdouble *p;
5354 /* difficult case */
5355 p = (void *)&env->fpregs[i];
5356 if (guess_mmx) {
5357 p->mant = mant;
5358 p->exp = 0xffff;
5359 } else {
5360 fp64_to_fp80(p, mant);
5363 #else
5364 env->fpregs[i].mmx.MMX_Q(0) = mant;
5365 #endif
5366 break;
5367 default:
5368 return -EINVAL;
5372 env->fpuc = fpuc;
5373 /* XXX: restore FPU round state */
5374 env->fpstt = (fpus >> 11) & 7;
5375 env->fpus = fpus & ~0x3800;
5376 fptag ^= 0xff;
5377 for(i = 0; i < 8; i++) {
5378 env->fptags[i] = (fptag >> i) & 1;
5381 for(i = 0; i < 6; i++)
5382 cpu_get_seg(f, &env->segs[i]);
5383 cpu_get_seg(f, &env->ldt);
5384 cpu_get_seg(f, &env->tr);
5385 cpu_get_seg(f, &env->gdt);
5386 cpu_get_seg(f, &env->idt);
5388 qemu_get_be32s(f, &env->sysenter_cs);
5389 qemu_get_be32s(f, &env->sysenter_esp);
5390 qemu_get_be32s(f, &env->sysenter_eip);
5392 qemu_get_betls(f, &env->cr[0]);
5393 qemu_get_betls(f, &env->cr[2]);
5394 qemu_get_betls(f, &env->cr[3]);
5395 qemu_get_betls(f, &env->cr[4]);
5397 for(i = 0; i < 8; i++)
5398 qemu_get_betls(f, &env->dr[i]);
5400 /* MMU */
5401 qemu_get_be32s(f, &env->a20_mask);
5403 qemu_get_be32s(f, &env->mxcsr);
5404 for(i = 0; i < CPU_NB_REGS; i++) {
5405 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5406 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5409 #ifdef TARGET_X86_64
5410 qemu_get_be64s(f, &env->efer);
5411 qemu_get_be64s(f, &env->star);
5412 qemu_get_be64s(f, &env->lstar);
5413 qemu_get_be64s(f, &env->cstar);
5414 qemu_get_be64s(f, &env->fmask);
5415 qemu_get_be64s(f, &env->kernelgsbase);
5416 #endif
5417 if (version_id >= 4)
5418 qemu_get_be32s(f, &env->smbase);
5420 /* XXX: compute hflags from scratch, except for CPL and IIF */
5421 env->hflags = hflags;
5422 tlb_flush(env, 1);
5423 #ifdef USE_KVM
5424 if (kvm_allowed) {
5425 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5426 qemu_get_betls(f, &env->kvm_interrupt_bitmap[i]);
5428 qemu_get_be64s(f, &env->tsc);
5429 kvm_load_registers(env);
5431 #endif
5432 return 0;
5435 #elif defined(TARGET_PPC)
5436 void cpu_save(QEMUFile *f, void *opaque)
5440 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5442 return 0;
5445 #elif defined(TARGET_MIPS)
5446 void cpu_save(QEMUFile *f, void *opaque)
5450 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5452 return 0;
5455 #elif defined(TARGET_SPARC)
5456 void cpu_save(QEMUFile *f, void *opaque)
5458 CPUState *env = opaque;
5459 int i;
5460 uint32_t tmp;
5462 for(i = 0; i < 8; i++)
5463 qemu_put_betls(f, &env->gregs[i]);
5464 for(i = 0; i < NWINDOWS * 16; i++)
5465 qemu_put_betls(f, &env->regbase[i]);
5467 /* FPU */
5468 for(i = 0; i < TARGET_FPREGS; i++) {
5469 union {
5470 float32 f;
5471 uint32_t i;
5472 } u;
5473 u.f = env->fpr[i];
5474 qemu_put_be32(f, u.i);
5477 qemu_put_betls(f, &env->pc);
5478 qemu_put_betls(f, &env->npc);
5479 qemu_put_betls(f, &env->y);
5480 tmp = GET_PSR(env);
5481 qemu_put_be32(f, tmp);
5482 qemu_put_betls(f, &env->fsr);
5483 qemu_put_betls(f, &env->tbr);
5484 #ifndef TARGET_SPARC64
5485 qemu_put_be32s(f, &env->wim);
5486 /* MMU */
5487 for(i = 0; i < 16; i++)
5488 qemu_put_be32s(f, &env->mmuregs[i]);
5489 #endif
5492 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5494 CPUState *env = opaque;
5495 int i;
5496 uint32_t tmp;
5498 for(i = 0; i < 8; i++)
5499 qemu_get_betls(f, &env->gregs[i]);
5500 for(i = 0; i < NWINDOWS * 16; i++)
5501 qemu_get_betls(f, &env->regbase[i]);
5503 /* FPU */
5504 for(i = 0; i < TARGET_FPREGS; i++) {
5505 union {
5506 float32 f;
5507 uint32_t i;
5508 } u;
5509 u.i = qemu_get_be32(f);
5510 env->fpr[i] = u.f;
5513 qemu_get_betls(f, &env->pc);
5514 qemu_get_betls(f, &env->npc);
5515 qemu_get_betls(f, &env->y);
5516 tmp = qemu_get_be32(f);
5517 env->cwp = 0; /* needed to ensure that the wrapping registers are
5518 correctly updated */
5519 PUT_PSR(env, tmp);
5520 qemu_get_betls(f, &env->fsr);
5521 qemu_get_betls(f, &env->tbr);
5522 #ifndef TARGET_SPARC64
5523 qemu_get_be32s(f, &env->wim);
5524 /* MMU */
5525 for(i = 0; i < 16; i++)
5526 qemu_get_be32s(f, &env->mmuregs[i]);
5527 #endif
5528 tlb_flush(env, 1);
5529 return 0;
5532 #elif defined(TARGET_ARM)
5534 /* ??? Need to implement these. */
5535 void cpu_save(QEMUFile *f, void *opaque)
5539 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5541 return 0;
5544 #else
5546 #warning No CPU save/restore functions
5548 #endif
5550 /***********************************************************/
5551 /* ram save/restore */
5553 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5555 int v;
5557 v = qemu_get_byte(f);
5558 switch(v) {
5559 case 0:
5560 if (qemu_get_buffer(f, buf, len) != len)
5561 return -EIO;
5562 break;
5563 case 1:
5564 v = qemu_get_byte(f);
5565 memset(buf, v, len);
5566 break;
5567 default:
5568 return -EINVAL;
5570 return 0;
5573 static int ram_load_v1(QEMUFile *f, void *opaque)
5575 int i, ret;
5577 if (qemu_get_be32(f) != phys_ram_size)
5578 return -EINVAL;
5579 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5580 #ifdef USE_KVM
5581 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5582 continue;
5583 #endif
5584 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5585 if (ret)
5586 return ret;
5588 return 0;
5591 #define BDRV_HASH_BLOCK_SIZE 1024
5592 #define IOBUF_SIZE 4096
5593 #define RAM_CBLOCK_MAGIC 0xfabe
5595 typedef struct RamCompressState {
5596 z_stream zstream;
5597 QEMUFile *f;
5598 uint8_t buf[IOBUF_SIZE];
5599 } RamCompressState;
5601 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5603 int ret;
5604 memset(s, 0, sizeof(*s));
5605 s->f = f;
5606 ret = deflateInit2(&s->zstream, 1,
5607 Z_DEFLATED, 15,
5608 9, Z_DEFAULT_STRATEGY);
5609 if (ret != Z_OK)
5610 return -1;
5611 s->zstream.avail_out = IOBUF_SIZE;
5612 s->zstream.next_out = s->buf;
5613 return 0;
5616 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5618 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5619 qemu_put_be16(s->f, len);
5620 qemu_put_buffer(s->f, buf, len);
5623 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5625 int ret;
5627 s->zstream.avail_in = len;
5628 s->zstream.next_in = (uint8_t *)buf;
5629 while (s->zstream.avail_in > 0) {
5630 ret = deflate(&s->zstream, Z_NO_FLUSH);
5631 if (ret != Z_OK)
5632 return -1;
5633 if (s->zstream.avail_out == 0) {
5634 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5635 s->zstream.avail_out = IOBUF_SIZE;
5636 s->zstream.next_out = s->buf;
5639 return 0;
5642 static void ram_compress_close(RamCompressState *s)
5644 int len, ret;
5646 /* compress last bytes */
5647 for(;;) {
5648 ret = deflate(&s->zstream, Z_FINISH);
5649 if (ret == Z_OK || ret == Z_STREAM_END) {
5650 len = IOBUF_SIZE - s->zstream.avail_out;
5651 if (len > 0) {
5652 ram_put_cblock(s, s->buf, len);
5654 s->zstream.avail_out = IOBUF_SIZE;
5655 s->zstream.next_out = s->buf;
5656 if (ret == Z_STREAM_END)
5657 break;
5658 } else {
5659 goto fail;
5662 fail:
5663 deflateEnd(&s->zstream);
5666 typedef struct RamDecompressState {
5667 z_stream zstream;
5668 QEMUFile *f;
5669 uint8_t buf[IOBUF_SIZE];
5670 } RamDecompressState;
5672 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5674 int ret;
5675 memset(s, 0, sizeof(*s));
5676 s->f = f;
5677 ret = inflateInit(&s->zstream);
5678 if (ret != Z_OK)
5679 return -1;
5680 return 0;
5683 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5685 int ret, clen;
5687 s->zstream.avail_out = len;
5688 s->zstream.next_out = buf;
5689 while (s->zstream.avail_out > 0) {
5690 if (s->zstream.avail_in == 0) {
5691 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5692 return -1;
5693 clen = qemu_get_be16(s->f);
5694 if (clen > IOBUF_SIZE)
5695 return -1;
5696 qemu_get_buffer(s->f, s->buf, clen);
5697 s->zstream.avail_in = clen;
5698 s->zstream.next_in = s->buf;
5700 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5701 if (ret != Z_OK && ret != Z_STREAM_END) {
5702 return -1;
5705 return 0;
5708 static void ram_decompress_close(RamDecompressState *s)
5710 inflateEnd(&s->zstream);
5713 static void ram_save_live(QEMUFile *f, void *opaque)
5715 target_ulong addr;
5717 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
5718 #ifdef USE_KVM
5719 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
5720 continue;
5721 #endif
5722 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
5723 qemu_put_be32(f, addr);
5724 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5727 qemu_put_be32(f, 1);
5730 static void ram_save_static(QEMUFile *f, void *opaque)
5732 int i;
5733 RamCompressState s1, *s = &s1;
5734 uint8_t buf[10];
5736 qemu_put_be32(f, phys_ram_size);
5737 if (ram_compress_open(s, f) < 0)
5738 return;
5739 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5740 #ifdef USE_KVM
5741 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5742 continue;
5743 #endif
5744 #if 0
5745 if (tight_savevm_enabled) {
5746 int64_t sector_num;
5747 int j;
5749 /* find if the memory block is available on a virtual
5750 block device */
5751 sector_num = -1;
5752 for(j = 0; j < MAX_DISKS; j++) {
5753 if (bs_table[j]) {
5754 sector_num = bdrv_hash_find(bs_table[j],
5755 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5756 if (sector_num >= 0)
5757 break;
5760 if (j == MAX_DISKS)
5761 goto normal_compress;
5762 buf[0] = 1;
5763 buf[1] = j;
5764 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5765 ram_compress_buf(s, buf, 10);
5766 } else
5767 #endif
5769 // normal_compress:
5770 buf[0] = 0;
5771 ram_compress_buf(s, buf, 1);
5772 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5775 ram_compress_close(s);
5778 static void ram_save(QEMUFile *f, void *opaque)
5780 int in_migration = cpu_physical_memory_get_dirty_tracking();
5782 qemu_put_byte(f, in_migration);
5784 if (in_migration)
5785 ram_save_live(f, opaque);
5786 else
5787 ram_save_static(f, opaque);
5790 static int ram_load_live(QEMUFile *f, void *opaque)
5792 target_ulong addr;
5794 do {
5795 addr = qemu_get_be32(f);
5796 if (addr == 1)
5797 break;
5799 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5800 } while (1);
5802 return 0;
5805 static int ram_load_static(QEMUFile *f, void *opaque)
5807 RamDecompressState s1, *s = &s1;
5808 uint8_t buf[10];
5809 int i;
5811 if (qemu_get_be32(f) != phys_ram_size)
5812 return -EINVAL;
5813 if (ram_decompress_open(s, f) < 0)
5814 return -EINVAL;
5815 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5816 #ifdef USE_KVM
5817 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5818 continue;
5819 #endif
5820 if (ram_decompress_buf(s, buf, 1) < 0) {
5821 fprintf(stderr, "Error while reading ram block header\n");
5822 goto error;
5824 if (buf[0] == 0) {
5825 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5826 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5827 goto error;
5829 } else
5830 #if 0
5831 if (buf[0] == 1) {
5832 int bs_index;
5833 int64_t sector_num;
5835 ram_decompress_buf(s, buf + 1, 9);
5836 bs_index = buf[1];
5837 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5838 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5839 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5840 goto error;
5842 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5843 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5844 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5845 bs_index, sector_num);
5846 goto error;
5848 } else
5849 #endif
5851 error:
5852 printf("Error block header\n");
5853 return -EINVAL;
5856 ram_decompress_close(s);
5857 return 0;
5860 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5862 int ret;
5864 switch (version_id) {
5865 case 1:
5866 ret = ram_load_v1(f, opaque);
5867 break;
5868 case 3:
5869 if (qemu_get_byte(f)) {
5870 ret = ram_load_live(f, opaque);
5871 break;
5873 case 2:
5874 ret = ram_load_static(f, opaque);
5875 break;
5876 default:
5877 ret = -EINVAL;
5878 break;
5881 return ret;
5884 /***********************************************************/
5885 /* bottom halves (can be seen as timers which expire ASAP) */
5887 struct QEMUBH {
5888 QEMUBHFunc *cb;
5889 void *opaque;
5890 int scheduled;
5891 QEMUBH *next;
5894 static QEMUBH *first_bh = NULL;
5896 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5898 QEMUBH *bh;
5899 bh = qemu_mallocz(sizeof(QEMUBH));
5900 if (!bh)
5901 return NULL;
5902 bh->cb = cb;
5903 bh->opaque = opaque;
5904 return bh;
5907 int qemu_bh_poll(void)
5909 QEMUBH *bh, **pbh;
5910 int ret;
5912 ret = 0;
5913 for(;;) {
5914 pbh = &first_bh;
5915 bh = *pbh;
5916 if (!bh)
5917 break;
5918 ret = 1;
5919 *pbh = bh->next;
5920 bh->scheduled = 0;
5921 bh->cb(bh->opaque);
5923 return ret;
5926 void qemu_bh_schedule(QEMUBH *bh)
5928 CPUState *env = cpu_single_env;
5929 if (bh->scheduled)
5930 return;
5931 bh->scheduled = 1;
5932 bh->next = first_bh;
5933 first_bh = bh;
5935 /* stop the currently executing CPU to execute the BH ASAP */
5936 if (env) {
5937 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5941 void qemu_bh_cancel(QEMUBH *bh)
5943 QEMUBH **pbh;
5944 if (bh->scheduled) {
5945 pbh = &first_bh;
5946 while (*pbh != bh)
5947 pbh = &(*pbh)->next;
5948 *pbh = bh->next;
5949 bh->scheduled = 0;
5953 void qemu_bh_delete(QEMUBH *bh)
5955 qemu_bh_cancel(bh);
5956 qemu_free(bh);
5959 /***********************************************************/
5960 /* machine registration */
5962 QEMUMachine *first_machine = NULL;
5964 int qemu_register_machine(QEMUMachine *m)
5966 QEMUMachine **pm;
5967 pm = &first_machine;
5968 while (*pm != NULL)
5969 pm = &(*pm)->next;
5970 m->next = NULL;
5971 *pm = m;
5972 return 0;
5975 QEMUMachine *find_machine(const char *name)
5977 QEMUMachine *m;
5979 for(m = first_machine; m != NULL; m = m->next) {
5980 if (!strcmp(m->name, name))
5981 return m;
5983 return NULL;
5986 /***********************************************************/
5987 /* main execution loop */
5989 void gui_update(void *opaque)
5991 display_state.dpy_refresh(&display_state);
5992 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5995 struct vm_change_state_entry {
5996 VMChangeStateHandler *cb;
5997 void *opaque;
5998 LIST_ENTRY (vm_change_state_entry) entries;
6001 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6003 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6004 void *opaque)
6006 VMChangeStateEntry *e;
6008 e = qemu_mallocz(sizeof (*e));
6009 if (!e)
6010 return NULL;
6012 e->cb = cb;
6013 e->opaque = opaque;
6014 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6015 return e;
6018 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6020 LIST_REMOVE (e, entries);
6021 qemu_free (e);
6024 static void vm_state_notify(int running)
6026 VMChangeStateEntry *e;
6028 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6029 e->cb(e->opaque, running);
6033 /* XXX: support several handlers */
6034 static VMStopHandler *vm_stop_cb;
6035 static void *vm_stop_opaque;
6037 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6039 vm_stop_cb = cb;
6040 vm_stop_opaque = opaque;
6041 return 0;
6044 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6046 vm_stop_cb = NULL;
6049 void vm_start(void)
6051 if (!vm_running) {
6052 cpu_enable_ticks();
6053 vm_running = 1;
6054 vm_state_notify(1);
6058 void vm_stop(int reason)
6060 if (vm_running) {
6061 cpu_disable_ticks();
6062 vm_running = 0;
6063 if (reason != 0) {
6064 if (vm_stop_cb) {
6065 vm_stop_cb(vm_stop_opaque, reason);
6068 vm_state_notify(0);
6072 /* reset/shutdown handler */
6074 typedef struct QEMUResetEntry {
6075 QEMUResetHandler *func;
6076 void *opaque;
6077 struct QEMUResetEntry *next;
6078 } QEMUResetEntry;
6080 static QEMUResetEntry *first_reset_entry;
6081 static int reset_requested;
6082 static int shutdown_requested;
6083 static int powerdown_requested;
6085 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6087 QEMUResetEntry **pre, *re;
6089 pre = &first_reset_entry;
6090 while (*pre != NULL)
6091 pre = &(*pre)->next;
6092 re = qemu_mallocz(sizeof(QEMUResetEntry));
6093 re->func = func;
6094 re->opaque = opaque;
6095 re->next = NULL;
6096 *pre = re;
6099 static void qemu_system_reset(void)
6101 QEMUResetEntry *re;
6103 /* reset all devices */
6104 for(re = first_reset_entry; re != NULL; re = re->next) {
6105 re->func(re->opaque);
6109 void qemu_system_reset_request(void)
6111 if (no_reboot) {
6112 shutdown_requested = 1;
6113 } else {
6114 reset_requested = 1;
6116 if (cpu_single_env)
6117 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6120 void qemu_system_shutdown_request(void)
6122 shutdown_requested = 1;
6123 if (cpu_single_env)
6124 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6127 void qemu_system_powerdown_request(void)
6129 powerdown_requested = 1;
6130 if (cpu_single_env)
6131 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6134 void main_loop_wait(int timeout)
6136 IOHandlerRecord *ioh;
6137 fd_set rfds, wfds, xfds;
6138 int ret, nfds;
6139 struct timeval tv;
6140 PollingEntry *pe;
6143 /* XXX: need to suppress polling by better using win32 events */
6144 ret = 0;
6145 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6146 ret |= pe->func(pe->opaque);
6148 #ifdef _WIN32
6149 if (ret == 0 && timeout > 0) {
6150 int err;
6151 WaitObjects *w = &wait_objects;
6153 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6154 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6155 if (w->func[ret - WAIT_OBJECT_0])
6156 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6157 } else if (ret == WAIT_TIMEOUT) {
6158 } else {
6159 err = GetLastError();
6160 fprintf(stderr, "Wait error %d %d\n", ret, err);
6163 #endif
6164 /* poll any events */
6165 /* XXX: separate device handlers from system ones */
6166 nfds = -1;
6167 FD_ZERO(&rfds);
6168 FD_ZERO(&wfds);
6169 FD_ZERO(&xfds);
6170 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6171 if (ioh->deleted)
6172 continue;
6173 if (ioh->fd_read &&
6174 (!ioh->fd_read_poll ||
6175 ioh->fd_read_poll(ioh->opaque) != 0)) {
6176 FD_SET(ioh->fd, &rfds);
6177 if (ioh->fd > nfds)
6178 nfds = ioh->fd;
6180 if (ioh->fd_write) {
6181 FD_SET(ioh->fd, &wfds);
6182 if (ioh->fd > nfds)
6183 nfds = ioh->fd;
6187 tv.tv_sec = 0;
6188 #ifdef _WIN32
6189 tv.tv_usec = 0;
6190 #else
6191 tv.tv_usec = timeout * 1000;
6192 #endif
6193 #if defined(CONFIG_SLIRP)
6194 if (slirp_inited) {
6195 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6197 #endif
6198 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6199 if (ret > 0) {
6200 IOHandlerRecord **pioh;
6202 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6203 if (ioh->deleted)
6204 continue;
6205 if (FD_ISSET(ioh->fd, &rfds)) {
6206 ioh->fd_read(ioh->opaque);
6208 if (FD_ISSET(ioh->fd, &wfds)) {
6209 ioh->fd_write(ioh->opaque);
6213 /* remove deleted IO handlers */
6214 pioh = &first_io_handler;
6215 while (*pioh) {
6216 ioh = *pioh;
6217 if (ioh->deleted) {
6218 *pioh = ioh->next;
6219 qemu_free(ioh);
6220 } else
6221 pioh = &ioh->next;
6224 #if defined(CONFIG_SLIRP)
6225 if (slirp_inited) {
6226 if (ret < 0) {
6227 FD_ZERO(&rfds);
6228 FD_ZERO(&wfds);
6229 FD_ZERO(&xfds);
6231 slirp_select_poll(&rfds, &wfds, &xfds);
6233 #endif
6234 qemu_aio_poll();
6235 qemu_bh_poll();
6237 if (vm_running) {
6238 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6239 qemu_get_clock(vm_clock));
6240 /* run dma transfers, if any */
6241 DMA_run();
6244 /* real time timers */
6245 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6246 qemu_get_clock(rt_clock));
6249 static CPUState *cur_cpu;
6251 int main_loop(void)
6253 int ret, timeout;
6254 #ifdef CONFIG_PROFILER
6255 int64_t ti;
6256 #endif
6257 CPUState *env;
6259 cur_cpu = first_cpu;
6260 for(;;) {
6261 if (vm_running) {
6263 env = cur_cpu;
6264 for(;;) {
6265 /* get next cpu */
6266 env = env->next_cpu;
6267 if (!env)
6268 env = first_cpu;
6269 #ifdef CONFIG_PROFILER
6270 ti = profile_getclock();
6271 #endif
6272 ret = cpu_exec(env);
6273 #ifdef CONFIG_PROFILER
6274 qemu_time += profile_getclock() - ti;
6275 #endif
6276 if (ret != EXCP_HALTED)
6277 break;
6278 /* all CPUs are halted ? */
6279 if (env == cur_cpu) {
6280 ret = EXCP_HLT;
6281 break;
6284 cur_cpu = env;
6286 if (shutdown_requested) {
6287 ret = EXCP_INTERRUPT;
6288 break;
6290 if (reset_requested) {
6291 reset_requested = 0;
6292 qemu_system_reset();
6293 #ifdef USE_KVM
6294 if (kvm_allowed)
6295 kvm_load_registers(env);
6296 #endif
6297 ret = EXCP_INTERRUPT;
6299 if (powerdown_requested) {
6300 powerdown_requested = 0;
6301 qemu_system_powerdown();
6302 ret = EXCP_INTERRUPT;
6304 if (ret == EXCP_DEBUG) {
6305 vm_stop(EXCP_DEBUG);
6307 /* if hlt instruction, we wait until the next IRQ */
6308 /* XXX: use timeout computed from timers */
6309 if (ret == EXCP_HLT)
6310 timeout = 10;
6311 else
6312 timeout = 0;
6313 } else {
6314 timeout = 10;
6316 #ifdef CONFIG_PROFILER
6317 ti = profile_getclock();
6318 #endif
6319 main_loop_wait(timeout);
6320 #ifdef CONFIG_PROFILER
6321 dev_time += profile_getclock() - ti;
6322 #endif
6324 cpu_disable_ticks();
6325 return ret;
6328 void help(void)
6330 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6331 "usage: %s [options] [disk_image]\n"
6332 "\n"
6333 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6334 "\n"
6335 "Standard options:\n"
6336 "-M machine select emulated machine (-M ? for list)\n"
6337 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6338 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6339 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6340 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6341 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6342 "-snapshot write to temporary files instead of disk image files\n"
6343 #ifdef CONFIG_SDL
6344 "-no-quit disable SDL window close capability\n"
6345 #endif
6346 #ifdef TARGET_I386
6347 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6348 #endif
6349 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6350 "-smp n set the number of CPUs to 'n' [default=1]\n"
6351 "-nographic disable graphical output and redirect serial I/Os to console\n"
6352 #ifndef _WIN32
6353 "-k language use keyboard layout (for example \"fr\" for French)\n"
6354 #endif
6355 #ifdef HAS_AUDIO
6356 "-audio-help print list of audio drivers and their options\n"
6357 "-soundhw c1,... enable audio support\n"
6358 " and only specified sound cards (comma separated list)\n"
6359 " use -soundhw ? to get the list of supported cards\n"
6360 " use -soundhw all to enable all of them\n"
6361 #endif
6362 "-localtime set the real time clock to local time [default=utc]\n"
6363 "-full-screen start in full screen\n"
6364 #ifdef TARGET_I386
6365 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6366 #endif
6367 "-usb enable the USB driver (will be the default soon)\n"
6368 "-usbdevice name add the host or guest USB device 'name'\n"
6369 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6370 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6371 #endif
6372 "\n"
6373 "Network options:\n"
6374 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6375 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6376 #ifdef CONFIG_SLIRP
6377 "-net user[,vlan=n][,hostname=host]\n"
6378 " connect the user mode network stack to VLAN 'n' and send\n"
6379 " hostname 'host' to DHCP clients\n"
6380 #endif
6381 #ifdef _WIN32
6382 "-net tap[,vlan=n],ifname=name\n"
6383 " connect the host TAP network interface to VLAN 'n'\n"
6384 #else
6385 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6386 " connect the host TAP network interface to VLAN 'n' and use\n"
6387 " the network script 'file' (default=%s);\n"
6388 " use 'script=no' to disable script execution;\n"
6389 " use 'fd=h' to connect to an already opened TAP interface\n"
6390 #endif
6391 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6392 " connect the vlan 'n' to another VLAN using a socket connection\n"
6393 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6394 " connect the vlan 'n' to multicast maddr and port\n"
6395 "-net none use it alone to have zero network devices; if no -net option\n"
6396 " is provided, the default is '-net nic -net user'\n"
6397 "\n"
6398 #ifdef CONFIG_SLIRP
6399 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6400 #ifndef _WIN32
6401 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6402 #endif
6403 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6404 " redirect TCP or UDP connections from host to guest [-net user]\n"
6405 #endif
6406 "\n"
6407 "Linux boot specific:\n"
6408 "-kernel bzImage use 'bzImage' as kernel image\n"
6409 "-append cmdline use 'cmdline' as kernel command line\n"
6410 "-initrd file use 'file' as initial ram disk\n"
6411 "\n"
6412 "Debug/Expert options:\n"
6413 "-monitor dev redirect the monitor to char device 'dev'\n"
6414 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6415 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
6416 "-serial dev redirect the serial port to char device 'dev'\n"
6417 "-parallel dev redirect the parallel port to char device 'dev'\n"
6418 "-pidfile file Write PID to 'file'\n"
6419 "-S freeze CPU at startup (use 'c' to start execution)\n"
6420 "-s wait gdb connection to port %d\n"
6421 "-p port change gdb connection port\n"
6422 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6423 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6424 " translation (t=none or lba) (usually qemu can guess them)\n"
6425 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6426 #ifdef USE_KQEMU
6427 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6428 "-no-kqemu disable KQEMU kernel module usage\n"
6429 #endif
6430 #ifdef USE_KVM
6431 "-no-kvm disable KVM hardware virtualization\n"
6432 #endif
6433 #ifdef USE_CODE_COPY
6434 "-no-code-copy disable code copy acceleration\n"
6435 #endif
6436 #ifdef TARGET_I386
6437 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6438 " (default is CL-GD5446 PCI VGA)\n"
6439 "-no-acpi disable ACPI\n"
6440 #endif
6441 "-no-reboot exit instead of rebooting\n"
6442 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6443 "-vnc display start a VNC server on display\n"
6444 #ifndef _WIN32
6445 "-daemonize daemonize QEMU after initializing\n"
6446 #endif
6447 "-no-tdf do not inject timer interrupts that got lost\n"
6448 #if defined(__linux__)
6449 "-no-rtc don't use /dev/rtc for timer alarm (do use gettimeofday)\n"
6450 #endif
6451 "-option-rom rom load a file, rom, into the option ROM space\n"
6452 "\n"
6453 "During emulation, the following keys are useful:\n"
6454 "ctrl-alt-f toggle full screen\n"
6455 "ctrl-alt-n switch to virtual console 'n'\n"
6456 "ctrl-alt toggle mouse and keyboard grab\n"
6457 "\n"
6458 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6460 "qemu",
6461 DEFAULT_RAM_SIZE,
6462 #ifndef _WIN32
6463 DEFAULT_NETWORK_SCRIPT,
6464 #endif
6465 DEFAULT_GDBSTUB_PORT,
6466 "/tmp/qemu.log");
6467 exit(1);
6470 #define HAS_ARG 0x0001
6472 enum {
6473 QEMU_OPTION_h,
6475 QEMU_OPTION_M,
6476 QEMU_OPTION_fda,
6477 QEMU_OPTION_fdb,
6478 QEMU_OPTION_hda,
6479 QEMU_OPTION_hdb,
6480 QEMU_OPTION_hdc,
6481 QEMU_OPTION_hdd,
6482 QEMU_OPTION_cdrom,
6483 QEMU_OPTION_boot,
6484 QEMU_OPTION_snapshot,
6485 #ifdef TARGET_I386
6486 QEMU_OPTION_no_fd_bootchk,
6487 #endif
6488 QEMU_OPTION_m,
6489 QEMU_OPTION_nographic,
6490 #ifdef HAS_AUDIO
6491 QEMU_OPTION_audio_help,
6492 QEMU_OPTION_soundhw,
6493 #endif
6495 QEMU_OPTION_net,
6496 QEMU_OPTION_tftp,
6497 QEMU_OPTION_smb,
6498 QEMU_OPTION_redir,
6500 QEMU_OPTION_kernel,
6501 QEMU_OPTION_append,
6502 QEMU_OPTION_initrd,
6504 QEMU_OPTION_S,
6505 QEMU_OPTION_s,
6506 QEMU_OPTION_p,
6507 QEMU_OPTION_d,
6508 QEMU_OPTION_hdachs,
6509 QEMU_OPTION_L,
6510 QEMU_OPTION_no_code_copy,
6511 QEMU_OPTION_k,
6512 QEMU_OPTION_localtime,
6513 QEMU_OPTION_cirrusvga,
6514 QEMU_OPTION_g,
6515 QEMU_OPTION_std_vga,
6516 QEMU_OPTION_monitor,
6517 QEMU_OPTION_balloon,
6518 QEMU_OPTION_vmchannel,
6519 QEMU_OPTION_serial,
6520 QEMU_OPTION_parallel,
6521 QEMU_OPTION_loadvm,
6522 QEMU_OPTION_full_screen,
6523 QEMU_OPTION_no_quit,
6524 QEMU_OPTION_pidfile,
6525 QEMU_OPTION_no_kqemu,
6526 QEMU_OPTION_kernel_kqemu,
6527 QEMU_OPTION_win2k_hack,
6528 QEMU_OPTION_usb,
6529 QEMU_OPTION_usbdevice,
6530 QEMU_OPTION_smp,
6531 QEMU_OPTION_vnc,
6532 QEMU_OPTION_no_acpi,
6533 QEMU_OPTION_no_kvm,
6534 QEMU_OPTION_no_reboot,
6535 QEMU_OPTION_daemonize,
6536 QEMU_OPTION_option_rom,
6537 QEMU_OPTION_semihosting,
6538 QEMU_OPTION_incoming,
6539 QEMU_OPTION_tdf,
6540 #if defined(__linux__)
6541 QEMU_OPTION_no_rtc,
6542 #endif
6543 QEMU_OPTION_cpu_vendor,
6546 typedef struct QEMUOption {
6547 const char *name;
6548 int flags;
6549 int index;
6550 } QEMUOption;
6552 const QEMUOption qemu_options[] = {
6553 { "h", 0, QEMU_OPTION_h },
6554 { "help", 0, QEMU_OPTION_h },
6556 { "M", HAS_ARG, QEMU_OPTION_M },
6557 { "fda", HAS_ARG, QEMU_OPTION_fda },
6558 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6559 { "hda", HAS_ARG, QEMU_OPTION_hda },
6560 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6561 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6562 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6563 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6564 { "boot", HAS_ARG, QEMU_OPTION_boot },
6565 { "snapshot", 0, QEMU_OPTION_snapshot },
6566 #ifdef TARGET_I386
6567 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6568 #endif
6569 { "m", HAS_ARG, QEMU_OPTION_m },
6570 { "nographic", 0, QEMU_OPTION_nographic },
6571 { "k", HAS_ARG, QEMU_OPTION_k },
6572 #ifdef HAS_AUDIO
6573 { "audio-help", 0, QEMU_OPTION_audio_help },
6574 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6575 #endif
6577 { "net", HAS_ARG, QEMU_OPTION_net},
6578 #ifdef CONFIG_SLIRP
6579 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6580 #ifndef _WIN32
6581 { "smb", HAS_ARG, QEMU_OPTION_smb },
6582 #endif
6583 { "redir", HAS_ARG, QEMU_OPTION_redir },
6584 #endif
6586 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6587 { "append", HAS_ARG, QEMU_OPTION_append },
6588 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6590 { "S", 0, QEMU_OPTION_S },
6591 { "s", 0, QEMU_OPTION_s },
6592 { "p", HAS_ARG, QEMU_OPTION_p },
6593 { "d", HAS_ARG, QEMU_OPTION_d },
6594 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6595 { "L", HAS_ARG, QEMU_OPTION_L },
6596 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6597 #ifdef USE_KQEMU
6598 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6599 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6600 #endif
6601 #ifdef USE_KVM
6602 { "no-kvm", 0, QEMU_OPTION_no_kvm },
6603 #endif
6604 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6605 { "g", 1, QEMU_OPTION_g },
6606 #endif
6607 { "localtime", 0, QEMU_OPTION_localtime },
6608 { "std-vga", 0, QEMU_OPTION_std_vga },
6609 { "monitor", 1, QEMU_OPTION_monitor },
6610 { "balloon", 1, QEMU_OPTION_balloon },
6611 { "vmchannel", 1, QEMU_OPTION_vmchannel },
6612 { "serial", 1, QEMU_OPTION_serial },
6613 { "parallel", 1, QEMU_OPTION_parallel },
6614 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6615 { "incoming", 1, QEMU_OPTION_incoming },
6616 { "full-screen", 0, QEMU_OPTION_full_screen },
6617 #ifdef CONFIG_SDL
6618 { "no-quit", 0, QEMU_OPTION_no_quit },
6619 #endif
6620 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6621 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6622 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6623 { "smp", HAS_ARG, QEMU_OPTION_smp },
6624 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6626 /* temporary options */
6627 { "usb", 0, QEMU_OPTION_usb },
6628 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6629 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6630 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6631 { "daemonize", 0, QEMU_OPTION_daemonize },
6632 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6633 #if defined(TARGET_ARM)
6634 { "semihosting", 0, QEMU_OPTION_semihosting },
6635 #endif
6636 { "no-tdf", 0, QEMU_OPTION_tdf }, /* no time drift fix */
6637 #if defined(__linux__)
6638 { "no-rtc", 0, QEMU_OPTION_no_rtc },
6639 #endif
6640 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
6641 { NULL },
6644 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6646 /* this stack is only used during signal handling */
6647 #define SIGNAL_STACK_SIZE 32768
6649 static uint8_t *signal_stack;
6651 #endif
6653 /* password input */
6655 static BlockDriverState *get_bdrv(int index)
6657 BlockDriverState *bs;
6659 if (index < 4) {
6660 bs = bs_table[index];
6661 } else if (index < 6) {
6662 bs = fd_table[index - 4];
6663 } else {
6664 bs = NULL;
6666 return bs;
6669 static void read_passwords(void)
6671 BlockDriverState *bs;
6672 int i, j;
6673 char password[256];
6675 for(i = 0; i < 6; i++) {
6676 bs = get_bdrv(i);
6677 if (bs && bdrv_is_encrypted(bs)) {
6678 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6679 for(j = 0; j < 3; j++) {
6680 monitor_readline("Password: ",
6681 1, password, sizeof(password));
6682 if (bdrv_set_key(bs, password) == 0)
6683 break;
6684 term_printf("invalid password\n");
6690 /* XXX: currently we cannot use simultaneously different CPUs */
6691 void register_machines(void)
6693 #if defined(TARGET_I386)
6694 qemu_register_machine(&pc_machine);
6695 qemu_register_machine(&isapc_machine);
6696 #elif defined(TARGET_PPC)
6697 qemu_register_machine(&heathrow_machine);
6698 qemu_register_machine(&core99_machine);
6699 qemu_register_machine(&prep_machine);
6700 #elif defined(TARGET_MIPS)
6701 qemu_register_machine(&mips_machine);
6702 qemu_register_machine(&mips_malta_machine);
6703 #elif defined(TARGET_SPARC)
6704 #ifdef TARGET_SPARC64
6705 qemu_register_machine(&sun4u_machine);
6706 #else
6707 qemu_register_machine(&sun4m_machine);
6708 #endif
6709 #elif defined(TARGET_ARM)
6710 qemu_register_machine(&integratorcp926_machine);
6711 qemu_register_machine(&integratorcp1026_machine);
6712 qemu_register_machine(&versatilepb_machine);
6713 qemu_register_machine(&versatileab_machine);
6714 qemu_register_machine(&realview_machine);
6715 #elif defined(TARGET_SH4)
6716 qemu_register_machine(&shix_machine);
6717 #else
6718 #error unsupported CPU
6719 #endif
6722 #ifdef HAS_AUDIO
6723 struct soundhw soundhw[] = {
6724 #ifdef TARGET_I386
6726 "pcspk",
6727 "PC speaker",
6730 { .init_isa = pcspk_audio_init }
6732 #endif
6734 "sb16",
6735 "Creative Sound Blaster 16",
6738 { .init_isa = SB16_init }
6741 #ifdef CONFIG_ADLIB
6743 "adlib",
6744 #ifdef HAS_YMF262
6745 "Yamaha YMF262 (OPL3)",
6746 #else
6747 "Yamaha YM3812 (OPL2)",
6748 #endif
6751 { .init_isa = Adlib_init }
6753 #endif
6755 #ifdef CONFIG_GUS
6757 "gus",
6758 "Gravis Ultrasound GF1",
6761 { .init_isa = GUS_init }
6763 #endif
6766 "es1370",
6767 "ENSONIQ AudioPCI ES1370",
6770 { .init_pci = es1370_init }
6773 { NULL, NULL, 0, 0, { NULL } }
6776 static void select_soundhw (const char *optarg)
6778 struct soundhw *c;
6780 if (*optarg == '?') {
6781 show_valid_cards:
6783 printf ("Valid sound card names (comma separated):\n");
6784 for (c = soundhw; c->name; ++c) {
6785 printf ("%-11s %s\n", c->name, c->descr);
6787 printf ("\n-soundhw all will enable all of the above\n");
6788 exit (*optarg != '?');
6790 else {
6791 size_t l;
6792 const char *p;
6793 char *e;
6794 int bad_card = 0;
6796 if (!strcmp (optarg, "all")) {
6797 for (c = soundhw; c->name; ++c) {
6798 c->enabled = 1;
6800 return;
6803 p = optarg;
6804 while (*p) {
6805 e = strchr (p, ',');
6806 l = !e ? strlen (p) : (size_t) (e - p);
6808 for (c = soundhw; c->name; ++c) {
6809 if (!strncmp (c->name, p, l)) {
6810 c->enabled = 1;
6811 break;
6815 if (!c->name) {
6816 if (l > 80) {
6817 fprintf (stderr,
6818 "Unknown sound card name (too big to show)\n");
6820 else {
6821 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6822 (int) l, p);
6824 bad_card = 1;
6826 p += l + (e != NULL);
6829 if (bad_card)
6830 goto show_valid_cards;
6833 #endif
6835 #ifdef _WIN32
6836 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6838 exit(STATUS_CONTROL_C_EXIT);
6839 return TRUE;
6841 #endif
6843 #define MAX_NET_CLIENTS 32
6845 static int saved_argc;
6846 static char **saved_argv;
6848 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
6850 *argc = saved_argc;
6851 *argv = saved_argv;
6852 *opt_daemonize = daemonize;
6853 *opt_incoming = incoming;
6856 int main(int argc, char **argv)
6858 #ifdef CONFIG_GDBSTUB
6859 int use_gdbstub, gdbstub_port;
6860 #endif
6861 int i, cdrom_index;
6862 int snapshot, linux_boot;
6863 const char *initrd_filename;
6864 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6865 const char *kernel_filename, *kernel_cmdline;
6866 DisplayState *ds = &display_state;
6867 int cyls, heads, secs, translation;
6868 char net_clients[MAX_NET_CLIENTS][256];
6869 int nb_net_clients;
6870 int optind;
6871 const char *r, *optarg;
6872 CharDriverState *monitor_hd;
6873 char monitor_device[128];
6874 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
6875 int vmchannel_device_index;
6876 char serial_devices[MAX_SERIAL_PORTS][128];
6877 int serial_device_index;
6878 char parallel_devices[MAX_PARALLEL_PORTS][128];
6879 int parallel_device_index;
6880 const char *loadvm = NULL;
6881 QEMUMachine *machine;
6882 char usb_devices[MAX_USB_CMDLINE][128];
6883 int usb_devices_index;
6884 int fds[2];
6886 saved_argc = argc;
6887 saved_argv = argv;
6889 LIST_INIT (&vm_change_state_head);
6890 #ifndef _WIN32
6892 struct sigaction act;
6893 sigfillset(&act.sa_mask);
6894 act.sa_flags = 0;
6895 act.sa_handler = SIG_IGN;
6896 sigaction(SIGPIPE, &act, NULL);
6898 #else
6899 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6900 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6901 QEMU to run on a single CPU */
6903 HANDLE h;
6904 DWORD mask, smask;
6905 int i;
6906 h = GetCurrentProcess();
6907 if (GetProcessAffinityMask(h, &mask, &smask)) {
6908 for(i = 0; i < 32; i++) {
6909 if (mask & (1 << i))
6910 break;
6912 if (i != 32) {
6913 mask = 1 << i;
6914 SetProcessAffinityMask(h, mask);
6918 #endif
6920 register_machines();
6921 machine = first_machine;
6922 initrd_filename = NULL;
6923 for(i = 0; i < MAX_FD; i++)
6924 fd_filename[i] = NULL;
6925 for(i = 0; i < MAX_DISKS; i++)
6926 hd_filename[i] = NULL;
6927 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6928 vga_ram_size = VGA_RAM_SIZE;
6929 bios_size = BIOS_SIZE;
6930 #ifdef CONFIG_GDBSTUB
6931 use_gdbstub = 0;
6932 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6933 #endif
6934 snapshot = 0;
6935 nographic = 0;
6936 kernel_filename = NULL;
6937 kernel_cmdline = "";
6938 #ifdef TARGET_PPC
6939 cdrom_index = 1;
6940 #else
6941 cdrom_index = 2;
6942 #endif
6943 cyls = heads = secs = 0;
6944 translation = BIOS_ATA_TRANSLATION_AUTO;
6945 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6947 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
6948 vmchannel_devices[i][0] = '\0';
6949 vmchannel_device_index = 0;
6951 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6952 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6953 serial_devices[i][0] = '\0';
6954 serial_device_index = 0;
6956 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6957 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6958 parallel_devices[i][0] = '\0';
6959 parallel_device_index = 0;
6961 usb_devices_index = 0;
6963 nb_net_clients = 0;
6965 nb_nics = 0;
6966 /* default mac address of the first network interface */
6968 optind = 1;
6969 for(;;) {
6970 if (optind >= argc)
6971 break;
6972 r = argv[optind];
6973 if (r[0] != '-') {
6974 hd_filename[0] = argv[optind++];
6975 } else {
6976 const QEMUOption *popt;
6978 optind++;
6979 /* Treat --foo the same as -foo. */
6980 if (r[1] == '-')
6981 r++;
6982 popt = qemu_options;
6983 for(;;) {
6984 if (!popt->name) {
6985 fprintf(stderr, "%s: invalid option -- '%s'\n",
6986 argv[0], r);
6987 exit(1);
6989 if (!strcmp(popt->name, r + 1))
6990 break;
6991 popt++;
6993 if (popt->flags & HAS_ARG) {
6994 if (optind >= argc) {
6995 fprintf(stderr, "%s: option '%s' requires an argument\n",
6996 argv[0], r);
6997 exit(1);
6999 optarg = argv[optind++];
7000 } else {
7001 optarg = NULL;
7004 switch(popt->index) {
7005 case QEMU_OPTION_M:
7006 machine = find_machine(optarg);
7007 if (!machine) {
7008 QEMUMachine *m;
7009 printf("Supported machines are:\n");
7010 for(m = first_machine; m != NULL; m = m->next) {
7011 printf("%-10s %s%s\n",
7012 m->name, m->desc,
7013 m == first_machine ? " (default)" : "");
7015 exit(1);
7017 break;
7018 case QEMU_OPTION_initrd:
7019 initrd_filename = optarg;
7020 break;
7021 case QEMU_OPTION_hda:
7022 case QEMU_OPTION_hdb:
7023 case QEMU_OPTION_hdc:
7024 case QEMU_OPTION_hdd:
7026 int hd_index;
7027 hd_index = popt->index - QEMU_OPTION_hda;
7028 hd_filename[hd_index] = optarg;
7029 if (hd_index == cdrom_index)
7030 cdrom_index = -1;
7032 break;
7033 case QEMU_OPTION_snapshot:
7034 snapshot = 1;
7035 break;
7036 case QEMU_OPTION_hdachs:
7038 const char *p;
7039 p = optarg;
7040 cyls = strtol(p, (char **)&p, 0);
7041 if (cyls < 1 || cyls > 16383)
7042 goto chs_fail;
7043 if (*p != ',')
7044 goto chs_fail;
7045 p++;
7046 heads = strtol(p, (char **)&p, 0);
7047 if (heads < 1 || heads > 16)
7048 goto chs_fail;
7049 if (*p != ',')
7050 goto chs_fail;
7051 p++;
7052 secs = strtol(p, (char **)&p, 0);
7053 if (secs < 1 || secs > 63)
7054 goto chs_fail;
7055 if (*p == ',') {
7056 p++;
7057 if (!strcmp(p, "none"))
7058 translation = BIOS_ATA_TRANSLATION_NONE;
7059 else if (!strcmp(p, "lba"))
7060 translation = BIOS_ATA_TRANSLATION_LBA;
7061 else if (!strcmp(p, "auto"))
7062 translation = BIOS_ATA_TRANSLATION_AUTO;
7063 else
7064 goto chs_fail;
7065 } else if (*p != '\0') {
7066 chs_fail:
7067 fprintf(stderr, "qemu: invalid physical CHS format\n");
7068 exit(1);
7071 break;
7072 case QEMU_OPTION_nographic:
7073 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7074 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7075 nographic = 1;
7076 break;
7077 case QEMU_OPTION_kernel:
7078 kernel_filename = optarg;
7079 break;
7080 case QEMU_OPTION_append:
7081 kernel_cmdline = optarg;
7082 break;
7083 case QEMU_OPTION_cdrom:
7084 if (cdrom_index >= 0) {
7085 hd_filename[cdrom_index] = optarg;
7087 break;
7088 case QEMU_OPTION_boot:
7089 boot_device = optarg[0];
7090 if (boot_device != 'a' &&
7091 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7092 // Network boot
7093 boot_device != 'n' &&
7094 #endif
7095 boot_device != 'c' && boot_device != 'd') {
7096 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7097 exit(1);
7099 break;
7100 case QEMU_OPTION_fda:
7101 fd_filename[0] = optarg;
7102 break;
7103 case QEMU_OPTION_fdb:
7104 fd_filename[1] = optarg;
7105 break;
7106 #ifdef TARGET_I386
7107 case QEMU_OPTION_no_fd_bootchk:
7108 fd_bootchk = 0;
7109 break;
7110 #endif
7111 case QEMU_OPTION_no_code_copy:
7112 code_copy_enabled = 0;
7113 break;
7114 case QEMU_OPTION_net:
7115 if (nb_net_clients >= MAX_NET_CLIENTS) {
7116 fprintf(stderr, "qemu: too many network clients\n");
7117 exit(1);
7119 pstrcpy(net_clients[nb_net_clients],
7120 sizeof(net_clients[0]),
7121 optarg);
7122 nb_net_clients++;
7123 break;
7124 #ifdef CONFIG_SLIRP
7125 case QEMU_OPTION_tftp:
7126 tftp_prefix = optarg;
7127 break;
7128 #ifndef _WIN32
7129 case QEMU_OPTION_smb:
7130 net_slirp_smb(optarg);
7131 break;
7132 #endif
7133 case QEMU_OPTION_redir:
7134 net_slirp_redir(optarg);
7135 break;
7136 #endif
7137 #ifdef HAS_AUDIO
7138 case QEMU_OPTION_audio_help:
7139 AUD_help ();
7140 exit (0);
7141 break;
7142 case QEMU_OPTION_soundhw:
7143 select_soundhw (optarg);
7144 break;
7145 #endif
7146 case QEMU_OPTION_h:
7147 help();
7148 break;
7149 case QEMU_OPTION_m:
7150 ram_size = atoi(optarg) * 1024 * 1024;
7151 if (ram_size <= 0)
7152 help();
7153 if (ram_size > PHYS_RAM_MAX_SIZE) {
7154 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7155 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7156 exit(1);
7158 break;
7159 case QEMU_OPTION_d:
7161 int mask;
7162 CPULogItem *item;
7164 mask = cpu_str_to_log_mask(optarg);
7165 if (!mask) {
7166 printf("Log items (comma separated):\n");
7167 for(item = cpu_log_items; item->mask != 0; item++) {
7168 printf("%-10s %s\n", item->name, item->help);
7170 exit(1);
7172 cpu_set_log(mask);
7174 break;
7175 #ifdef CONFIG_GDBSTUB
7176 case QEMU_OPTION_s:
7177 use_gdbstub = 1;
7178 break;
7179 case QEMU_OPTION_p:
7180 gdbstub_port = atoi(optarg);
7181 break;
7182 #endif
7183 case QEMU_OPTION_L:
7184 bios_dir = optarg;
7185 break;
7186 case QEMU_OPTION_S:
7187 autostart = 0;
7188 break;
7189 case QEMU_OPTION_k:
7190 keyboard_layout = optarg;
7191 break;
7192 case QEMU_OPTION_localtime:
7193 rtc_utc = 0;
7194 break;
7195 case QEMU_OPTION_cirrusvga:
7196 cirrus_vga_enabled = 1;
7197 break;
7198 case QEMU_OPTION_std_vga:
7199 cirrus_vga_enabled = 0;
7200 break;
7201 case QEMU_OPTION_g:
7203 const char *p;
7204 int w, h, depth;
7205 p = optarg;
7206 w = strtol(p, (char **)&p, 10);
7207 if (w <= 0) {
7208 graphic_error:
7209 fprintf(stderr, "qemu: invalid resolution or depth\n");
7210 exit(1);
7212 if (*p != 'x')
7213 goto graphic_error;
7214 p++;
7215 h = strtol(p, (char **)&p, 10);
7216 if (h <= 0)
7217 goto graphic_error;
7218 if (*p == 'x') {
7219 p++;
7220 depth = strtol(p, (char **)&p, 10);
7221 if (depth != 8 && depth != 15 && depth != 16 &&
7222 depth != 24 && depth != 32)
7223 goto graphic_error;
7224 } else if (*p == '\0') {
7225 depth = graphic_depth;
7226 } else {
7227 goto graphic_error;
7230 graphic_width = w;
7231 graphic_height = h;
7232 graphic_depth = depth;
7234 break;
7235 case QEMU_OPTION_monitor:
7236 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7237 break;
7238 case QEMU_OPTION_balloon:
7239 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7240 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7241 exit(1);
7243 if (balloon_used) {
7244 fprintf(stderr, "qemu: only one balloon device can be used\n");
7245 exit(1);
7247 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
7248 vmchannel_device_index++;
7249 balloon_used = 1;
7250 break;
7251 case QEMU_OPTION_vmchannel:
7252 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7253 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7254 exit(1);
7256 pstrcpy(vmchannel_devices[vmchannel_device_index],
7257 sizeof(vmchannel_devices[0]), optarg);
7258 vmchannel_device_index++;
7259 break;
7260 case QEMU_OPTION_serial:
7261 if (serial_device_index >= MAX_SERIAL_PORTS) {
7262 fprintf(stderr, "qemu: too many serial ports\n");
7263 exit(1);
7265 pstrcpy(serial_devices[serial_device_index],
7266 sizeof(serial_devices[0]), optarg);
7267 serial_device_index++;
7268 break;
7269 case QEMU_OPTION_parallel:
7270 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7271 fprintf(stderr, "qemu: too many parallel ports\n");
7272 exit(1);
7274 pstrcpy(parallel_devices[parallel_device_index],
7275 sizeof(parallel_devices[0]), optarg);
7276 parallel_device_index++;
7277 break;
7278 case QEMU_OPTION_loadvm:
7279 loadvm = optarg;
7280 break;
7281 case QEMU_OPTION_incoming:
7282 incoming = optarg;
7283 break;
7284 case QEMU_OPTION_full_screen:
7285 full_screen = 1;
7286 break;
7287 #ifdef CONFIG_SDL
7288 case QEMU_OPTION_no_quit:
7289 no_quit = 1;
7290 break;
7291 #endif
7292 case QEMU_OPTION_pidfile:
7293 create_pidfile(optarg);
7294 break;
7295 #ifdef TARGET_I386
7296 case QEMU_OPTION_win2k_hack:
7297 win2k_install_hack = 1;
7298 break;
7299 #endif
7300 #ifdef USE_KQEMU
7301 case QEMU_OPTION_no_kqemu:
7302 kqemu_allowed = 0;
7303 break;
7304 case QEMU_OPTION_kernel_kqemu:
7305 kqemu_allowed = 2;
7306 break;
7307 #endif
7308 #ifdef USE_KVM
7309 case QEMU_OPTION_no_kvm:
7310 kvm_allowed = 0;
7311 break;
7312 #endif
7313 case QEMU_OPTION_usb:
7314 usb_enabled = 1;
7315 break;
7316 case QEMU_OPTION_usbdevice:
7317 usb_enabled = 1;
7318 if (usb_devices_index >= MAX_USB_CMDLINE) {
7319 fprintf(stderr, "Too many USB devices\n");
7320 exit(1);
7322 pstrcpy(usb_devices[usb_devices_index],
7323 sizeof(usb_devices[usb_devices_index]),
7324 optarg);
7325 usb_devices_index++;
7326 break;
7327 case QEMU_OPTION_smp:
7328 smp_cpus = atoi(optarg);
7329 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7330 fprintf(stderr, "Invalid number of CPUs\n");
7331 exit(1);
7333 break;
7334 case QEMU_OPTION_vnc:
7335 vnc_display = optarg;
7336 break;
7337 case QEMU_OPTION_no_acpi:
7338 acpi_enabled = 0;
7339 break;
7340 case QEMU_OPTION_no_reboot:
7341 no_reboot = 1;
7342 break;
7343 case QEMU_OPTION_daemonize:
7344 daemonize = 1;
7345 break;
7346 case QEMU_OPTION_option_rom:
7347 if (nb_option_roms >= MAX_OPTION_ROMS) {
7348 fprintf(stderr, "Too many option ROMs\n");
7349 exit(1);
7351 option_rom[nb_option_roms] = optarg;
7352 nb_option_roms++;
7353 break;
7354 case QEMU_OPTION_semihosting:
7355 semihosting_enabled = 1;
7356 break;
7357 case QEMU_OPTION_tdf:
7358 time_drift_fix = 0;
7359 #if defined(__linux__)
7360 case QEMU_OPTION_no_rtc:
7361 use_rtc = 0;
7362 break;
7363 #endif
7364 case QEMU_OPTION_cpu_vendor:
7365 cpu_vendor_string = optarg;
7366 break;
7371 #ifndef _WIN32
7372 if (daemonize) {
7373 pid_t pid;
7375 if (pipe(fds) == -1)
7376 exit(1);
7378 pid = fork();
7379 if (pid > 0) {
7380 uint8_t status;
7381 ssize_t len;
7383 close(fds[1]);
7385 again:
7386 len = read(fds[0], &status, 1);
7387 if (len == -1 && (errno == EINTR))
7388 goto again;
7390 if (len != 1 || status != 0)
7391 exit(1);
7392 else
7393 exit(0);
7394 } else if (pid < 0)
7395 exit(1);
7397 setsid();
7399 pid = fork();
7400 if (pid > 0)
7401 exit(0);
7402 else if (pid < 0)
7403 exit(1);
7405 umask(027);
7407 signal(SIGTSTP, SIG_IGN);
7408 signal(SIGTTOU, SIG_IGN);
7409 signal(SIGTTIN, SIG_IGN);
7411 #endif
7413 #if USE_KVM
7414 if (kvm_allowed) {
7415 if (kvm_qemu_init() < 0) {
7416 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
7417 kvm_allowed = 0;
7420 #endif
7422 #ifdef USE_KQEMU
7423 if (smp_cpus > 1)
7424 kqemu_allowed = 0;
7425 #endif
7426 linux_boot = (kernel_filename != NULL);
7428 if (!linux_boot &&
7429 hd_filename[0] == '\0' &&
7430 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7431 fd_filename[0] == '\0')
7432 help();
7434 /* boot to floppy or the default cd if no hard disk defined yet */
7435 if (hd_filename[0] == '\0' && boot_device == 'c') {
7436 if (fd_filename[0] != '\0')
7437 boot_device = 'a';
7438 else
7439 boot_device = 'd';
7442 setvbuf(stdout, NULL, _IOLBF, 0);
7444 init_timers();
7445 init_timer_alarm();
7446 qemu_aio_init();
7448 #ifdef _WIN32
7449 socket_init();
7450 #endif
7452 /* init network clients */
7453 if (nb_net_clients == 0) {
7454 /* if no clients, we use a default config */
7455 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7456 "nic");
7457 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7458 "user");
7459 nb_net_clients = 2;
7462 for(i = 0;i < nb_net_clients; i++) {
7463 if (net_client_init(net_clients[i]) < 0)
7464 exit(1);
7467 #ifdef TARGET_I386
7468 if (boot_device == 'n') {
7469 for (i = 0; i < nb_nics; i++) {
7470 const char *model = nd_table[i].model;
7471 char buf[1024];
7472 if (model == NULL)
7473 model = "ne2k_pci";
7474 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7475 if (get_image_size(buf) > 0) {
7476 option_rom[nb_option_roms] = strdup(buf);
7477 nb_option_roms++;
7478 break;
7481 if (i == nb_nics) {
7482 fprintf(stderr, "No valid PXE rom found for network device\n");
7483 exit(1);
7485 boot_device = 'c'; /* to prevent confusion by the BIOS */
7487 #endif
7489 /* init the memory */
7490 phys_ram_size = ram_size + vga_ram_size + bios_size;
7493 for (i = 0; i < nb_option_roms; i++) {
7494 int ret = get_image_size(option_rom[i]);
7495 if (ret == -1) {
7496 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7497 exit(1);
7499 phys_ram_size += ret;
7502 #if USE_KVM
7503 /* Initialize kvm */
7504 if (kvm_allowed) {
7505 phys_ram_size += KVM_EXTRA_PAGES * 4096;
7506 if (kvm_qemu_create_context() < 0) {
7507 fprintf(stderr, "Could not create KVM context\n");
7508 exit(1);
7510 } else {
7511 phys_ram_base = qemu_vmalloc(phys_ram_size);
7512 if (!phys_ram_base) {
7513 fprintf(stderr, "Could not allocate physical memory\n");
7514 exit(1);
7517 #else
7518 phys_ram_base = qemu_vmalloc(phys_ram_size);
7519 if (!phys_ram_base) {
7520 fprintf(stderr, "Could not allocate physical memory\n");
7521 exit(1);
7523 #endif
7525 /* we always create the cdrom drive, even if no disk is there */
7526 bdrv_init();
7527 if (cdrom_index >= 0) {
7528 bs_table[cdrom_index] = bdrv_new("cdrom");
7529 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7532 /* open the virtual block devices */
7533 for(i = 0; i < MAX_DISKS; i++) {
7534 if (hd_filename[i]) {
7535 if (!bs_table[i]) {
7536 char buf[64];
7537 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7538 bs_table[i] = bdrv_new(buf);
7540 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7541 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7542 hd_filename[i]);
7543 exit(1);
7545 if (i == 0 && cyls != 0) {
7546 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7547 bdrv_set_translation_hint(bs_table[i], translation);
7552 /* we always create at least one floppy disk */
7553 fd_table[0] = bdrv_new("fda");
7554 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7556 for(i = 0; i < MAX_FD; i++) {
7557 if (fd_filename[i]) {
7558 if (!fd_table[i]) {
7559 char buf[64];
7560 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7561 fd_table[i] = bdrv_new(buf);
7562 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7564 if (fd_filename[i] != '\0') {
7565 if (bdrv_open(fd_table[i], fd_filename[i],
7566 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7567 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7568 fd_filename[i]);
7569 exit(1);
7575 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7576 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
7578 init_ioports();
7580 /* terminal init */
7581 if (nographic) {
7582 dumb_display_init(ds);
7583 } else if (vnc_display != NULL) {
7584 vnc_display_init(ds, vnc_display);
7585 } else {
7586 #if defined(CONFIG_SDL)
7587 sdl_display_init(ds, full_screen);
7588 #elif defined(CONFIG_COCOA)
7589 cocoa_display_init(ds, full_screen);
7590 #else
7591 dumb_display_init(ds);
7592 #endif
7595 monitor_hd = qemu_chr_open(monitor_device);
7596 if (!monitor_hd) {
7597 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7598 exit(1);
7600 monitor_init(monitor_hd, !nographic);
7602 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
7603 const char *devname = vmchannel_devices[i];
7604 if (devname[0] != '\0' && strcmp(devname, "none")) {
7605 int devid;
7606 char *termn;
7608 if (strstart(devname, "di:", &devname)) {
7609 devid = strtol(devname, &termn, 16);
7610 devname = termn + 1;
7612 else {
7613 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
7614 devname);
7615 exit(1);
7617 vmchannel_hds[i] = qemu_chr_open(devname);
7618 if (!vmchannel_hds[i]) {
7619 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
7620 devname);
7621 exit(1);
7623 vmchannel_init(vmchannel_hds[i], devid, i);
7627 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7628 const char *devname = serial_devices[i];
7629 if (devname[0] != '\0' && strcmp(devname, "none")) {
7630 serial_hds[i] = qemu_chr_open(devname);
7631 if (!serial_hds[i]) {
7632 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7633 devname);
7634 exit(1);
7636 if (!strcmp(devname, "vc"))
7637 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7641 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7642 const char *devname = parallel_devices[i];
7643 if (devname[0] != '\0' && strcmp(devname, "none")) {
7644 parallel_hds[i] = qemu_chr_open(devname);
7645 if (!parallel_hds[i]) {
7646 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7647 devname);
7648 exit(1);
7650 if (!strcmp(devname, "vc"))
7651 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7655 machine->init(ram_size, vga_ram_size, boot_device,
7656 ds, fd_filename, snapshot,
7657 kernel_filename, kernel_cmdline, initrd_filename);
7659 /* init USB devices */
7660 if (usb_enabled) {
7661 for(i = 0; i < usb_devices_index; i++) {
7662 if (usb_device_add(usb_devices[i]) < 0) {
7663 fprintf(stderr, "Warning: could not add USB device %s\n",
7664 usb_devices[i]);
7669 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7670 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7672 #ifdef CONFIG_GDBSTUB
7673 if (use_gdbstub) {
7674 /* XXX: use standard host:port notation and modify options
7675 accordingly. */
7676 if (gdbserver_start_port(gdbstub_port) < 0) {
7677 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7678 gdbstub_port);
7679 exit(1);
7681 } else
7682 #endif
7683 if (loadvm) {
7684 do_loadvm(loadvm);
7687 if (incoming) {
7688 int rc;
7690 rc = migrate_incoming(incoming);
7691 if (rc != 0) {
7692 fprintf(stderr, "Migration failed rc=%d\n", rc);
7693 exit(rc);
7698 /* XXX: simplify init */
7699 read_passwords();
7700 if (autostart) {
7701 vm_start();
7705 if (daemonize) {
7706 uint8_t status = 0;
7707 ssize_t len;
7708 int fd;
7710 again1:
7711 len = write(fds[1], &status, 1);
7712 if (len == -1 && (errno == EINTR))
7713 goto again1;
7715 if (len != 1)
7716 exit(1);
7718 chdir("/");
7719 fd = open("/dev/null", O_RDWR);
7720 if (fd == -1)
7721 exit(1);
7723 dup2(fd, 0);
7724 dup2(fd, 1);
7725 dup2(fd, 2);
7727 close(fd);
7730 main_loop();
7731 quit_timers();
7732 return 0;