kvm: bios: update generated files
[qemu-kvm/fedora.git] / vl.c
blob5360ed72a641e35369e7719aa93043297ba8e375
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 if (version_id > se->version_id) { /* src version > dst version */
4851 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
4852 idstr, version_id, se->version_id);
4853 ret = -1;
4854 goto the_end;
4856 ret = se->load_state(f, se->opaque, version_id);
4857 if (ret < 0) {
4858 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4859 instance_id, idstr);
4860 goto the_end;
4864 ret = 0;
4866 qemu_announce_self();
4868 the_end:
4869 return ret;
4872 /* device can contain snapshots */
4873 static int bdrv_can_snapshot(BlockDriverState *bs)
4875 return (bs &&
4876 !bdrv_is_removable(bs) &&
4877 !bdrv_is_read_only(bs));
4880 /* device must be snapshots in order to have a reliable snapshot */
4881 static int bdrv_has_snapshot(BlockDriverState *bs)
4883 return (bs &&
4884 !bdrv_is_removable(bs) &&
4885 !bdrv_is_read_only(bs));
4888 static BlockDriverState *get_bs_snapshots(void)
4890 BlockDriverState *bs;
4891 int i;
4893 if (bs_snapshots)
4894 return bs_snapshots;
4895 for(i = 0; i <= MAX_DISKS; i++) {
4896 bs = bs_table[i];
4897 if (bdrv_can_snapshot(bs))
4898 goto ok;
4900 return NULL;
4902 bs_snapshots = bs;
4903 return bs;
4906 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4907 const char *name)
4909 QEMUSnapshotInfo *sn_tab, *sn;
4910 int nb_sns, i, ret;
4912 ret = -ENOENT;
4913 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4914 if (nb_sns < 0)
4915 return ret;
4916 for(i = 0; i < nb_sns; i++) {
4917 sn = &sn_tab[i];
4918 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4919 *sn_info = *sn;
4920 ret = 0;
4921 break;
4924 qemu_free(sn_tab);
4925 return ret;
4928 void do_savevm(const char *name)
4930 BlockDriverState *bs, *bs1;
4931 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4932 int must_delete, ret, i;
4933 BlockDriverInfo bdi1, *bdi = &bdi1;
4934 QEMUFile *f;
4935 int saved_vm_running;
4936 #ifdef _WIN32
4937 struct _timeb tb;
4938 #else
4939 struct timeval tv;
4940 #endif
4942 bs = get_bs_snapshots();
4943 if (!bs) {
4944 term_printf("No block device can accept snapshots\n");
4945 return;
4948 /* ??? Should this occur after vm_stop? */
4949 qemu_aio_flush();
4951 saved_vm_running = vm_running;
4952 vm_stop(0);
4954 must_delete = 0;
4955 if (name) {
4956 ret = bdrv_snapshot_find(bs, old_sn, name);
4957 if (ret >= 0) {
4958 must_delete = 1;
4961 memset(sn, 0, sizeof(*sn));
4962 if (must_delete) {
4963 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4964 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4965 } else {
4966 if (name)
4967 pstrcpy(sn->name, sizeof(sn->name), name);
4970 /* fill auxiliary fields */
4971 #ifdef _WIN32
4972 _ftime(&tb);
4973 sn->date_sec = tb.time;
4974 sn->date_nsec = tb.millitm * 1000000;
4975 #else
4976 gettimeofday(&tv, NULL);
4977 sn->date_sec = tv.tv_sec;
4978 sn->date_nsec = tv.tv_usec * 1000;
4979 #endif
4980 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4982 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4983 term_printf("Device %s does not support VM state snapshots\n",
4984 bdrv_get_device_name(bs));
4985 goto the_end;
4988 /* save the VM state */
4989 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4990 if (!f) {
4991 term_printf("Could not open VM state file\n");
4992 goto the_end;
4994 ret = qemu_savevm_state(f);
4995 sn->vm_state_size = qemu_ftell(f);
4996 qemu_fclose(f);
4997 if (ret < 0) {
4998 term_printf("Error %d while writing VM\n", ret);
4999 goto the_end;
5002 /* create the snapshots */
5004 for(i = 0; i < MAX_DISKS; i++) {
5005 bs1 = bs_table[i];
5006 if (bdrv_has_snapshot(bs1)) {
5007 if (must_delete) {
5008 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5009 if (ret < 0) {
5010 term_printf("Error while deleting snapshot on '%s'\n",
5011 bdrv_get_device_name(bs1));
5014 ret = bdrv_snapshot_create(bs1, sn);
5015 if (ret < 0) {
5016 term_printf("Error while creating snapshot on '%s'\n",
5017 bdrv_get_device_name(bs1));
5022 the_end:
5023 if (saved_vm_running)
5024 vm_start();
5027 void do_loadvm(const char *name)
5029 BlockDriverState *bs, *bs1;
5030 BlockDriverInfo bdi1, *bdi = &bdi1;
5031 QEMUFile *f;
5032 int i, ret;
5033 int saved_vm_running;
5035 bs = get_bs_snapshots();
5036 if (!bs) {
5037 term_printf("No block device supports snapshots\n");
5038 return;
5041 /* Flush all IO requests so they don't interfere with the new state. */
5042 qemu_aio_flush();
5044 saved_vm_running = vm_running;
5045 vm_stop(0);
5047 for(i = 0; i <= MAX_DISKS; i++) {
5048 bs1 = bs_table[i];
5049 if (bdrv_has_snapshot(bs1)) {
5050 ret = bdrv_snapshot_goto(bs1, name);
5051 if (ret < 0) {
5052 if (bs != bs1)
5053 term_printf("Warning: ");
5054 switch(ret) {
5055 case -ENOTSUP:
5056 term_printf("Snapshots not supported on device '%s'\n",
5057 bdrv_get_device_name(bs1));
5058 break;
5059 case -ENOENT:
5060 term_printf("Could not find snapshot '%s' on device '%s'\n",
5061 name, bdrv_get_device_name(bs1));
5062 break;
5063 default:
5064 term_printf("Error %d while activating snapshot on '%s'\n",
5065 ret, bdrv_get_device_name(bs1));
5066 break;
5068 /* fatal on snapshot block device */
5069 if (bs == bs1)
5070 goto the_end;
5075 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5076 term_printf("Device %s does not support VM state snapshots\n",
5077 bdrv_get_device_name(bs));
5078 return;
5081 /* restore the VM state */
5082 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5083 if (!f) {
5084 term_printf("Could not open VM state file\n");
5085 goto the_end;
5087 ret = qemu_loadvm_state(f);
5088 qemu_fclose(f);
5089 if (ret < 0) {
5090 term_printf("Error %d while loading VM state\n", ret);
5092 the_end:
5093 if (saved_vm_running)
5094 vm_start();
5097 void do_delvm(const char *name)
5099 BlockDriverState *bs, *bs1;
5100 int i, ret;
5102 bs = get_bs_snapshots();
5103 if (!bs) {
5104 term_printf("No block device supports snapshots\n");
5105 return;
5108 for(i = 0; i <= MAX_DISKS; i++) {
5109 bs1 = bs_table[i];
5110 if (bdrv_has_snapshot(bs1)) {
5111 ret = bdrv_snapshot_delete(bs1, name);
5112 if (ret < 0) {
5113 if (ret == -ENOTSUP)
5114 term_printf("Snapshots not supported on device '%s'\n",
5115 bdrv_get_device_name(bs1));
5116 else
5117 term_printf("Error %d while deleting snapshot on '%s'\n",
5118 ret, bdrv_get_device_name(bs1));
5124 void do_info_snapshots(void)
5126 BlockDriverState *bs, *bs1;
5127 QEMUSnapshotInfo *sn_tab, *sn;
5128 int nb_sns, i;
5129 char buf[256];
5131 bs = get_bs_snapshots();
5132 if (!bs) {
5133 term_printf("No available block device supports snapshots\n");
5134 return;
5136 term_printf("Snapshot devices:");
5137 for(i = 0; i <= MAX_DISKS; i++) {
5138 bs1 = bs_table[i];
5139 if (bdrv_has_snapshot(bs1)) {
5140 if (bs == bs1)
5141 term_printf(" %s", bdrv_get_device_name(bs1));
5144 term_printf("\n");
5146 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5147 if (nb_sns < 0) {
5148 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5149 return;
5151 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5152 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5153 for(i = 0; i < nb_sns; i++) {
5154 sn = &sn_tab[i];
5155 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5157 qemu_free(sn_tab);
5160 /***********************************************************/
5161 /* cpu save/restore */
5163 #if defined(TARGET_I386)
5165 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5167 qemu_put_be32(f, dt->selector);
5168 qemu_put_betl(f, dt->base);
5169 qemu_put_be32(f, dt->limit);
5170 qemu_put_be32(f, dt->flags);
5173 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5175 dt->selector = qemu_get_be32(f);
5176 dt->base = qemu_get_betl(f);
5177 dt->limit = qemu_get_be32(f);
5178 dt->flags = qemu_get_be32(f);
5181 void cpu_save(QEMUFile *f, void *opaque)
5183 CPUState *env = opaque;
5184 uint16_t fptag, fpus, fpuc, fpregs_format;
5185 uint32_t hflags;
5186 int i;
5188 #ifdef USE_KVM
5189 if (kvm_allowed)
5190 kvm_save_registers(env);
5191 #endif
5193 for(i = 0; i < CPU_NB_REGS; i++)
5194 qemu_put_betls(f, &env->regs[i]);
5195 qemu_put_betls(f, &env->eip);
5196 qemu_put_betls(f, &env->eflags);
5197 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5198 qemu_put_be32s(f, &hflags);
5200 /* FPU */
5201 fpuc = env->fpuc;
5202 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5203 fptag = 0;
5204 for(i = 0; i < 8; i++) {
5205 fptag |= ((!env->fptags[i]) << i);
5208 qemu_put_be16s(f, &fpuc);
5209 qemu_put_be16s(f, &fpus);
5210 qemu_put_be16s(f, &fptag);
5212 #ifdef USE_X86LDOUBLE
5213 fpregs_format = 0;
5214 #else
5215 fpregs_format = 1;
5216 #endif
5217 qemu_put_be16s(f, &fpregs_format);
5219 for(i = 0; i < 8; i++) {
5220 #ifdef USE_X86LDOUBLE
5222 uint64_t mant;
5223 uint16_t exp;
5224 /* we save the real CPU data (in case of MMX usage only 'mant'
5225 contains the MMX register */
5226 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5227 qemu_put_be64(f, mant);
5228 qemu_put_be16(f, exp);
5230 #else
5231 /* if we use doubles for float emulation, we save the doubles to
5232 avoid losing information in case of MMX usage. It can give
5233 problems if the image is restored on a CPU where long
5234 doubles are used instead. */
5235 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5236 #endif
5239 for(i = 0; i < 6; i++)
5240 cpu_put_seg(f, &env->segs[i]);
5241 cpu_put_seg(f, &env->ldt);
5242 cpu_put_seg(f, &env->tr);
5243 cpu_put_seg(f, &env->gdt);
5244 cpu_put_seg(f, &env->idt);
5246 qemu_put_be32s(f, &env->sysenter_cs);
5247 qemu_put_be32s(f, &env->sysenter_esp);
5248 qemu_put_be32s(f, &env->sysenter_eip);
5250 qemu_put_betls(f, &env->cr[0]);
5251 qemu_put_betls(f, &env->cr[2]);
5252 qemu_put_betls(f, &env->cr[3]);
5253 qemu_put_betls(f, &env->cr[4]);
5255 for(i = 0; i < 8; i++)
5256 qemu_put_betls(f, &env->dr[i]);
5258 /* MMU */
5259 qemu_put_be32s(f, &env->a20_mask);
5261 /* XMM */
5262 qemu_put_be32s(f, &env->mxcsr);
5263 for(i = 0; i < CPU_NB_REGS; i++) {
5264 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5265 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5268 #ifdef TARGET_X86_64
5269 qemu_put_be64s(f, &env->efer);
5270 qemu_put_be64s(f, &env->star);
5271 qemu_put_be64s(f, &env->lstar);
5272 qemu_put_be64s(f, &env->cstar);
5273 qemu_put_be64s(f, &env->fmask);
5274 qemu_put_be64s(f, &env->kernelgsbase);
5275 #endif
5276 qemu_put_be32s(f, &env->smbase);
5278 #ifdef USE_KVM
5279 if (kvm_allowed) {
5280 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5281 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
5283 qemu_put_be64s(f, &env->tsc);
5285 #endif
5289 #ifdef USE_X86LDOUBLE
5290 /* XXX: add that in a FPU generic layer */
5291 union x86_longdouble {
5292 uint64_t mant;
5293 uint16_t exp;
5296 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5297 #define EXPBIAS1 1023
5298 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5299 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5301 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5303 int e;
5304 /* mantissa */
5305 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5306 /* exponent + sign */
5307 e = EXPD1(temp) - EXPBIAS1 + 16383;
5308 e |= SIGND1(temp) >> 16;
5309 p->exp = e;
5311 #endif
5313 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5315 CPUState *env = opaque;
5316 int i, guess_mmx;
5317 uint32_t hflags;
5318 uint16_t fpus, fpuc, fptag, fpregs_format;
5320 if (version_id != 3 && version_id != 4)
5321 return -EINVAL;
5322 for(i = 0; i < CPU_NB_REGS; i++)
5323 qemu_get_betls(f, &env->regs[i]);
5324 qemu_get_betls(f, &env->eip);
5325 qemu_get_betls(f, &env->eflags);
5326 qemu_get_be32s(f, &hflags);
5328 qemu_get_be16s(f, &fpuc);
5329 qemu_get_be16s(f, &fpus);
5330 qemu_get_be16s(f, &fptag);
5331 qemu_get_be16s(f, &fpregs_format);
5333 /* NOTE: we cannot always restore the FPU state if the image come
5334 from a host with a different 'USE_X86LDOUBLE' define. We guess
5335 if we are in an MMX state to restore correctly in that case. */
5336 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5337 for(i = 0; i < 8; i++) {
5338 uint64_t mant;
5339 uint16_t exp;
5341 switch(fpregs_format) {
5342 case 0:
5343 mant = qemu_get_be64(f);
5344 exp = qemu_get_be16(f);
5345 #ifdef USE_X86LDOUBLE
5346 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5347 #else
5348 /* difficult case */
5349 if (guess_mmx)
5350 env->fpregs[i].mmx.MMX_Q(0) = mant;
5351 else
5352 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5353 #endif
5354 break;
5355 case 1:
5356 mant = qemu_get_be64(f);
5357 #ifdef USE_X86LDOUBLE
5359 union x86_longdouble *p;
5360 /* difficult case */
5361 p = (void *)&env->fpregs[i];
5362 if (guess_mmx) {
5363 p->mant = mant;
5364 p->exp = 0xffff;
5365 } else {
5366 fp64_to_fp80(p, mant);
5369 #else
5370 env->fpregs[i].mmx.MMX_Q(0) = mant;
5371 #endif
5372 break;
5373 default:
5374 return -EINVAL;
5378 env->fpuc = fpuc;
5379 /* XXX: restore FPU round state */
5380 env->fpstt = (fpus >> 11) & 7;
5381 env->fpus = fpus & ~0x3800;
5382 fptag ^= 0xff;
5383 for(i = 0; i < 8; i++) {
5384 env->fptags[i] = (fptag >> i) & 1;
5387 for(i = 0; i < 6; i++)
5388 cpu_get_seg(f, &env->segs[i]);
5389 cpu_get_seg(f, &env->ldt);
5390 cpu_get_seg(f, &env->tr);
5391 cpu_get_seg(f, &env->gdt);
5392 cpu_get_seg(f, &env->idt);
5394 qemu_get_be32s(f, &env->sysenter_cs);
5395 qemu_get_be32s(f, &env->sysenter_esp);
5396 qemu_get_be32s(f, &env->sysenter_eip);
5398 qemu_get_betls(f, &env->cr[0]);
5399 qemu_get_betls(f, &env->cr[2]);
5400 qemu_get_betls(f, &env->cr[3]);
5401 qemu_get_betls(f, &env->cr[4]);
5403 for(i = 0; i < 8; i++)
5404 qemu_get_betls(f, &env->dr[i]);
5406 /* MMU */
5407 qemu_get_be32s(f, &env->a20_mask);
5409 qemu_get_be32s(f, &env->mxcsr);
5410 for(i = 0; i < CPU_NB_REGS; i++) {
5411 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5412 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5415 #ifdef TARGET_X86_64
5416 qemu_get_be64s(f, &env->efer);
5417 qemu_get_be64s(f, &env->star);
5418 qemu_get_be64s(f, &env->lstar);
5419 qemu_get_be64s(f, &env->cstar);
5420 qemu_get_be64s(f, &env->fmask);
5421 qemu_get_be64s(f, &env->kernelgsbase);
5422 #endif
5423 if (version_id >= 4)
5424 qemu_get_be32s(f, &env->smbase);
5426 /* XXX: compute hflags from scratch, except for CPL and IIF */
5427 env->hflags = hflags;
5428 tlb_flush(env, 1);
5429 #ifdef USE_KVM
5430 if (kvm_allowed) {
5431 for (i = 0; i < NR_IRQ_WORDS ; i++) {
5432 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
5434 qemu_get_be64s(f, &env->tsc);
5435 kvm_load_registers(env);
5437 #endif
5438 return 0;
5441 #elif defined(TARGET_PPC)
5442 void cpu_save(QEMUFile *f, void *opaque)
5446 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5448 return 0;
5451 #elif defined(TARGET_MIPS)
5452 void cpu_save(QEMUFile *f, void *opaque)
5456 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5458 return 0;
5461 #elif defined(TARGET_SPARC)
5462 void cpu_save(QEMUFile *f, void *opaque)
5464 CPUState *env = opaque;
5465 int i;
5466 uint32_t tmp;
5468 for(i = 0; i < 8; i++)
5469 qemu_put_betls(f, &env->gregs[i]);
5470 for(i = 0; i < NWINDOWS * 16; i++)
5471 qemu_put_betls(f, &env->regbase[i]);
5473 /* FPU */
5474 for(i = 0; i < TARGET_FPREGS; i++) {
5475 union {
5476 float32 f;
5477 uint32_t i;
5478 } u;
5479 u.f = env->fpr[i];
5480 qemu_put_be32(f, u.i);
5483 qemu_put_betls(f, &env->pc);
5484 qemu_put_betls(f, &env->npc);
5485 qemu_put_betls(f, &env->y);
5486 tmp = GET_PSR(env);
5487 qemu_put_be32(f, tmp);
5488 qemu_put_betls(f, &env->fsr);
5489 qemu_put_betls(f, &env->tbr);
5490 #ifndef TARGET_SPARC64
5491 qemu_put_be32s(f, &env->wim);
5492 /* MMU */
5493 for(i = 0; i < 16; i++)
5494 qemu_put_be32s(f, &env->mmuregs[i]);
5495 #endif
5498 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5500 CPUState *env = opaque;
5501 int i;
5502 uint32_t tmp;
5504 for(i = 0; i < 8; i++)
5505 qemu_get_betls(f, &env->gregs[i]);
5506 for(i = 0; i < NWINDOWS * 16; i++)
5507 qemu_get_betls(f, &env->regbase[i]);
5509 /* FPU */
5510 for(i = 0; i < TARGET_FPREGS; i++) {
5511 union {
5512 float32 f;
5513 uint32_t i;
5514 } u;
5515 u.i = qemu_get_be32(f);
5516 env->fpr[i] = u.f;
5519 qemu_get_betls(f, &env->pc);
5520 qemu_get_betls(f, &env->npc);
5521 qemu_get_betls(f, &env->y);
5522 tmp = qemu_get_be32(f);
5523 env->cwp = 0; /* needed to ensure that the wrapping registers are
5524 correctly updated */
5525 PUT_PSR(env, tmp);
5526 qemu_get_betls(f, &env->fsr);
5527 qemu_get_betls(f, &env->tbr);
5528 #ifndef TARGET_SPARC64
5529 qemu_get_be32s(f, &env->wim);
5530 /* MMU */
5531 for(i = 0; i < 16; i++)
5532 qemu_get_be32s(f, &env->mmuregs[i]);
5533 #endif
5534 tlb_flush(env, 1);
5535 return 0;
5538 #elif defined(TARGET_ARM)
5540 /* ??? Need to implement these. */
5541 void cpu_save(QEMUFile *f, void *opaque)
5545 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5547 return 0;
5550 #else
5552 #warning No CPU save/restore functions
5554 #endif
5556 /***********************************************************/
5557 /* ram save/restore */
5559 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5561 int v;
5563 v = qemu_get_byte(f);
5564 switch(v) {
5565 case 0:
5566 if (qemu_get_buffer(f, buf, len) != len)
5567 return -EIO;
5568 break;
5569 case 1:
5570 v = qemu_get_byte(f);
5571 memset(buf, v, len);
5572 break;
5573 default:
5574 return -EINVAL;
5576 return 0;
5579 static int ram_load_v1(QEMUFile *f, void *opaque)
5581 int i, ret;
5583 if (qemu_get_be32(f) != phys_ram_size)
5584 return -EINVAL;
5585 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5586 #ifdef USE_KVM
5587 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5588 continue;
5589 #endif
5590 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5591 if (ret)
5592 return ret;
5594 return 0;
5597 #define BDRV_HASH_BLOCK_SIZE 1024
5598 #define IOBUF_SIZE 4096
5599 #define RAM_CBLOCK_MAGIC 0xfabe
5601 typedef struct RamCompressState {
5602 z_stream zstream;
5603 QEMUFile *f;
5604 uint8_t buf[IOBUF_SIZE];
5605 } RamCompressState;
5607 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5609 int ret;
5610 memset(s, 0, sizeof(*s));
5611 s->f = f;
5612 ret = deflateInit2(&s->zstream, 1,
5613 Z_DEFLATED, 15,
5614 9, Z_DEFAULT_STRATEGY);
5615 if (ret != Z_OK)
5616 return -1;
5617 s->zstream.avail_out = IOBUF_SIZE;
5618 s->zstream.next_out = s->buf;
5619 return 0;
5622 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5624 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5625 qemu_put_be16(s->f, len);
5626 qemu_put_buffer(s->f, buf, len);
5629 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5631 int ret;
5633 s->zstream.avail_in = len;
5634 s->zstream.next_in = (uint8_t *)buf;
5635 while (s->zstream.avail_in > 0) {
5636 ret = deflate(&s->zstream, Z_NO_FLUSH);
5637 if (ret != Z_OK)
5638 return -1;
5639 if (s->zstream.avail_out == 0) {
5640 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5641 s->zstream.avail_out = IOBUF_SIZE;
5642 s->zstream.next_out = s->buf;
5645 return 0;
5648 static void ram_compress_close(RamCompressState *s)
5650 int len, ret;
5652 /* compress last bytes */
5653 for(;;) {
5654 ret = deflate(&s->zstream, Z_FINISH);
5655 if (ret == Z_OK || ret == Z_STREAM_END) {
5656 len = IOBUF_SIZE - s->zstream.avail_out;
5657 if (len > 0) {
5658 ram_put_cblock(s, s->buf, len);
5660 s->zstream.avail_out = IOBUF_SIZE;
5661 s->zstream.next_out = s->buf;
5662 if (ret == Z_STREAM_END)
5663 break;
5664 } else {
5665 goto fail;
5668 fail:
5669 deflateEnd(&s->zstream);
5672 typedef struct RamDecompressState {
5673 z_stream zstream;
5674 QEMUFile *f;
5675 uint8_t buf[IOBUF_SIZE];
5676 } RamDecompressState;
5678 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5680 int ret;
5681 memset(s, 0, sizeof(*s));
5682 s->f = f;
5683 ret = inflateInit(&s->zstream);
5684 if (ret != Z_OK)
5685 return -1;
5686 return 0;
5689 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5691 int ret, clen;
5693 s->zstream.avail_out = len;
5694 s->zstream.next_out = buf;
5695 while (s->zstream.avail_out > 0) {
5696 if (s->zstream.avail_in == 0) {
5697 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5698 return -1;
5699 clen = qemu_get_be16(s->f);
5700 if (clen > IOBUF_SIZE)
5701 return -1;
5702 qemu_get_buffer(s->f, s->buf, clen);
5703 s->zstream.avail_in = clen;
5704 s->zstream.next_in = s->buf;
5706 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5707 if (ret != Z_OK && ret != Z_STREAM_END) {
5708 return -1;
5711 return 0;
5714 static void ram_decompress_close(RamDecompressState *s)
5716 inflateEnd(&s->zstream);
5719 static void ram_save_live(QEMUFile *f, void *opaque)
5721 target_ulong addr;
5723 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
5724 #ifdef USE_KVM
5725 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
5726 continue;
5727 #endif
5728 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
5729 qemu_put_be32(f, addr);
5730 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5733 qemu_put_be32(f, 1);
5736 static void ram_save_static(QEMUFile *f, void *opaque)
5738 int i;
5739 RamCompressState s1, *s = &s1;
5740 uint8_t buf[10];
5742 qemu_put_be32(f, phys_ram_size);
5743 if (ram_compress_open(s, f) < 0)
5744 return;
5745 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5746 #ifdef USE_KVM
5747 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5748 continue;
5749 #endif
5750 #if 0
5751 if (tight_savevm_enabled) {
5752 int64_t sector_num;
5753 int j;
5755 /* find if the memory block is available on a virtual
5756 block device */
5757 sector_num = -1;
5758 for(j = 0; j < MAX_DISKS; j++) {
5759 if (bs_table[j]) {
5760 sector_num = bdrv_hash_find(bs_table[j],
5761 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5762 if (sector_num >= 0)
5763 break;
5766 if (j == MAX_DISKS)
5767 goto normal_compress;
5768 buf[0] = 1;
5769 buf[1] = j;
5770 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5771 ram_compress_buf(s, buf, 10);
5772 } else
5773 #endif
5775 // normal_compress:
5776 buf[0] = 0;
5777 ram_compress_buf(s, buf, 1);
5778 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5781 ram_compress_close(s);
5784 static void ram_save(QEMUFile *f, void *opaque)
5786 int in_migration = cpu_physical_memory_get_dirty_tracking();
5788 qemu_put_byte(f, in_migration);
5790 if (in_migration)
5791 ram_save_live(f, opaque);
5792 else
5793 ram_save_static(f, opaque);
5796 static int ram_load_live(QEMUFile *f, void *opaque)
5798 target_ulong addr;
5800 do {
5801 addr = qemu_get_be32(f);
5802 if (addr == 1)
5803 break;
5805 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
5806 } while (1);
5808 return 0;
5811 static int ram_load_static(QEMUFile *f, void *opaque)
5813 RamDecompressState s1, *s = &s1;
5814 uint8_t buf[10];
5815 int i;
5817 if (qemu_get_be32(f) != phys_ram_size)
5818 return -EINVAL;
5819 if (ram_decompress_open(s, f) < 0)
5820 return -EINVAL;
5821 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5822 #ifdef USE_KVM
5823 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
5824 continue;
5825 #endif
5826 if (ram_decompress_buf(s, buf, 1) < 0) {
5827 fprintf(stderr, "Error while reading ram block header\n");
5828 goto error;
5830 if (buf[0] == 0) {
5831 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5832 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5833 goto error;
5835 } else
5836 #if 0
5837 if (buf[0] == 1) {
5838 int bs_index;
5839 int64_t sector_num;
5841 ram_decompress_buf(s, buf + 1, 9);
5842 bs_index = buf[1];
5843 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5844 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5845 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5846 goto error;
5848 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5849 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5850 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5851 bs_index, sector_num);
5852 goto error;
5854 } else
5855 #endif
5857 error:
5858 printf("Error block header\n");
5859 return -EINVAL;
5862 ram_decompress_close(s);
5863 return 0;
5866 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5868 int ret;
5870 switch (version_id) {
5871 case 1:
5872 ret = ram_load_v1(f, opaque);
5873 break;
5874 case 3:
5875 if (qemu_get_byte(f)) {
5876 ret = ram_load_live(f, opaque);
5877 break;
5879 case 2:
5880 ret = ram_load_static(f, opaque);
5881 break;
5882 default:
5883 ret = -EINVAL;
5884 break;
5887 return ret;
5890 /***********************************************************/
5891 /* bottom halves (can be seen as timers which expire ASAP) */
5893 struct QEMUBH {
5894 QEMUBHFunc *cb;
5895 void *opaque;
5896 int scheduled;
5897 QEMUBH *next;
5900 static QEMUBH *first_bh = NULL;
5902 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5904 QEMUBH *bh;
5905 bh = qemu_mallocz(sizeof(QEMUBH));
5906 if (!bh)
5907 return NULL;
5908 bh->cb = cb;
5909 bh->opaque = opaque;
5910 return bh;
5913 int qemu_bh_poll(void)
5915 QEMUBH *bh, **pbh;
5916 int ret;
5918 ret = 0;
5919 for(;;) {
5920 pbh = &first_bh;
5921 bh = *pbh;
5922 if (!bh)
5923 break;
5924 ret = 1;
5925 *pbh = bh->next;
5926 bh->scheduled = 0;
5927 bh->cb(bh->opaque);
5929 return ret;
5932 void qemu_bh_schedule(QEMUBH *bh)
5934 CPUState *env = cpu_single_env;
5935 if (bh->scheduled)
5936 return;
5937 bh->scheduled = 1;
5938 bh->next = first_bh;
5939 first_bh = bh;
5941 /* stop the currently executing CPU to execute the BH ASAP */
5942 if (env) {
5943 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5947 void qemu_bh_cancel(QEMUBH *bh)
5949 QEMUBH **pbh;
5950 if (bh->scheduled) {
5951 pbh = &first_bh;
5952 while (*pbh != bh)
5953 pbh = &(*pbh)->next;
5954 *pbh = bh->next;
5955 bh->scheduled = 0;
5959 void qemu_bh_delete(QEMUBH *bh)
5961 qemu_bh_cancel(bh);
5962 qemu_free(bh);
5965 /***********************************************************/
5966 /* machine registration */
5968 QEMUMachine *first_machine = NULL;
5970 int qemu_register_machine(QEMUMachine *m)
5972 QEMUMachine **pm;
5973 pm = &first_machine;
5974 while (*pm != NULL)
5975 pm = &(*pm)->next;
5976 m->next = NULL;
5977 *pm = m;
5978 return 0;
5981 QEMUMachine *find_machine(const char *name)
5983 QEMUMachine *m;
5985 for(m = first_machine; m != NULL; m = m->next) {
5986 if (!strcmp(m->name, name))
5987 return m;
5989 return NULL;
5992 /***********************************************************/
5993 /* main execution loop */
5995 void gui_update(void *opaque)
5997 display_state.dpy_refresh(&display_state);
5998 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6001 struct vm_change_state_entry {
6002 VMChangeStateHandler *cb;
6003 void *opaque;
6004 LIST_ENTRY (vm_change_state_entry) entries;
6007 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6009 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6010 void *opaque)
6012 VMChangeStateEntry *e;
6014 e = qemu_mallocz(sizeof (*e));
6015 if (!e)
6016 return NULL;
6018 e->cb = cb;
6019 e->opaque = opaque;
6020 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6021 return e;
6024 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6026 LIST_REMOVE (e, entries);
6027 qemu_free (e);
6030 static void vm_state_notify(int running)
6032 VMChangeStateEntry *e;
6034 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6035 e->cb(e->opaque, running);
6039 /* XXX: support several handlers */
6040 static VMStopHandler *vm_stop_cb;
6041 static void *vm_stop_opaque;
6043 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6045 vm_stop_cb = cb;
6046 vm_stop_opaque = opaque;
6047 return 0;
6050 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6052 vm_stop_cb = NULL;
6055 void vm_start(void)
6057 if (!vm_running) {
6058 cpu_enable_ticks();
6059 vm_running = 1;
6060 vm_state_notify(1);
6064 void vm_stop(int reason)
6066 if (vm_running) {
6067 cpu_disable_ticks();
6068 vm_running = 0;
6069 if (reason != 0) {
6070 if (vm_stop_cb) {
6071 vm_stop_cb(vm_stop_opaque, reason);
6074 vm_state_notify(0);
6078 /* reset/shutdown handler */
6080 typedef struct QEMUResetEntry {
6081 QEMUResetHandler *func;
6082 void *opaque;
6083 struct QEMUResetEntry *next;
6084 } QEMUResetEntry;
6086 static QEMUResetEntry *first_reset_entry;
6087 static int reset_requested;
6088 static int shutdown_requested;
6089 static int powerdown_requested;
6091 int qemu_shutdown_requested(void)
6093 int r = shutdown_requested;
6094 shutdown_requested = 0;
6095 return r;
6098 int qemu_reset_requested(void)
6100 int r = reset_requested;
6101 reset_requested = 0;
6102 return r;
6105 int qemu_powerdown_requested(void)
6107 int r = powerdown_requested;
6108 powerdown_requested = 0;
6109 return r;
6112 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6114 QEMUResetEntry **pre, *re;
6116 pre = &first_reset_entry;
6117 while (*pre != NULL)
6118 pre = &(*pre)->next;
6119 re = qemu_mallocz(sizeof(QEMUResetEntry));
6120 re->func = func;
6121 re->opaque = opaque;
6122 re->next = NULL;
6123 *pre = re;
6126 void qemu_system_reset(void)
6128 QEMUResetEntry *re;
6130 /* reset all devices */
6131 for(re = first_reset_entry; re != NULL; re = re->next) {
6132 re->func(re->opaque);
6136 void qemu_system_reset_request(void)
6138 if (no_reboot) {
6139 shutdown_requested = 1;
6140 } else {
6141 reset_requested = 1;
6143 if (cpu_single_env)
6144 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6147 void qemu_system_shutdown_request(void)
6149 shutdown_requested = 1;
6150 if (cpu_single_env)
6151 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6154 void qemu_system_powerdown_request(void)
6156 powerdown_requested = 1;
6157 if (cpu_single_env)
6158 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6161 void main_loop_wait(int timeout)
6163 IOHandlerRecord *ioh;
6164 fd_set rfds, wfds, xfds;
6165 int ret, nfds;
6166 struct timeval tv;
6167 PollingEntry *pe;
6170 /* XXX: need to suppress polling by better using win32 events */
6171 ret = 0;
6172 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6173 ret |= pe->func(pe->opaque);
6175 #ifdef _WIN32
6176 if (ret == 0 && timeout > 0) {
6177 int err;
6178 WaitObjects *w = &wait_objects;
6180 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6181 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6182 if (w->func[ret - WAIT_OBJECT_0])
6183 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6184 } else if (ret == WAIT_TIMEOUT) {
6185 } else {
6186 err = GetLastError();
6187 fprintf(stderr, "Wait error %d %d\n", ret, err);
6190 #endif
6191 /* poll any events */
6192 /* XXX: separate device handlers from system ones */
6193 nfds = -1;
6194 FD_ZERO(&rfds);
6195 FD_ZERO(&wfds);
6196 FD_ZERO(&xfds);
6197 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6198 if (ioh->deleted)
6199 continue;
6200 if (ioh->fd_read &&
6201 (!ioh->fd_read_poll ||
6202 ioh->fd_read_poll(ioh->opaque) != 0)) {
6203 FD_SET(ioh->fd, &rfds);
6204 if (ioh->fd > nfds)
6205 nfds = ioh->fd;
6207 if (ioh->fd_write) {
6208 FD_SET(ioh->fd, &wfds);
6209 if (ioh->fd > nfds)
6210 nfds = ioh->fd;
6214 tv.tv_sec = 0;
6215 #ifdef _WIN32
6216 tv.tv_usec = 0;
6217 #else
6218 tv.tv_usec = timeout * 1000;
6219 #endif
6220 #if defined(CONFIG_SLIRP)
6221 if (slirp_inited) {
6222 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6224 #endif
6225 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6226 if (ret > 0) {
6227 IOHandlerRecord **pioh;
6229 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6230 if (ioh->deleted)
6231 continue;
6232 if (FD_ISSET(ioh->fd, &rfds)) {
6233 ioh->fd_read(ioh->opaque);
6235 if (FD_ISSET(ioh->fd, &wfds)) {
6236 ioh->fd_write(ioh->opaque);
6240 /* remove deleted IO handlers */
6241 pioh = &first_io_handler;
6242 while (*pioh) {
6243 ioh = *pioh;
6244 if (ioh->deleted) {
6245 *pioh = ioh->next;
6246 qemu_free(ioh);
6247 } else
6248 pioh = &ioh->next;
6251 #if defined(CONFIG_SLIRP)
6252 if (slirp_inited) {
6253 if (ret < 0) {
6254 FD_ZERO(&rfds);
6255 FD_ZERO(&wfds);
6256 FD_ZERO(&xfds);
6258 slirp_select_poll(&rfds, &wfds, &xfds);
6260 #endif
6261 qemu_aio_poll();
6262 qemu_bh_poll();
6264 if (vm_running) {
6265 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6266 qemu_get_clock(vm_clock));
6267 /* run dma transfers, if any */
6268 DMA_run();
6271 /* real time timers */
6272 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6273 qemu_get_clock(rt_clock));
6276 static CPUState *cur_cpu;
6278 int main_loop(void)
6280 int ret, timeout;
6281 #ifdef CONFIG_PROFILER
6282 int64_t ti;
6283 #endif
6284 CPUState *env;
6287 #ifdef USE_KVM
6288 if (kvm_allowed) {
6289 kvm_main_loop();
6290 cpu_disable_ticks();
6291 return 0;
6293 #endif
6294 cur_cpu = first_cpu;
6295 for(;;) {
6296 if (vm_running) {
6298 env = cur_cpu;
6299 for(;;) {
6300 /* get next cpu */
6301 env = env->next_cpu;
6302 if (!env)
6303 env = first_cpu;
6304 #ifdef CONFIG_PROFILER
6305 ti = profile_getclock();
6306 #endif
6307 ret = cpu_exec(env);
6308 #ifdef CONFIG_PROFILER
6309 qemu_time += profile_getclock() - ti;
6310 #endif
6311 if (ret != EXCP_HALTED)
6312 break;
6313 /* all CPUs are halted ? */
6314 if (env == cur_cpu) {
6315 ret = EXCP_HLT;
6316 break;
6319 cur_cpu = env;
6321 if (shutdown_requested) {
6322 ret = EXCP_INTERRUPT;
6323 break;
6325 if (reset_requested) {
6326 reset_requested = 0;
6327 qemu_system_reset();
6328 #ifdef USE_KVM
6329 if (kvm_allowed)
6330 kvm_load_registers(env);
6331 #endif
6332 ret = EXCP_INTERRUPT;
6334 if (powerdown_requested) {
6335 powerdown_requested = 0;
6336 qemu_system_powerdown();
6337 ret = EXCP_INTERRUPT;
6339 if (ret == EXCP_DEBUG) {
6340 vm_stop(EXCP_DEBUG);
6342 /* if hlt instruction, we wait until the next IRQ */
6343 /* XXX: use timeout computed from timers */
6344 if (ret == EXCP_HLT)
6345 timeout = 10;
6346 else
6347 timeout = 0;
6348 } else {
6349 timeout = 10;
6351 #ifdef CONFIG_PROFILER
6352 ti = profile_getclock();
6353 #endif
6354 main_loop_wait(timeout);
6355 #ifdef CONFIG_PROFILER
6356 dev_time += profile_getclock() - ti;
6357 #endif
6359 cpu_disable_ticks();
6360 return ret;
6363 void help(void)
6365 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6366 "usage: %s [options] [disk_image]\n"
6367 "\n"
6368 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6369 "\n"
6370 "Standard options:\n"
6371 "-M machine select emulated machine (-M ? for list)\n"
6372 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6373 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6374 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6375 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6376 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6377 "-snapshot write to temporary files instead of disk image files\n"
6378 #ifdef CONFIG_SDL
6379 "-no-quit disable SDL window close capability\n"
6380 #endif
6381 #ifdef TARGET_I386
6382 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6383 #endif
6384 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6385 "-smp n set the number of CPUs to 'n' [default=1]\n"
6386 "-nographic disable graphical output and redirect serial I/Os to console\n"
6387 #ifndef _WIN32
6388 "-k language use keyboard layout (for example \"fr\" for French)\n"
6389 #endif
6390 #ifdef HAS_AUDIO
6391 "-audio-help print list of audio drivers and their options\n"
6392 "-soundhw c1,... enable audio support\n"
6393 " and only specified sound cards (comma separated list)\n"
6394 " use -soundhw ? to get the list of supported cards\n"
6395 " use -soundhw all to enable all of them\n"
6396 #endif
6397 "-localtime set the real time clock to local time [default=utc]\n"
6398 "-full-screen start in full screen\n"
6399 #ifdef TARGET_I386
6400 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6401 #endif
6402 "-usb enable the USB driver (will be the default soon)\n"
6403 "-usbdevice name add the host or guest USB device 'name'\n"
6404 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6405 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6406 #endif
6407 "\n"
6408 "Network options:\n"
6409 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6410 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6411 #ifdef CONFIG_SLIRP
6412 "-net user[,vlan=n][,hostname=host]\n"
6413 " connect the user mode network stack to VLAN 'n' and send\n"
6414 " hostname 'host' to DHCP clients\n"
6415 #endif
6416 #ifdef _WIN32
6417 "-net tap[,vlan=n],ifname=name\n"
6418 " connect the host TAP network interface to VLAN 'n'\n"
6419 #else
6420 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6421 " connect the host TAP network interface to VLAN 'n' and use\n"
6422 " the network script 'file' (default=%s);\n"
6423 " use 'script=no' to disable script execution;\n"
6424 " use 'fd=h' to connect to an already opened TAP interface\n"
6425 #endif
6426 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6427 " connect the vlan 'n' to another VLAN using a socket connection\n"
6428 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6429 " connect the vlan 'n' to multicast maddr and port\n"
6430 "-net none use it alone to have zero network devices; if no -net option\n"
6431 " is provided, the default is '-net nic -net user'\n"
6432 "\n"
6433 #ifdef CONFIG_SLIRP
6434 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6435 #ifndef _WIN32
6436 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6437 #endif
6438 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6439 " redirect TCP or UDP connections from host to guest [-net user]\n"
6440 #endif
6441 "\n"
6442 "Linux boot specific:\n"
6443 "-kernel bzImage use 'bzImage' as kernel image\n"
6444 "-append cmdline use 'cmdline' as kernel command line\n"
6445 "-initrd file use 'file' as initial ram disk\n"
6446 "\n"
6447 "Debug/Expert options:\n"
6448 "-monitor dev redirect the monitor to char device 'dev'\n"
6449 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6450 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
6451 "-serial dev redirect the serial port to char device 'dev'\n"
6452 "-parallel dev redirect the parallel port to char device 'dev'\n"
6453 "-pidfile file Write PID to 'file'\n"
6454 "-S freeze CPU at startup (use 'c' to start execution)\n"
6455 "-s wait gdb connection to port %d\n"
6456 "-p port change gdb connection port\n"
6457 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6458 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6459 " translation (t=none or lba) (usually qemu can guess them)\n"
6460 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6461 #ifdef USE_KQEMU
6462 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6463 "-no-kqemu disable KQEMU kernel module usage\n"
6464 #endif
6465 #ifdef USE_KVM
6466 "-no-kvm disable KVM hardware virtualization\n"
6467 #endif
6468 #ifdef USE_CODE_COPY
6469 "-no-code-copy disable code copy acceleration\n"
6470 #endif
6471 #ifdef TARGET_I386
6472 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6473 " (default is CL-GD5446 PCI VGA)\n"
6474 "-no-acpi disable ACPI\n"
6475 #endif
6476 "-no-reboot exit instead of rebooting\n"
6477 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6478 "-vnc display start a VNC server on display\n"
6479 #ifndef _WIN32
6480 "-daemonize daemonize QEMU after initializing\n"
6481 #endif
6482 "-tdf inject timer interrupts that got lost\n"
6483 #if defined(__linux__)
6484 "-no-rtc don't use /dev/rtc for timer alarm (do use gettimeofday)\n"
6485 #endif
6486 "-option-rom rom load a file, rom, into the option ROM space\n"
6487 "\n"
6488 "During emulation, the following keys are useful:\n"
6489 "ctrl-alt-f toggle full screen\n"
6490 "ctrl-alt-n switch to virtual console 'n'\n"
6491 "ctrl-alt toggle mouse and keyboard grab\n"
6492 "\n"
6493 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6495 "qemu",
6496 DEFAULT_RAM_SIZE,
6497 #ifndef _WIN32
6498 DEFAULT_NETWORK_SCRIPT,
6499 #endif
6500 DEFAULT_GDBSTUB_PORT,
6501 "/tmp/qemu.log");
6502 exit(1);
6505 #define HAS_ARG 0x0001
6507 enum {
6508 QEMU_OPTION_h,
6510 QEMU_OPTION_M,
6511 QEMU_OPTION_fda,
6512 QEMU_OPTION_fdb,
6513 QEMU_OPTION_hda,
6514 QEMU_OPTION_hdb,
6515 QEMU_OPTION_hdc,
6516 QEMU_OPTION_hdd,
6517 QEMU_OPTION_cdrom,
6518 QEMU_OPTION_boot,
6519 QEMU_OPTION_snapshot,
6520 #ifdef TARGET_I386
6521 QEMU_OPTION_no_fd_bootchk,
6522 #endif
6523 QEMU_OPTION_m,
6524 QEMU_OPTION_nographic,
6525 #ifdef HAS_AUDIO
6526 QEMU_OPTION_audio_help,
6527 QEMU_OPTION_soundhw,
6528 #endif
6530 QEMU_OPTION_net,
6531 QEMU_OPTION_tftp,
6532 QEMU_OPTION_smb,
6533 QEMU_OPTION_redir,
6535 QEMU_OPTION_kernel,
6536 QEMU_OPTION_append,
6537 QEMU_OPTION_initrd,
6539 QEMU_OPTION_S,
6540 QEMU_OPTION_s,
6541 QEMU_OPTION_p,
6542 QEMU_OPTION_d,
6543 QEMU_OPTION_hdachs,
6544 QEMU_OPTION_L,
6545 QEMU_OPTION_no_code_copy,
6546 QEMU_OPTION_k,
6547 QEMU_OPTION_localtime,
6548 QEMU_OPTION_cirrusvga,
6549 QEMU_OPTION_g,
6550 QEMU_OPTION_std_vga,
6551 QEMU_OPTION_monitor,
6552 QEMU_OPTION_balloon,
6553 QEMU_OPTION_vmchannel,
6554 QEMU_OPTION_serial,
6555 QEMU_OPTION_parallel,
6556 QEMU_OPTION_loadvm,
6557 QEMU_OPTION_full_screen,
6558 QEMU_OPTION_no_quit,
6559 QEMU_OPTION_pidfile,
6560 QEMU_OPTION_no_kqemu,
6561 QEMU_OPTION_kernel_kqemu,
6562 QEMU_OPTION_win2k_hack,
6563 QEMU_OPTION_usb,
6564 QEMU_OPTION_usbdevice,
6565 QEMU_OPTION_smp,
6566 QEMU_OPTION_vnc,
6567 QEMU_OPTION_no_acpi,
6568 QEMU_OPTION_no_kvm,
6569 QEMU_OPTION_no_reboot,
6570 QEMU_OPTION_daemonize,
6571 QEMU_OPTION_option_rom,
6572 QEMU_OPTION_semihosting,
6573 QEMU_OPTION_incoming,
6574 QEMU_OPTION_tdf,
6575 #if defined(__linux__)
6576 QEMU_OPTION_no_rtc,
6577 #endif
6578 QEMU_OPTION_cpu_vendor,
6581 typedef struct QEMUOption {
6582 const char *name;
6583 int flags;
6584 int index;
6585 } QEMUOption;
6587 const QEMUOption qemu_options[] = {
6588 { "h", 0, QEMU_OPTION_h },
6589 { "help", 0, QEMU_OPTION_h },
6591 { "M", HAS_ARG, QEMU_OPTION_M },
6592 { "fda", HAS_ARG, QEMU_OPTION_fda },
6593 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6594 { "hda", HAS_ARG, QEMU_OPTION_hda },
6595 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6596 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6597 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6598 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6599 { "boot", HAS_ARG, QEMU_OPTION_boot },
6600 { "snapshot", 0, QEMU_OPTION_snapshot },
6601 #ifdef TARGET_I386
6602 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6603 #endif
6604 { "m", HAS_ARG, QEMU_OPTION_m },
6605 { "nographic", 0, QEMU_OPTION_nographic },
6606 { "k", HAS_ARG, QEMU_OPTION_k },
6607 #ifdef HAS_AUDIO
6608 { "audio-help", 0, QEMU_OPTION_audio_help },
6609 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6610 #endif
6612 { "net", HAS_ARG, QEMU_OPTION_net},
6613 #ifdef CONFIG_SLIRP
6614 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6615 #ifndef _WIN32
6616 { "smb", HAS_ARG, QEMU_OPTION_smb },
6617 #endif
6618 { "redir", HAS_ARG, QEMU_OPTION_redir },
6619 #endif
6621 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6622 { "append", HAS_ARG, QEMU_OPTION_append },
6623 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6625 { "S", 0, QEMU_OPTION_S },
6626 { "s", 0, QEMU_OPTION_s },
6627 { "p", HAS_ARG, QEMU_OPTION_p },
6628 { "d", HAS_ARG, QEMU_OPTION_d },
6629 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6630 { "L", HAS_ARG, QEMU_OPTION_L },
6631 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6632 #ifdef USE_KQEMU
6633 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6634 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6635 #endif
6636 #ifdef USE_KVM
6637 { "no-kvm", 0, QEMU_OPTION_no_kvm },
6638 #endif
6639 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6640 { "g", 1, QEMU_OPTION_g },
6641 #endif
6642 { "localtime", 0, QEMU_OPTION_localtime },
6643 { "std-vga", 0, QEMU_OPTION_std_vga },
6644 { "monitor", 1, QEMU_OPTION_monitor },
6645 { "balloon", 1, QEMU_OPTION_balloon },
6646 { "vmchannel", 1, QEMU_OPTION_vmchannel },
6647 { "serial", 1, QEMU_OPTION_serial },
6648 { "parallel", 1, QEMU_OPTION_parallel },
6649 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6650 { "incoming", 1, QEMU_OPTION_incoming },
6651 { "full-screen", 0, QEMU_OPTION_full_screen },
6652 #ifdef CONFIG_SDL
6653 { "no-quit", 0, QEMU_OPTION_no_quit },
6654 #endif
6655 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6656 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6657 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6658 { "smp", HAS_ARG, QEMU_OPTION_smp },
6659 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6661 /* temporary options */
6662 { "usb", 0, QEMU_OPTION_usb },
6663 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6664 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6665 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6666 { "daemonize", 0, QEMU_OPTION_daemonize },
6667 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6668 #if defined(TARGET_ARM)
6669 { "semihosting", 0, QEMU_OPTION_semihosting },
6670 #endif
6671 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
6672 #if defined(__linux__)
6673 { "no-rtc", 0, QEMU_OPTION_no_rtc },
6674 #endif
6675 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
6676 { NULL },
6679 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6681 /* this stack is only used during signal handling */
6682 #define SIGNAL_STACK_SIZE 32768
6684 static uint8_t *signal_stack;
6686 #endif
6688 /* password input */
6690 static BlockDriverState *get_bdrv(int index)
6692 BlockDriverState *bs;
6694 if (index < 4) {
6695 bs = bs_table[index];
6696 } else if (index < 6) {
6697 bs = fd_table[index - 4];
6698 } else {
6699 bs = NULL;
6701 return bs;
6704 static void read_passwords(void)
6706 BlockDriverState *bs;
6707 int i, j;
6708 char password[256];
6710 for(i = 0; i < 6; i++) {
6711 bs = get_bdrv(i);
6712 if (bs && bdrv_is_encrypted(bs)) {
6713 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6714 for(j = 0; j < 3; j++) {
6715 monitor_readline("Password: ",
6716 1, password, sizeof(password));
6717 if (bdrv_set_key(bs, password) == 0)
6718 break;
6719 term_printf("invalid password\n");
6725 /* XXX: currently we cannot use simultaneously different CPUs */
6726 void register_machines(void)
6728 #if defined(TARGET_I386)
6729 qemu_register_machine(&pc_machine);
6730 qemu_register_machine(&isapc_machine);
6731 #elif defined(TARGET_PPC)
6732 qemu_register_machine(&heathrow_machine);
6733 qemu_register_machine(&core99_machine);
6734 qemu_register_machine(&prep_machine);
6735 #elif defined(TARGET_MIPS)
6736 qemu_register_machine(&mips_machine);
6737 qemu_register_machine(&mips_malta_machine);
6738 #elif defined(TARGET_SPARC)
6739 #ifdef TARGET_SPARC64
6740 qemu_register_machine(&sun4u_machine);
6741 #else
6742 qemu_register_machine(&sun4m_machine);
6743 #endif
6744 #elif defined(TARGET_ARM)
6745 qemu_register_machine(&integratorcp926_machine);
6746 qemu_register_machine(&integratorcp1026_machine);
6747 qemu_register_machine(&versatilepb_machine);
6748 qemu_register_machine(&versatileab_machine);
6749 qemu_register_machine(&realview_machine);
6750 #elif defined(TARGET_SH4)
6751 qemu_register_machine(&shix_machine);
6752 #else
6753 #error unsupported CPU
6754 #endif
6757 #ifdef HAS_AUDIO
6758 struct soundhw soundhw[] = {
6759 #ifdef TARGET_I386
6761 "pcspk",
6762 "PC speaker",
6765 { .init_isa = pcspk_audio_init }
6767 #endif
6769 "sb16",
6770 "Creative Sound Blaster 16",
6773 { .init_isa = SB16_init }
6776 #ifdef CONFIG_ADLIB
6778 "adlib",
6779 #ifdef HAS_YMF262
6780 "Yamaha YMF262 (OPL3)",
6781 #else
6782 "Yamaha YM3812 (OPL2)",
6783 #endif
6786 { .init_isa = Adlib_init }
6788 #endif
6790 #ifdef CONFIG_GUS
6792 "gus",
6793 "Gravis Ultrasound GF1",
6796 { .init_isa = GUS_init }
6798 #endif
6801 "es1370",
6802 "ENSONIQ AudioPCI ES1370",
6805 { .init_pci = es1370_init }
6808 { NULL, NULL, 0, 0, { NULL } }
6811 static void select_soundhw (const char *optarg)
6813 struct soundhw *c;
6815 if (*optarg == '?') {
6816 show_valid_cards:
6818 printf ("Valid sound card names (comma separated):\n");
6819 for (c = soundhw; c->name; ++c) {
6820 printf ("%-11s %s\n", c->name, c->descr);
6822 printf ("\n-soundhw all will enable all of the above\n");
6823 exit (*optarg != '?');
6825 else {
6826 size_t l;
6827 const char *p;
6828 char *e;
6829 int bad_card = 0;
6831 if (!strcmp (optarg, "all")) {
6832 for (c = soundhw; c->name; ++c) {
6833 c->enabled = 1;
6835 return;
6838 p = optarg;
6839 while (*p) {
6840 e = strchr (p, ',');
6841 l = !e ? strlen (p) : (size_t) (e - p);
6843 for (c = soundhw; c->name; ++c) {
6844 if (!strncmp (c->name, p, l)) {
6845 c->enabled = 1;
6846 break;
6850 if (!c->name) {
6851 if (l > 80) {
6852 fprintf (stderr,
6853 "Unknown sound card name (too big to show)\n");
6855 else {
6856 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6857 (int) l, p);
6859 bad_card = 1;
6861 p += l + (e != NULL);
6864 if (bad_card)
6865 goto show_valid_cards;
6868 #endif
6870 #ifdef _WIN32
6871 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6873 exit(STATUS_CONTROL_C_EXIT);
6874 return TRUE;
6876 #endif
6878 #define MAX_NET_CLIENTS 32
6880 static int saved_argc;
6881 static char **saved_argv;
6883 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
6885 *argc = saved_argc;
6886 *argv = saved_argv;
6887 *opt_daemonize = daemonize;
6888 *opt_incoming = incoming;
6891 int main(int argc, char **argv)
6893 #ifdef CONFIG_GDBSTUB
6894 int use_gdbstub, gdbstub_port;
6895 #endif
6896 int i, cdrom_index;
6897 int snapshot, linux_boot;
6898 const char *initrd_filename;
6899 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6900 const char *kernel_filename, *kernel_cmdline;
6901 DisplayState *ds = &display_state;
6902 int cyls, heads, secs, translation;
6903 char net_clients[MAX_NET_CLIENTS][256];
6904 int nb_net_clients;
6905 int optind;
6906 const char *r, *optarg;
6907 CharDriverState *monitor_hd;
6908 char monitor_device[128];
6909 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
6910 int vmchannel_device_index;
6911 char serial_devices[MAX_SERIAL_PORTS][128];
6912 int serial_device_index;
6913 char parallel_devices[MAX_PARALLEL_PORTS][128];
6914 int parallel_device_index;
6915 const char *loadvm = NULL;
6916 QEMUMachine *machine;
6917 char usb_devices[MAX_USB_CMDLINE][128];
6918 int usb_devices_index;
6919 int fds[2];
6921 saved_argc = argc;
6922 saved_argv = argv;
6924 LIST_INIT (&vm_change_state_head);
6925 #ifndef _WIN32
6927 struct sigaction act;
6928 sigfillset(&act.sa_mask);
6929 act.sa_flags = 0;
6930 act.sa_handler = SIG_IGN;
6931 sigaction(SIGPIPE, &act, NULL);
6933 #else
6934 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6935 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6936 QEMU to run on a single CPU */
6938 HANDLE h;
6939 DWORD mask, smask;
6940 int i;
6941 h = GetCurrentProcess();
6942 if (GetProcessAffinityMask(h, &mask, &smask)) {
6943 for(i = 0; i < 32; i++) {
6944 if (mask & (1 << i))
6945 break;
6947 if (i != 32) {
6948 mask = 1 << i;
6949 SetProcessAffinityMask(h, mask);
6953 #endif
6955 register_machines();
6956 machine = first_machine;
6957 initrd_filename = NULL;
6958 for(i = 0; i < MAX_FD; i++)
6959 fd_filename[i] = NULL;
6960 for(i = 0; i < MAX_DISKS; i++)
6961 hd_filename[i] = NULL;
6962 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6963 vga_ram_size = VGA_RAM_SIZE;
6964 bios_size = BIOS_SIZE;
6965 #ifdef CONFIG_GDBSTUB
6966 use_gdbstub = 0;
6967 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6968 #endif
6969 snapshot = 0;
6970 nographic = 0;
6971 kernel_filename = NULL;
6972 kernel_cmdline = "";
6973 #ifdef TARGET_PPC
6974 cdrom_index = 1;
6975 #else
6976 cdrom_index = 2;
6977 #endif
6978 cyls = heads = secs = 0;
6979 translation = BIOS_ATA_TRANSLATION_AUTO;
6980 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6982 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
6983 vmchannel_devices[i][0] = '\0';
6984 vmchannel_device_index = 0;
6986 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6987 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6988 serial_devices[i][0] = '\0';
6989 serial_device_index = 0;
6991 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6992 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6993 parallel_devices[i][0] = '\0';
6994 parallel_device_index = 0;
6996 usb_devices_index = 0;
6998 nb_net_clients = 0;
7000 nb_nics = 0;
7001 /* default mac address of the first network interface */
7003 optind = 1;
7004 for(;;) {
7005 if (optind >= argc)
7006 break;
7007 r = argv[optind];
7008 if (r[0] != '-') {
7009 hd_filename[0] = argv[optind++];
7010 } else {
7011 const QEMUOption *popt;
7013 optind++;
7014 /* Treat --foo the same as -foo. */
7015 if (r[1] == '-')
7016 r++;
7017 popt = qemu_options;
7018 for(;;) {
7019 if (!popt->name) {
7020 fprintf(stderr, "%s: invalid option -- '%s'\n",
7021 argv[0], r);
7022 exit(1);
7024 if (!strcmp(popt->name, r + 1))
7025 break;
7026 popt++;
7028 if (popt->flags & HAS_ARG) {
7029 if (optind >= argc) {
7030 fprintf(stderr, "%s: option '%s' requires an argument\n",
7031 argv[0], r);
7032 exit(1);
7034 optarg = argv[optind++];
7035 } else {
7036 optarg = NULL;
7039 switch(popt->index) {
7040 case QEMU_OPTION_M:
7041 machine = find_machine(optarg);
7042 if (!machine) {
7043 QEMUMachine *m;
7044 printf("Supported machines are:\n");
7045 for(m = first_machine; m != NULL; m = m->next) {
7046 printf("%-10s %s%s\n",
7047 m->name, m->desc,
7048 m == first_machine ? " (default)" : "");
7050 exit(1);
7052 break;
7053 case QEMU_OPTION_initrd:
7054 initrd_filename = optarg;
7055 break;
7056 case QEMU_OPTION_hda:
7057 case QEMU_OPTION_hdb:
7058 case QEMU_OPTION_hdc:
7059 case QEMU_OPTION_hdd:
7061 int hd_index;
7062 hd_index = popt->index - QEMU_OPTION_hda;
7063 hd_filename[hd_index] = optarg;
7064 if (hd_index == cdrom_index)
7065 cdrom_index = -1;
7067 break;
7068 case QEMU_OPTION_snapshot:
7069 snapshot = 1;
7070 break;
7071 case QEMU_OPTION_hdachs:
7073 const char *p;
7074 p = optarg;
7075 cyls = strtol(p, (char **)&p, 0);
7076 if (cyls < 1 || cyls > 16383)
7077 goto chs_fail;
7078 if (*p != ',')
7079 goto chs_fail;
7080 p++;
7081 heads = strtol(p, (char **)&p, 0);
7082 if (heads < 1 || heads > 16)
7083 goto chs_fail;
7084 if (*p != ',')
7085 goto chs_fail;
7086 p++;
7087 secs = strtol(p, (char **)&p, 0);
7088 if (secs < 1 || secs > 63)
7089 goto chs_fail;
7090 if (*p == ',') {
7091 p++;
7092 if (!strcmp(p, "none"))
7093 translation = BIOS_ATA_TRANSLATION_NONE;
7094 else if (!strcmp(p, "lba"))
7095 translation = BIOS_ATA_TRANSLATION_LBA;
7096 else if (!strcmp(p, "auto"))
7097 translation = BIOS_ATA_TRANSLATION_AUTO;
7098 else
7099 goto chs_fail;
7100 } else if (*p != '\0') {
7101 chs_fail:
7102 fprintf(stderr, "qemu: invalid physical CHS format\n");
7103 exit(1);
7106 break;
7107 case QEMU_OPTION_nographic:
7108 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7109 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7110 nographic = 1;
7111 break;
7112 case QEMU_OPTION_kernel:
7113 kernel_filename = optarg;
7114 break;
7115 case QEMU_OPTION_append:
7116 kernel_cmdline = optarg;
7117 break;
7118 case QEMU_OPTION_cdrom:
7119 if (cdrom_index >= 0) {
7120 hd_filename[cdrom_index] = optarg;
7122 break;
7123 case QEMU_OPTION_boot:
7124 boot_device = optarg[0];
7125 if (boot_device != 'a' &&
7126 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7127 // Network boot
7128 boot_device != 'n' &&
7129 #endif
7130 boot_device != 'c' && boot_device != 'd') {
7131 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7132 exit(1);
7134 break;
7135 case QEMU_OPTION_fda:
7136 fd_filename[0] = optarg;
7137 break;
7138 case QEMU_OPTION_fdb:
7139 fd_filename[1] = optarg;
7140 break;
7141 #ifdef TARGET_I386
7142 case QEMU_OPTION_no_fd_bootchk:
7143 fd_bootchk = 0;
7144 break;
7145 #endif
7146 case QEMU_OPTION_no_code_copy:
7147 code_copy_enabled = 0;
7148 break;
7149 case QEMU_OPTION_net:
7150 if (nb_net_clients >= MAX_NET_CLIENTS) {
7151 fprintf(stderr, "qemu: too many network clients\n");
7152 exit(1);
7154 pstrcpy(net_clients[nb_net_clients],
7155 sizeof(net_clients[0]),
7156 optarg);
7157 nb_net_clients++;
7158 break;
7159 #ifdef CONFIG_SLIRP
7160 case QEMU_OPTION_tftp:
7161 tftp_prefix = optarg;
7162 break;
7163 #ifndef _WIN32
7164 case QEMU_OPTION_smb:
7165 net_slirp_smb(optarg);
7166 break;
7167 #endif
7168 case QEMU_OPTION_redir:
7169 net_slirp_redir(optarg);
7170 break;
7171 #endif
7172 #ifdef HAS_AUDIO
7173 case QEMU_OPTION_audio_help:
7174 AUD_help ();
7175 exit (0);
7176 break;
7177 case QEMU_OPTION_soundhw:
7178 select_soundhw (optarg);
7179 break;
7180 #endif
7181 case QEMU_OPTION_h:
7182 help();
7183 break;
7184 case QEMU_OPTION_m:
7185 ram_size = atoi(optarg) * 1024 * 1024;
7186 if (ram_size <= 0)
7187 help();
7188 if (ram_size > PHYS_RAM_MAX_SIZE) {
7189 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7190 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7191 exit(1);
7193 break;
7194 case QEMU_OPTION_d:
7196 int mask;
7197 CPULogItem *item;
7199 mask = cpu_str_to_log_mask(optarg);
7200 if (!mask) {
7201 printf("Log items (comma separated):\n");
7202 for(item = cpu_log_items; item->mask != 0; item++) {
7203 printf("%-10s %s\n", item->name, item->help);
7205 exit(1);
7207 cpu_set_log(mask);
7209 break;
7210 #ifdef CONFIG_GDBSTUB
7211 case QEMU_OPTION_s:
7212 use_gdbstub = 1;
7213 break;
7214 case QEMU_OPTION_p:
7215 gdbstub_port = atoi(optarg);
7216 break;
7217 #endif
7218 case QEMU_OPTION_L:
7219 bios_dir = optarg;
7220 break;
7221 case QEMU_OPTION_S:
7222 autostart = 0;
7223 break;
7224 case QEMU_OPTION_k:
7225 keyboard_layout = optarg;
7226 break;
7227 case QEMU_OPTION_localtime:
7228 rtc_utc = 0;
7229 break;
7230 case QEMU_OPTION_cirrusvga:
7231 cirrus_vga_enabled = 1;
7232 break;
7233 case QEMU_OPTION_std_vga:
7234 cirrus_vga_enabled = 0;
7235 break;
7236 case QEMU_OPTION_g:
7238 const char *p;
7239 int w, h, depth;
7240 p = optarg;
7241 w = strtol(p, (char **)&p, 10);
7242 if (w <= 0) {
7243 graphic_error:
7244 fprintf(stderr, "qemu: invalid resolution or depth\n");
7245 exit(1);
7247 if (*p != 'x')
7248 goto graphic_error;
7249 p++;
7250 h = strtol(p, (char **)&p, 10);
7251 if (h <= 0)
7252 goto graphic_error;
7253 if (*p == 'x') {
7254 p++;
7255 depth = strtol(p, (char **)&p, 10);
7256 if (depth != 8 && depth != 15 && depth != 16 &&
7257 depth != 24 && depth != 32)
7258 goto graphic_error;
7259 } else if (*p == '\0') {
7260 depth = graphic_depth;
7261 } else {
7262 goto graphic_error;
7265 graphic_width = w;
7266 graphic_height = h;
7267 graphic_depth = depth;
7269 break;
7270 case QEMU_OPTION_monitor:
7271 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7272 break;
7273 case QEMU_OPTION_balloon:
7274 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7275 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7276 exit(1);
7278 if (balloon_used) {
7279 fprintf(stderr, "qemu: only one balloon device can be used\n");
7280 exit(1);
7282 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
7283 vmchannel_device_index++;
7284 balloon_used = 1;
7285 break;
7286 case QEMU_OPTION_vmchannel:
7287 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
7288 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
7289 exit(1);
7291 pstrcpy(vmchannel_devices[vmchannel_device_index],
7292 sizeof(vmchannel_devices[0]), optarg);
7293 vmchannel_device_index++;
7294 break;
7295 case QEMU_OPTION_serial:
7296 if (serial_device_index >= MAX_SERIAL_PORTS) {
7297 fprintf(stderr, "qemu: too many serial ports\n");
7298 exit(1);
7300 pstrcpy(serial_devices[serial_device_index],
7301 sizeof(serial_devices[0]), optarg);
7302 serial_device_index++;
7303 break;
7304 case QEMU_OPTION_parallel:
7305 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7306 fprintf(stderr, "qemu: too many parallel ports\n");
7307 exit(1);
7309 pstrcpy(parallel_devices[parallel_device_index],
7310 sizeof(parallel_devices[0]), optarg);
7311 parallel_device_index++;
7312 break;
7313 case QEMU_OPTION_loadvm:
7314 loadvm = optarg;
7315 break;
7316 case QEMU_OPTION_incoming:
7317 incoming = optarg;
7318 break;
7319 case QEMU_OPTION_full_screen:
7320 full_screen = 1;
7321 break;
7322 #ifdef CONFIG_SDL
7323 case QEMU_OPTION_no_quit:
7324 no_quit = 1;
7325 break;
7326 #endif
7327 case QEMU_OPTION_pidfile:
7328 create_pidfile(optarg);
7329 break;
7330 #ifdef TARGET_I386
7331 case QEMU_OPTION_win2k_hack:
7332 win2k_install_hack = 1;
7333 break;
7334 #endif
7335 #ifdef USE_KQEMU
7336 case QEMU_OPTION_no_kqemu:
7337 kqemu_allowed = 0;
7338 break;
7339 case QEMU_OPTION_kernel_kqemu:
7340 kqemu_allowed = 2;
7341 break;
7342 #endif
7343 #ifdef USE_KVM
7344 case QEMU_OPTION_no_kvm:
7345 kvm_allowed = 0;
7346 break;
7347 #endif
7348 case QEMU_OPTION_usb:
7349 usb_enabled = 1;
7350 break;
7351 case QEMU_OPTION_usbdevice:
7352 usb_enabled = 1;
7353 if (usb_devices_index >= MAX_USB_CMDLINE) {
7354 fprintf(stderr, "Too many USB devices\n");
7355 exit(1);
7357 pstrcpy(usb_devices[usb_devices_index],
7358 sizeof(usb_devices[usb_devices_index]),
7359 optarg);
7360 usb_devices_index++;
7361 break;
7362 case QEMU_OPTION_smp:
7363 smp_cpus = atoi(optarg);
7364 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7365 fprintf(stderr, "Invalid number of CPUs\n");
7366 exit(1);
7368 break;
7369 case QEMU_OPTION_vnc:
7370 vnc_display = optarg;
7371 break;
7372 case QEMU_OPTION_no_acpi:
7373 acpi_enabled = 0;
7374 break;
7375 case QEMU_OPTION_no_reboot:
7376 no_reboot = 1;
7377 break;
7378 case QEMU_OPTION_daemonize:
7379 daemonize = 1;
7380 break;
7381 case QEMU_OPTION_option_rom:
7382 if (nb_option_roms >= MAX_OPTION_ROMS) {
7383 fprintf(stderr, "Too many option ROMs\n");
7384 exit(1);
7386 option_rom[nb_option_roms] = optarg;
7387 nb_option_roms++;
7388 break;
7389 case QEMU_OPTION_semihosting:
7390 semihosting_enabled = 1;
7391 break;
7392 case QEMU_OPTION_tdf:
7393 time_drift_fix = 1;
7394 #if defined(__linux__)
7395 case QEMU_OPTION_no_rtc:
7396 use_rtc = 0;
7397 break;
7398 #endif
7399 case QEMU_OPTION_cpu_vendor:
7400 cpu_vendor_string = optarg;
7401 break;
7406 #ifndef _WIN32
7407 if (daemonize) {
7408 pid_t pid;
7410 if (pipe(fds) == -1)
7411 exit(1);
7413 pid = fork();
7414 if (pid > 0) {
7415 uint8_t status;
7416 ssize_t len;
7418 close(fds[1]);
7420 again:
7421 len = read(fds[0], &status, 1);
7422 if (len == -1 && (errno == EINTR))
7423 goto again;
7425 if (len != 1 || status != 0)
7426 exit(1);
7427 else
7428 exit(0);
7429 } else if (pid < 0)
7430 exit(1);
7432 setsid();
7434 pid = fork();
7435 if (pid > 0)
7436 exit(0);
7437 else if (pid < 0)
7438 exit(1);
7440 umask(027);
7442 signal(SIGTSTP, SIG_IGN);
7443 signal(SIGTTOU, SIG_IGN);
7444 signal(SIGTTIN, SIG_IGN);
7446 #endif
7448 #if USE_KVM
7449 if (kvm_allowed) {
7450 if (kvm_qemu_init() < 0) {
7451 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
7452 kvm_allowed = 0;
7455 #endif
7457 #ifdef USE_KQEMU
7458 if (smp_cpus > 1)
7459 kqemu_allowed = 0;
7460 #endif
7461 linux_boot = (kernel_filename != NULL);
7463 if (!linux_boot &&
7464 hd_filename[0] == '\0' &&
7465 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7466 fd_filename[0] == '\0')
7467 help();
7469 /* boot to floppy or the default cd if no hard disk defined yet */
7470 if (hd_filename[0] == '\0' && boot_device == 'c') {
7471 if (fd_filename[0] != '\0')
7472 boot_device = 'a';
7473 else
7474 boot_device = 'd';
7477 setvbuf(stdout, NULL, _IOLBF, 0);
7479 init_timers();
7480 init_timer_alarm();
7481 qemu_aio_init();
7483 #ifdef _WIN32
7484 socket_init();
7485 #endif
7487 /* init network clients */
7488 if (nb_net_clients == 0) {
7489 /* if no clients, we use a default config */
7490 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7491 "nic");
7492 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7493 "user");
7494 nb_net_clients = 2;
7497 for(i = 0;i < nb_net_clients; i++) {
7498 if (net_client_init(net_clients[i]) < 0)
7499 exit(1);
7502 #ifdef TARGET_I386
7503 if (boot_device == 'n') {
7504 for (i = 0; i < nb_nics; i++) {
7505 const char *model = nd_table[i].model;
7506 char buf[1024];
7507 if (model == NULL)
7508 model = "ne2k_pci";
7509 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7510 if (get_image_size(buf) > 0) {
7511 option_rom[nb_option_roms] = strdup(buf);
7512 nb_option_roms++;
7513 break;
7516 if (i == nb_nics) {
7517 fprintf(stderr, "No valid PXE rom found for network device\n");
7518 exit(1);
7520 boot_device = 'c'; /* to prevent confusion by the BIOS */
7522 #endif
7524 /* init the memory */
7525 phys_ram_size = ram_size + vga_ram_size + bios_size;
7528 for (i = 0; i < nb_option_roms; i++) {
7529 int ret = get_image_size(option_rom[i]);
7530 if (ret == -1) {
7531 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7532 exit(1);
7534 phys_ram_size += ret;
7537 #if USE_KVM
7538 /* Initialize kvm */
7539 if (kvm_allowed) {
7540 phys_ram_size += KVM_EXTRA_PAGES * 4096;
7541 if (kvm_qemu_create_context() < 0) {
7542 fprintf(stderr, "Could not create KVM context\n");
7543 exit(1);
7545 } else {
7546 phys_ram_base = qemu_vmalloc(phys_ram_size);
7547 if (!phys_ram_base) {
7548 fprintf(stderr, "Could not allocate physical memory\n");
7549 exit(1);
7552 #else
7553 phys_ram_base = qemu_vmalloc(phys_ram_size);
7554 if (!phys_ram_base) {
7555 fprintf(stderr, "Could not allocate physical memory\n");
7556 exit(1);
7558 #endif
7560 /* we always create the cdrom drive, even if no disk is there */
7561 bdrv_init();
7562 if (cdrom_index >= 0) {
7563 bs_table[cdrom_index] = bdrv_new("cdrom");
7564 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7567 /* open the virtual block devices */
7568 for(i = 0; i < MAX_DISKS; i++) {
7569 if (hd_filename[i]) {
7570 if (!bs_table[i]) {
7571 char buf[64];
7572 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7573 bs_table[i] = bdrv_new(buf);
7575 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7576 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7577 hd_filename[i]);
7578 exit(1);
7580 if (i == 0 && cyls != 0) {
7581 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7582 bdrv_set_translation_hint(bs_table[i], translation);
7587 /* we always create at least one floppy disk */
7588 fd_table[0] = bdrv_new("fda");
7589 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7591 for(i = 0; i < MAX_FD; i++) {
7592 if (fd_filename[i]) {
7593 if (!fd_table[i]) {
7594 char buf[64];
7595 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7596 fd_table[i] = bdrv_new(buf);
7597 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7599 if (fd_filename[i] != '\0') {
7600 if (bdrv_open(fd_table[i], fd_filename[i],
7601 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7602 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7603 fd_filename[i]);
7604 exit(1);
7610 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7611 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
7613 init_ioports();
7615 /* terminal init */
7616 if (nographic) {
7617 dumb_display_init(ds);
7618 } else if (vnc_display != NULL) {
7619 vnc_display_init(ds, vnc_display);
7620 } else {
7621 #if defined(CONFIG_SDL)
7622 sdl_display_init(ds, full_screen);
7623 #elif defined(CONFIG_COCOA)
7624 cocoa_display_init(ds, full_screen);
7625 #else
7626 dumb_display_init(ds);
7627 #endif
7630 monitor_hd = qemu_chr_open(monitor_device);
7631 if (!monitor_hd) {
7632 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7633 exit(1);
7635 monitor_init(monitor_hd, !nographic);
7637 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
7638 const char *devname = vmchannel_devices[i];
7639 if (devname[0] != '\0' && strcmp(devname, "none")) {
7640 int devid;
7641 char *termn;
7643 if (strstart(devname, "di:", &devname)) {
7644 devid = strtol(devname, &termn, 16);
7645 devname = termn + 1;
7647 else {
7648 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
7649 devname);
7650 exit(1);
7652 vmchannel_hds[i] = qemu_chr_open(devname);
7653 if (!vmchannel_hds[i]) {
7654 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
7655 devname);
7656 exit(1);
7658 vmchannel_init(vmchannel_hds[i], devid, i);
7662 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7663 const char *devname = serial_devices[i];
7664 if (devname[0] != '\0' && strcmp(devname, "none")) {
7665 serial_hds[i] = qemu_chr_open(devname);
7666 if (!serial_hds[i]) {
7667 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7668 devname);
7669 exit(1);
7671 if (!strcmp(devname, "vc"))
7672 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7676 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7677 const char *devname = parallel_devices[i];
7678 if (devname[0] != '\0' && strcmp(devname, "none")) {
7679 parallel_hds[i] = qemu_chr_open(devname);
7680 if (!parallel_hds[i]) {
7681 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7682 devname);
7683 exit(1);
7685 if (!strcmp(devname, "vc"))
7686 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7690 machine->init(ram_size, vga_ram_size, boot_device,
7691 ds, fd_filename, snapshot,
7692 kernel_filename, kernel_cmdline, initrd_filename);
7694 /* init USB devices */
7695 if (usb_enabled) {
7696 for(i = 0; i < usb_devices_index; i++) {
7697 if (usb_device_add(usb_devices[i]) < 0) {
7698 fprintf(stderr, "Warning: could not add USB device %s\n",
7699 usb_devices[i]);
7704 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7705 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7707 #ifdef USE_KVM
7708 if (kvm_allowed)
7709 kvm_init_ap();
7710 #endif
7712 #ifdef CONFIG_GDBSTUB
7713 if (use_gdbstub) {
7714 /* XXX: use standard host:port notation and modify options
7715 accordingly. */
7716 if (gdbserver_start_port(gdbstub_port) < 0) {
7717 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7718 gdbstub_port);
7719 exit(1);
7721 } else
7722 #endif
7723 if (loadvm) {
7724 do_loadvm(loadvm);
7727 if (incoming) {
7728 int rc;
7730 rc = migrate_incoming(incoming);
7731 if (rc != 0) {
7732 fprintf(stderr, "Migration failed rc=%d\n", rc);
7733 exit(rc);
7738 /* XXX: simplify init */
7739 read_passwords();
7740 if (autostart) {
7741 vm_start();
7745 if (daemonize) {
7746 uint8_t status = 0;
7747 ssize_t len;
7748 int fd;
7750 again1:
7751 len = write(fds[1], &status, 1);
7752 if (len == -1 && (errno == EINTR))
7753 goto again1;
7755 if (len != 1)
7756 exit(1);
7758 chdir("/");
7759 fd = open("/dev/null", O_RDWR);
7760 if (fd == -1)
7761 exit(1);
7763 dup2(fd, 0);
7764 dup2(fd, 1);
7765 dup2(fd, 2);
7767 close(fd);
7770 main_loop();
7771 quit_timers();
7772 return 0;