Reinitialize monitor upon reconnect, by Anthony Liguori.
[qemu/kevin.git] / vl.c
blobe5399c7308c74f02d1e942055cc5cfb7470c48a6
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2006 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 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 #ifdef __sun__
93 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
94 #else
95 #define SMBD_COMMAND "/usr/sbin/smbd"
96 #endif
98 //#define DEBUG_UNUSED_IOPORT
99 //#define DEBUG_IOPORT
101 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
103 #ifdef TARGET_PPC
104 #define DEFAULT_RAM_SIZE 144
105 #else
106 #define DEFAULT_RAM_SIZE 128
107 #endif
108 /* in ms */
109 #define GUI_REFRESH_INTERVAL 30
111 /* Max number of USB devices that can be specified on the commandline. */
112 #define MAX_USB_CMDLINE 8
114 /* XXX: use a two level table to limit memory usage */
115 #define MAX_IOPORTS 65536
117 #define DISK_OPTIONS_SIZE 256
119 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
120 char phys_ram_file[1024];
121 void *ioport_opaque[MAX_IOPORTS];
122 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
123 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
124 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
125 to store the VM snapshots */
126 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
127 /* point to the block driver where the snapshots are managed */
128 BlockDriverState *bs_snapshots;
129 BlockDriverState *bs_scsi_table[MAX_SCSI_DISKS];
130 SCSIDiskInfo scsi_disks_info[MAX_SCSI_DISKS];
131 int scsi_hba_lsi; /* Count of scsi disks/cdrom using this lsi adapter */
132 int vga_ram_size;
133 int bios_size;
134 static DisplayState display_state;
135 int nographic;
136 const char* keyboard_layout = NULL;
137 int64_t ticks_per_sec;
138 int boot_device = 'c';
139 int ram_size;
140 int pit_min_timer_count = 0;
141 int nb_nics;
142 NICInfo nd_table[MAX_NICS];
143 QEMUTimer *gui_timer;
144 int vm_running;
145 int rtc_utc = 1;
146 int cirrus_vga_enabled = 1;
147 #ifdef TARGET_SPARC
148 int graphic_width = 1024;
149 int graphic_height = 768;
150 #else
151 int graphic_width = 800;
152 int graphic_height = 600;
153 #endif
154 int graphic_depth = 15;
155 int full_screen = 0;
156 int no_quit = 0;
157 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
158 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
159 #ifdef TARGET_I386
160 int win2k_install_hack = 0;
161 #endif
162 int usb_enabled = 0;
163 static VLANState *first_vlan;
164 int smp_cpus = 1;
165 const char *vnc_display;
166 #if defined(TARGET_SPARC)
167 #define MAX_CPUS 16
168 #elif defined(TARGET_I386)
169 #define MAX_CPUS 255
170 #else
171 #define MAX_CPUS 1
172 #endif
173 int acpi_enabled = 1;
174 int fd_bootchk = 1;
175 int no_reboot = 0;
176 int daemonize = 0;
177 const char *option_rom[MAX_OPTION_ROMS];
178 int nb_option_roms;
180 /***********************************************************/
181 /* x86 ISA bus support */
183 target_phys_addr_t isa_mem_base = 0;
184 PicState2 *isa_pic;
186 uint32_t default_ioport_readb(void *opaque, uint32_t address)
188 #ifdef DEBUG_UNUSED_IOPORT
189 fprintf(stderr, "inb: port=0x%04x\n", address);
190 #endif
191 return 0xff;
194 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
196 #ifdef DEBUG_UNUSED_IOPORT
197 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
198 #endif
201 /* default is to make two byte accesses */
202 uint32_t default_ioport_readw(void *opaque, uint32_t address)
204 uint32_t data;
205 data = ioport_read_table[0][address](ioport_opaque[address], address);
206 address = (address + 1) & (MAX_IOPORTS - 1);
207 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
208 return data;
211 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
213 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
214 address = (address + 1) & (MAX_IOPORTS - 1);
215 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
218 uint32_t default_ioport_readl(void *opaque, uint32_t address)
220 #ifdef DEBUG_UNUSED_IOPORT
221 fprintf(stderr, "inl: port=0x%04x\n", address);
222 #endif
223 return 0xffffffff;
226 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
228 #ifdef DEBUG_UNUSED_IOPORT
229 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
230 #endif
233 void init_ioports(void)
235 int i;
237 for(i = 0; i < MAX_IOPORTS; i++) {
238 ioport_read_table[0][i] = default_ioport_readb;
239 ioport_write_table[0][i] = default_ioport_writeb;
240 ioport_read_table[1][i] = default_ioport_readw;
241 ioport_write_table[1][i] = default_ioport_writew;
242 ioport_read_table[2][i] = default_ioport_readl;
243 ioport_write_table[2][i] = default_ioport_writel;
247 /* size is the word size in byte */
248 int register_ioport_read(int start, int length, int size,
249 IOPortReadFunc *func, void *opaque)
251 int i, bsize;
253 if (size == 1) {
254 bsize = 0;
255 } else if (size == 2) {
256 bsize = 1;
257 } else if (size == 4) {
258 bsize = 2;
259 } else {
260 hw_error("register_ioport_read: invalid size");
261 return -1;
263 for(i = start; i < start + length; i += size) {
264 ioport_read_table[bsize][i] = func;
265 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
266 hw_error("register_ioport_read: invalid opaque");
267 ioport_opaque[i] = opaque;
269 return 0;
272 /* size is the word size in byte */
273 int register_ioport_write(int start, int length, int size,
274 IOPortWriteFunc *func, void *opaque)
276 int i, bsize;
278 if (size == 1) {
279 bsize = 0;
280 } else if (size == 2) {
281 bsize = 1;
282 } else if (size == 4) {
283 bsize = 2;
284 } else {
285 hw_error("register_ioport_write: invalid size");
286 return -1;
288 for(i = start; i < start + length; i += size) {
289 ioport_write_table[bsize][i] = func;
290 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
291 hw_error("register_ioport_write: invalid opaque");
292 ioport_opaque[i] = opaque;
294 return 0;
297 void isa_unassign_ioport(int start, int length)
299 int i;
301 for(i = start; i < start + length; i++) {
302 ioport_read_table[0][i] = default_ioport_readb;
303 ioport_read_table[1][i] = default_ioport_readw;
304 ioport_read_table[2][i] = default_ioport_readl;
306 ioport_write_table[0][i] = default_ioport_writeb;
307 ioport_write_table[1][i] = default_ioport_writew;
308 ioport_write_table[2][i] = default_ioport_writel;
312 /***********************************************************/
314 void pstrcpy(char *buf, int buf_size, const char *str)
316 int c;
317 char *q = buf;
319 if (buf_size <= 0)
320 return;
322 for(;;) {
323 c = *str++;
324 if (c == 0 || q >= buf + buf_size - 1)
325 break;
326 *q++ = c;
328 *q = '\0';
331 /* strcat and truncate. */
332 char *pstrcat(char *buf, int buf_size, const char *s)
334 int len;
335 len = strlen(buf);
336 if (len < buf_size)
337 pstrcpy(buf + len, buf_size - len, s);
338 return buf;
341 int strstart(const char *str, const char *val, const char **ptr)
343 const char *p, *q;
344 p = str;
345 q = val;
346 while (*q != '\0') {
347 if (*p != *q)
348 return 0;
349 p++;
350 q++;
352 if (ptr)
353 *ptr = p;
354 return 1;
357 void cpu_outb(CPUState *env, int addr, int val)
359 #ifdef DEBUG_IOPORT
360 if (loglevel & CPU_LOG_IOPORT)
361 fprintf(logfile, "outb: %04x %02x\n", addr, val);
362 #endif
363 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
364 #ifdef USE_KQEMU
365 if (env)
366 env->last_io_time = cpu_get_time_fast();
367 #endif
370 void cpu_outw(CPUState *env, int addr, int val)
372 #ifdef DEBUG_IOPORT
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outw: %04x %04x\n", addr, val);
375 #endif
376 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
377 #ifdef USE_KQEMU
378 if (env)
379 env->last_io_time = cpu_get_time_fast();
380 #endif
383 void cpu_outl(CPUState *env, int addr, int val)
385 #ifdef DEBUG_IOPORT
386 if (loglevel & CPU_LOG_IOPORT)
387 fprintf(logfile, "outl: %04x %08x\n", addr, val);
388 #endif
389 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390 #ifdef USE_KQEMU
391 if (env)
392 env->last_io_time = cpu_get_time_fast();
393 #endif
396 int cpu_inb(CPUState *env, int addr)
398 int val;
399 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
400 #ifdef DEBUG_IOPORT
401 if (loglevel & CPU_LOG_IOPORT)
402 fprintf(logfile, "inb : %04x %02x\n", addr, val);
403 #endif
404 #ifdef USE_KQEMU
405 if (env)
406 env->last_io_time = cpu_get_time_fast();
407 #endif
408 return val;
411 int cpu_inw(CPUState *env, int addr)
413 int val;
414 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
415 #ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "inw : %04x %04x\n", addr, val);
418 #endif
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
423 return val;
426 int cpu_inl(CPUState *env, int addr)
428 int val;
429 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
430 #ifdef DEBUG_IOPORT
431 if (loglevel & CPU_LOG_IOPORT)
432 fprintf(logfile, "inl : %04x %08x\n", addr, val);
433 #endif
434 #ifdef USE_KQEMU
435 if (env)
436 env->last_io_time = cpu_get_time_fast();
437 #endif
438 return val;
441 /***********************************************************/
442 void hw_error(const char *fmt, ...)
444 va_list ap;
445 CPUState *env;
447 va_start(ap, fmt);
448 fprintf(stderr, "qemu: hardware error: ");
449 vfprintf(stderr, fmt, ap);
450 fprintf(stderr, "\n");
451 for(env = first_cpu; env != NULL; env = env->next_cpu) {
452 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
453 #ifdef TARGET_I386
454 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
455 #else
456 cpu_dump_state(env, stderr, fprintf, 0);
457 #endif
459 va_end(ap);
460 abort();
463 /***********************************************************/
464 /* keyboard/mouse */
466 static QEMUPutKBDEvent *qemu_put_kbd_event;
467 static void *qemu_put_kbd_event_opaque;
468 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
469 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
471 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
473 qemu_put_kbd_event_opaque = opaque;
474 qemu_put_kbd_event = func;
477 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
478 void *opaque, int absolute,
479 const char *name)
481 QEMUPutMouseEntry *s, *cursor;
483 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
484 if (!s)
485 return NULL;
487 s->qemu_put_mouse_event = func;
488 s->qemu_put_mouse_event_opaque = opaque;
489 s->qemu_put_mouse_event_absolute = absolute;
490 s->qemu_put_mouse_event_name = qemu_strdup(name);
491 s->next = NULL;
493 if (!qemu_put_mouse_event_head) {
494 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
495 return s;
498 cursor = qemu_put_mouse_event_head;
499 while (cursor->next != NULL)
500 cursor = cursor->next;
502 cursor->next = s;
503 qemu_put_mouse_event_current = s;
505 return s;
508 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
510 QEMUPutMouseEntry *prev = NULL, *cursor;
512 if (!qemu_put_mouse_event_head || entry == NULL)
513 return;
515 cursor = qemu_put_mouse_event_head;
516 while (cursor != NULL && cursor != entry) {
517 prev = cursor;
518 cursor = cursor->next;
521 if (cursor == NULL) // does not exist or list empty
522 return;
523 else if (prev == NULL) { // entry is head
524 qemu_put_mouse_event_head = cursor->next;
525 if (qemu_put_mouse_event_current == entry)
526 qemu_put_mouse_event_current = cursor->next;
527 qemu_free(entry->qemu_put_mouse_event_name);
528 qemu_free(entry);
529 return;
532 prev->next = entry->next;
534 if (qemu_put_mouse_event_current == entry)
535 qemu_put_mouse_event_current = prev;
537 qemu_free(entry->qemu_put_mouse_event_name);
538 qemu_free(entry);
541 void kbd_put_keycode(int keycode)
543 if (qemu_put_kbd_event) {
544 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
548 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
550 QEMUPutMouseEvent *mouse_event;
551 void *mouse_event_opaque;
553 if (!qemu_put_mouse_event_current) {
554 return;
557 mouse_event =
558 qemu_put_mouse_event_current->qemu_put_mouse_event;
559 mouse_event_opaque =
560 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
562 if (mouse_event) {
563 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
567 int kbd_mouse_is_absolute(void)
569 if (!qemu_put_mouse_event_current)
570 return 0;
572 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
575 void do_info_mice(void)
577 QEMUPutMouseEntry *cursor;
578 int index = 0;
580 if (!qemu_put_mouse_event_head) {
581 term_printf("No mouse devices connected\n");
582 return;
585 term_printf("Mouse devices available:\n");
586 cursor = qemu_put_mouse_event_head;
587 while (cursor != NULL) {
588 term_printf("%c Mouse #%d: %s\n",
589 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
590 index, cursor->qemu_put_mouse_event_name);
591 index++;
592 cursor = cursor->next;
596 void do_mouse_set(int index)
598 QEMUPutMouseEntry *cursor;
599 int i = 0;
601 if (!qemu_put_mouse_event_head) {
602 term_printf("No mouse devices connected\n");
603 return;
606 cursor = qemu_put_mouse_event_head;
607 while (cursor != NULL && index != i) {
608 i++;
609 cursor = cursor->next;
612 if (cursor != NULL)
613 qemu_put_mouse_event_current = cursor;
614 else
615 term_printf("Mouse at given index not found\n");
618 /* compute with 96 bit intermediate result: (a*b)/c */
619 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
621 union {
622 uint64_t ll;
623 struct {
624 #ifdef WORDS_BIGENDIAN
625 uint32_t high, low;
626 #else
627 uint32_t low, high;
628 #endif
629 } l;
630 } u, res;
631 uint64_t rl, rh;
633 u.ll = a;
634 rl = (uint64_t)u.l.low * (uint64_t)b;
635 rh = (uint64_t)u.l.high * (uint64_t)b;
636 rh += (rl >> 32);
637 res.l.high = rh / c;
638 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
639 return res.ll;
642 /***********************************************************/
643 /* real time host monotonic timer */
645 #define QEMU_TIMER_BASE 1000000000LL
647 #ifdef WIN32
649 static int64_t clock_freq;
651 static void init_get_clock(void)
653 LARGE_INTEGER freq;
654 int ret;
655 ret = QueryPerformanceFrequency(&freq);
656 if (ret == 0) {
657 fprintf(stderr, "Could not calibrate ticks\n");
658 exit(1);
660 clock_freq = freq.QuadPart;
663 static int64_t get_clock(void)
665 LARGE_INTEGER ti;
666 QueryPerformanceCounter(&ti);
667 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
670 #else
672 static int use_rt_clock;
674 static void init_get_clock(void)
676 use_rt_clock = 0;
677 #if defined(__linux__)
679 struct timespec ts;
680 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
681 use_rt_clock = 1;
684 #endif
687 static int64_t get_clock(void)
689 #if defined(__linux__)
690 if (use_rt_clock) {
691 struct timespec ts;
692 clock_gettime(CLOCK_MONOTONIC, &ts);
693 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
694 } else
695 #endif
697 /* XXX: using gettimeofday leads to problems if the date
698 changes, so it should be avoided. */
699 struct timeval tv;
700 gettimeofday(&tv, NULL);
701 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
705 #endif
707 /***********************************************************/
708 /* guest cycle counter */
710 static int64_t cpu_ticks_prev;
711 static int64_t cpu_ticks_offset;
712 static int64_t cpu_clock_offset;
713 static int cpu_ticks_enabled;
715 /* return the host CPU cycle counter and handle stop/restart */
716 int64_t cpu_get_ticks(void)
718 if (!cpu_ticks_enabled) {
719 return cpu_ticks_offset;
720 } else {
721 int64_t ticks;
722 ticks = cpu_get_real_ticks();
723 if (cpu_ticks_prev > ticks) {
724 /* Note: non increasing ticks may happen if the host uses
725 software suspend */
726 cpu_ticks_offset += cpu_ticks_prev - ticks;
728 cpu_ticks_prev = ticks;
729 return ticks + cpu_ticks_offset;
733 /* return the host CPU monotonic timer and handle stop/restart */
734 static int64_t cpu_get_clock(void)
736 int64_t ti;
737 if (!cpu_ticks_enabled) {
738 return cpu_clock_offset;
739 } else {
740 ti = get_clock();
741 return ti + cpu_clock_offset;
745 /* enable cpu_get_ticks() */
746 void cpu_enable_ticks(void)
748 if (!cpu_ticks_enabled) {
749 cpu_ticks_offset -= cpu_get_real_ticks();
750 cpu_clock_offset -= get_clock();
751 cpu_ticks_enabled = 1;
755 /* disable cpu_get_ticks() : the clock is stopped. You must not call
756 cpu_get_ticks() after that. */
757 void cpu_disable_ticks(void)
759 if (cpu_ticks_enabled) {
760 cpu_ticks_offset = cpu_get_ticks();
761 cpu_clock_offset = cpu_get_clock();
762 cpu_ticks_enabled = 0;
766 /***********************************************************/
767 /* timers */
769 #define QEMU_TIMER_REALTIME 0
770 #define QEMU_TIMER_VIRTUAL 1
772 struct QEMUClock {
773 int type;
774 /* XXX: add frequency */
777 struct QEMUTimer {
778 QEMUClock *clock;
779 int64_t expire_time;
780 QEMUTimerCB *cb;
781 void *opaque;
782 struct QEMUTimer *next;
785 QEMUClock *rt_clock;
786 QEMUClock *vm_clock;
788 static QEMUTimer *active_timers[2];
789 #ifdef _WIN32
790 static MMRESULT timerID;
791 static HANDLE host_alarm = NULL;
792 static unsigned int period = 1;
793 #else
794 /* frequency of the times() clock tick */
795 static int timer_freq;
796 #endif
798 QEMUClock *qemu_new_clock(int type)
800 QEMUClock *clock;
801 clock = qemu_mallocz(sizeof(QEMUClock));
802 if (!clock)
803 return NULL;
804 clock->type = type;
805 return clock;
808 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
810 QEMUTimer *ts;
812 ts = qemu_mallocz(sizeof(QEMUTimer));
813 ts->clock = clock;
814 ts->cb = cb;
815 ts->opaque = opaque;
816 return ts;
819 void qemu_free_timer(QEMUTimer *ts)
821 qemu_free(ts);
824 /* stop a timer, but do not dealloc it */
825 void qemu_del_timer(QEMUTimer *ts)
827 QEMUTimer **pt, *t;
829 /* NOTE: this code must be signal safe because
830 qemu_timer_expired() can be called from a signal. */
831 pt = &active_timers[ts->clock->type];
832 for(;;) {
833 t = *pt;
834 if (!t)
835 break;
836 if (t == ts) {
837 *pt = t->next;
838 break;
840 pt = &t->next;
844 /* modify the current timer so that it will be fired when current_time
845 >= expire_time. The corresponding callback will be called. */
846 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
848 QEMUTimer **pt, *t;
850 qemu_del_timer(ts);
852 /* add the timer in the sorted list */
853 /* NOTE: this code must be signal safe because
854 qemu_timer_expired() can be called from a signal. */
855 pt = &active_timers[ts->clock->type];
856 for(;;) {
857 t = *pt;
858 if (!t)
859 break;
860 if (t->expire_time > expire_time)
861 break;
862 pt = &t->next;
864 ts->expire_time = expire_time;
865 ts->next = *pt;
866 *pt = ts;
869 int qemu_timer_pending(QEMUTimer *ts)
871 QEMUTimer *t;
872 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
873 if (t == ts)
874 return 1;
876 return 0;
879 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
881 if (!timer_head)
882 return 0;
883 return (timer_head->expire_time <= current_time);
886 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
888 QEMUTimer *ts;
890 for(;;) {
891 ts = *ptimer_head;
892 if (!ts || ts->expire_time > current_time)
893 break;
894 /* remove timer from the list before calling the callback */
895 *ptimer_head = ts->next;
896 ts->next = NULL;
898 /* run the callback (the timer list can be modified) */
899 ts->cb(ts->opaque);
903 int64_t qemu_get_clock(QEMUClock *clock)
905 switch(clock->type) {
906 case QEMU_TIMER_REALTIME:
907 return get_clock() / 1000000;
908 default:
909 case QEMU_TIMER_VIRTUAL:
910 return cpu_get_clock();
914 static void init_timers(void)
916 init_get_clock();
917 ticks_per_sec = QEMU_TIMER_BASE;
918 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
919 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
922 /* save a timer */
923 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
925 uint64_t expire_time;
927 if (qemu_timer_pending(ts)) {
928 expire_time = ts->expire_time;
929 } else {
930 expire_time = -1;
932 qemu_put_be64(f, expire_time);
935 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
937 uint64_t expire_time;
939 expire_time = qemu_get_be64(f);
940 if (expire_time != -1) {
941 qemu_mod_timer(ts, expire_time);
942 } else {
943 qemu_del_timer(ts);
947 static void timer_save(QEMUFile *f, void *opaque)
949 if (cpu_ticks_enabled) {
950 hw_error("cannot save state if virtual timers are running");
952 qemu_put_be64s(f, &cpu_ticks_offset);
953 qemu_put_be64s(f, &ticks_per_sec);
954 qemu_put_be64s(f, &cpu_clock_offset);
957 static int timer_load(QEMUFile *f, void *opaque, int version_id)
959 if (version_id != 1 && version_id != 2)
960 return -EINVAL;
961 if (cpu_ticks_enabled) {
962 return -EINVAL;
964 qemu_get_be64s(f, &cpu_ticks_offset);
965 qemu_get_be64s(f, &ticks_per_sec);
966 if (version_id == 2) {
967 qemu_get_be64s(f, &cpu_clock_offset);
969 return 0;
972 #ifdef _WIN32
973 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
974 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
975 #else
976 static void host_alarm_handler(int host_signum)
977 #endif
979 #if 0
980 #define DISP_FREQ 1000
982 static int64_t delta_min = INT64_MAX;
983 static int64_t delta_max, delta_cum, last_clock, delta, ti;
984 static int count;
985 ti = qemu_get_clock(vm_clock);
986 if (last_clock != 0) {
987 delta = ti - last_clock;
988 if (delta < delta_min)
989 delta_min = delta;
990 if (delta > delta_max)
991 delta_max = delta;
992 delta_cum += delta;
993 if (++count == DISP_FREQ) {
994 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
995 muldiv64(delta_min, 1000000, ticks_per_sec),
996 muldiv64(delta_max, 1000000, ticks_per_sec),
997 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
998 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
999 count = 0;
1000 delta_min = INT64_MAX;
1001 delta_max = 0;
1002 delta_cum = 0;
1005 last_clock = ti;
1007 #endif
1008 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1009 qemu_get_clock(vm_clock)) ||
1010 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1011 qemu_get_clock(rt_clock))) {
1012 #ifdef _WIN32
1013 SetEvent(host_alarm);
1014 #endif
1015 CPUState *env = cpu_single_env;
1016 if (env) {
1017 /* stop the currently executing cpu because a timer occured */
1018 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1019 #ifdef USE_KQEMU
1020 if (env->kqemu_enabled) {
1021 kqemu_cpu_interrupt(env);
1023 #endif
1028 #ifndef _WIN32
1030 #if defined(__linux__)
1032 #define RTC_FREQ 1024
1034 static int rtc_fd;
1036 static int start_rtc_timer(void)
1038 rtc_fd = open("/dev/rtc", O_RDONLY);
1039 if (rtc_fd < 0)
1040 return -1;
1041 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1042 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1043 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1044 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1045 goto fail;
1047 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1048 fail:
1049 close(rtc_fd);
1050 return -1;
1052 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1053 return 0;
1056 #else
1058 static int start_rtc_timer(void)
1060 return -1;
1063 #endif /* !defined(__linux__) */
1065 #endif /* !defined(_WIN32) */
1067 static void init_timer_alarm(void)
1069 #ifdef _WIN32
1071 int count=0;
1072 TIMECAPS tc;
1074 ZeroMemory(&tc, sizeof(TIMECAPS));
1075 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1076 if (period < tc.wPeriodMin)
1077 period = tc.wPeriodMin;
1078 timeBeginPeriod(period);
1079 timerID = timeSetEvent(1, // interval (ms)
1080 period, // resolution
1081 host_alarm_handler, // function
1082 (DWORD)&count, // user parameter
1083 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1084 if( !timerID ) {
1085 perror("failed timer alarm");
1086 exit(1);
1088 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1089 if (!host_alarm) {
1090 perror("failed CreateEvent");
1091 exit(1);
1093 qemu_add_wait_object(host_alarm, NULL, NULL);
1095 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1096 #else
1098 struct sigaction act;
1099 struct itimerval itv;
1101 /* get times() syscall frequency */
1102 timer_freq = sysconf(_SC_CLK_TCK);
1104 /* timer signal */
1105 sigfillset(&act.sa_mask);
1106 act.sa_flags = 0;
1107 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1108 act.sa_flags |= SA_ONSTACK;
1109 #endif
1110 act.sa_handler = host_alarm_handler;
1111 sigaction(SIGALRM, &act, NULL);
1113 itv.it_interval.tv_sec = 0;
1114 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1115 itv.it_value.tv_sec = 0;
1116 itv.it_value.tv_usec = 10 * 1000;
1117 setitimer(ITIMER_REAL, &itv, NULL);
1118 /* we probe the tick duration of the kernel to inform the user if
1119 the emulated kernel requested a too high timer frequency */
1120 getitimer(ITIMER_REAL, &itv);
1122 #if defined(__linux__)
1123 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1124 have timers with 1 ms resolution. The correct solution will
1125 be to use the POSIX real time timers available in recent
1126 2.6 kernels */
1127 if (itv.it_interval.tv_usec > 1000 || 1) {
1128 /* try to use /dev/rtc to have a faster timer */
1129 if (start_rtc_timer() < 0)
1130 goto use_itimer;
1131 /* disable itimer */
1132 itv.it_interval.tv_sec = 0;
1133 itv.it_interval.tv_usec = 0;
1134 itv.it_value.tv_sec = 0;
1135 itv.it_value.tv_usec = 0;
1136 setitimer(ITIMER_REAL, &itv, NULL);
1138 /* use the RTC */
1139 sigaction(SIGIO, &act, NULL);
1140 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1141 fcntl(rtc_fd, F_SETOWN, getpid());
1142 } else
1143 #endif /* defined(__linux__) */
1145 use_itimer:
1146 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1147 PIT_FREQ) / 1000000;
1150 #endif
1153 void quit_timers(void)
1155 #ifdef _WIN32
1156 timeKillEvent(timerID);
1157 timeEndPeriod(period);
1158 if (host_alarm) {
1159 CloseHandle(host_alarm);
1160 host_alarm = NULL;
1162 #endif
1165 /***********************************************************/
1166 /* character device */
1168 static void qemu_chr_reset_bh(void *opaque)
1170 CharDriverState *s = opaque;
1171 if (s->chr_event)
1172 s->chr_event(s, CHR_EVENT_RESET);
1173 qemu_bh_delete(s->bh);
1174 s->bh = NULL;
1177 void qemu_chr_reset(CharDriverState *s)
1179 if (s->bh == NULL) {
1180 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1181 qemu_bh_schedule(s->bh);
1185 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1187 return s->chr_write(s, buf, len);
1190 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1192 if (!s->chr_ioctl)
1193 return -ENOTSUP;
1194 return s->chr_ioctl(s, cmd, arg);
1197 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1199 char buf[4096];
1200 va_list ap;
1201 va_start(ap, fmt);
1202 vsnprintf(buf, sizeof(buf), fmt, ap);
1203 qemu_chr_write(s, buf, strlen(buf));
1204 va_end(ap);
1207 void qemu_chr_send_event(CharDriverState *s, int event)
1209 if (s->chr_send_event)
1210 s->chr_send_event(s, event);
1213 void qemu_chr_add_read_handler(CharDriverState *s,
1214 IOCanRWHandler *fd_can_read,
1215 IOReadHandler *fd_read, void *opaque)
1217 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1220 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1222 s->chr_event = chr_event;
1225 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1227 return len;
1230 static void null_chr_add_read_handler(CharDriverState *chr,
1231 IOCanRWHandler *fd_can_read,
1232 IOReadHandler *fd_read, void *opaque)
1236 static CharDriverState *qemu_chr_open_null(void)
1238 CharDriverState *chr;
1240 chr = qemu_mallocz(sizeof(CharDriverState));
1241 if (!chr)
1242 return NULL;
1243 chr->chr_write = null_chr_write;
1244 chr->chr_add_read_handler = null_chr_add_read_handler;
1245 return chr;
1248 #ifdef _WIN32
1250 static void socket_cleanup(void)
1252 WSACleanup();
1255 static int socket_init(void)
1257 WSADATA Data;
1258 int ret, err;
1260 ret = WSAStartup(MAKEWORD(2,2), &Data);
1261 if (ret != 0) {
1262 err = WSAGetLastError();
1263 fprintf(stderr, "WSAStartup: %d\n", err);
1264 return -1;
1266 atexit(socket_cleanup);
1267 return 0;
1270 static int send_all(int fd, const uint8_t *buf, int len1)
1272 int ret, len;
1274 len = len1;
1275 while (len > 0) {
1276 ret = send(fd, buf, len, 0);
1277 if (ret < 0) {
1278 int errno;
1279 errno = WSAGetLastError();
1280 if (errno != WSAEWOULDBLOCK) {
1281 return -1;
1283 } else if (ret == 0) {
1284 break;
1285 } else {
1286 buf += ret;
1287 len -= ret;
1290 return len1 - len;
1293 void socket_set_nonblock(int fd)
1295 unsigned long opt = 1;
1296 ioctlsocket(fd, FIONBIO, &opt);
1299 #else
1301 static int unix_write(int fd, const uint8_t *buf, int len1)
1303 int ret, len;
1305 len = len1;
1306 while (len > 0) {
1307 ret = write(fd, buf, len);
1308 if (ret < 0) {
1309 if (errno != EINTR && errno != EAGAIN)
1310 return -1;
1311 } else if (ret == 0) {
1312 break;
1313 } else {
1314 buf += ret;
1315 len -= ret;
1318 return len1 - len;
1321 static inline int send_all(int fd, const uint8_t *buf, int len1)
1323 return unix_write(fd, buf, len1);
1326 void socket_set_nonblock(int fd)
1328 fcntl(fd, F_SETFL, O_NONBLOCK);
1330 #endif /* !_WIN32 */
1332 #ifndef _WIN32
1334 typedef struct {
1335 int fd_in, fd_out;
1336 IOCanRWHandler *fd_can_read;
1337 IOReadHandler *fd_read;
1338 void *fd_opaque;
1339 int max_size;
1340 } FDCharDriver;
1342 #define STDIO_MAX_CLIENTS 2
1344 static int stdio_nb_clients;
1345 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1347 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1349 FDCharDriver *s = chr->opaque;
1350 return unix_write(s->fd_out, buf, len);
1353 static int fd_chr_read_poll(void *opaque)
1355 CharDriverState *chr = opaque;
1356 FDCharDriver *s = chr->opaque;
1358 s->max_size = s->fd_can_read(s->fd_opaque);
1359 return s->max_size;
1362 static void fd_chr_read(void *opaque)
1364 CharDriverState *chr = opaque;
1365 FDCharDriver *s = chr->opaque;
1366 int size, len;
1367 uint8_t buf[1024];
1369 len = sizeof(buf);
1370 if (len > s->max_size)
1371 len = s->max_size;
1372 if (len == 0)
1373 return;
1374 size = read(s->fd_in, buf, len);
1375 if (size == 0) {
1376 /* FD has been closed. Remove it from the active list. */
1377 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1378 return;
1380 if (size > 0) {
1381 s->fd_read(s->fd_opaque, buf, size);
1385 static void fd_chr_add_read_handler(CharDriverState *chr,
1386 IOCanRWHandler *fd_can_read,
1387 IOReadHandler *fd_read, void *opaque)
1389 FDCharDriver *s = chr->opaque;
1391 if (s->fd_in >= 0) {
1392 s->fd_can_read = fd_can_read;
1393 s->fd_read = fd_read;
1394 s->fd_opaque = opaque;
1395 if (nographic && s->fd_in == 0) {
1396 } else {
1397 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1398 fd_chr_read, NULL, chr);
1403 /* open a character device to a unix fd */
1404 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1406 CharDriverState *chr;
1407 FDCharDriver *s;
1409 chr = qemu_mallocz(sizeof(CharDriverState));
1410 if (!chr)
1411 return NULL;
1412 s = qemu_mallocz(sizeof(FDCharDriver));
1413 if (!s) {
1414 free(chr);
1415 return NULL;
1417 s->fd_in = fd_in;
1418 s->fd_out = fd_out;
1419 chr->opaque = s;
1420 chr->chr_write = fd_chr_write;
1421 chr->chr_add_read_handler = fd_chr_add_read_handler;
1423 qemu_chr_reset(chr);
1425 return chr;
1428 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1430 int fd_out;
1432 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1433 if (fd_out < 0)
1434 return NULL;
1435 return qemu_chr_open_fd(-1, fd_out);
1438 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1440 int fd_in, fd_out;
1441 char filename_in[256], filename_out[256];
1443 snprintf(filename_in, 256, "%s.in", filename);
1444 snprintf(filename_out, 256, "%s.out", filename);
1445 fd_in = open(filename_in, O_RDWR | O_BINARY);
1446 fd_out = open(filename_out, O_RDWR | O_BINARY);
1447 if (fd_in < 0 || fd_out < 0) {
1448 if (fd_in >= 0)
1449 close(fd_in);
1450 if (fd_out >= 0)
1451 close(fd_out);
1452 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1453 if (fd_in < 0)
1454 return NULL;
1456 return qemu_chr_open_fd(fd_in, fd_out);
1460 /* for STDIO, we handle the case where several clients use it
1461 (nographic mode) */
1463 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1465 #define TERM_FIFO_MAX_SIZE 1
1467 static int term_got_escape, client_index;
1468 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1469 static int term_fifo_size;
1470 static int term_timestamps;
1471 static int64_t term_timestamps_start;
1473 void term_print_help(void)
1475 printf("\n"
1476 "C-a h print this help\n"
1477 "C-a x exit emulator\n"
1478 "C-a s save disk data back to file (if -snapshot)\n"
1479 "C-a b send break (magic sysrq)\n"
1480 "C-a t toggle console timestamps\n"
1481 "C-a c switch between console and monitor\n"
1482 "C-a C-a send C-a\n"
1486 /* called when a char is received */
1487 static void stdio_received_byte(int ch)
1489 if (term_got_escape) {
1490 term_got_escape = 0;
1491 switch(ch) {
1492 case 'h':
1493 term_print_help();
1494 break;
1495 case 'x':
1496 exit(0);
1497 break;
1498 case 's':
1500 int i;
1501 for (i = 0; i < MAX_DISKS; i++) {
1502 if (bs_table[i])
1503 bdrv_commit(bs_table[i]);
1506 break;
1507 case 'b':
1508 if (client_index < stdio_nb_clients) {
1509 CharDriverState *chr;
1510 FDCharDriver *s;
1512 chr = stdio_clients[client_index];
1513 s = chr->opaque;
1514 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1516 break;
1517 case 'c':
1518 client_index++;
1519 if (client_index >= stdio_nb_clients)
1520 client_index = 0;
1521 if (client_index == 0) {
1522 /* send a new line in the monitor to get the prompt */
1523 ch = '\r';
1524 goto send_char;
1526 break;
1527 case 't':
1528 term_timestamps = !term_timestamps;
1529 term_timestamps_start = -1;
1530 break;
1531 case TERM_ESCAPE:
1532 goto send_char;
1534 } else if (ch == TERM_ESCAPE) {
1535 term_got_escape = 1;
1536 } else {
1537 send_char:
1538 if (client_index < stdio_nb_clients) {
1539 uint8_t buf[1];
1540 CharDriverState *chr;
1541 FDCharDriver *s;
1543 chr = stdio_clients[client_index];
1544 s = chr->opaque;
1545 if (s->fd_can_read(s->fd_opaque) > 0) {
1546 buf[0] = ch;
1547 s->fd_read(s->fd_opaque, buf, 1);
1548 } else if (term_fifo_size == 0) {
1549 term_fifo[term_fifo_size++] = ch;
1555 static int stdio_read_poll(void *opaque)
1557 CharDriverState *chr;
1558 FDCharDriver *s;
1560 if (client_index < stdio_nb_clients) {
1561 chr = stdio_clients[client_index];
1562 s = chr->opaque;
1563 /* try to flush the queue if needed */
1564 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1565 s->fd_read(s->fd_opaque, term_fifo, 1);
1566 term_fifo_size = 0;
1568 /* see if we can absorb more chars */
1569 if (term_fifo_size == 0)
1570 return 1;
1571 else
1572 return 0;
1573 } else {
1574 return 1;
1578 static void stdio_read(void *opaque)
1580 int size;
1581 uint8_t buf[1];
1583 size = read(0, buf, 1);
1584 if (size == 0) {
1585 /* stdin has been closed. Remove it from the active list. */
1586 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1587 return;
1589 if (size > 0)
1590 stdio_received_byte(buf[0]);
1593 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1595 FDCharDriver *s = chr->opaque;
1596 if (!term_timestamps) {
1597 return unix_write(s->fd_out, buf, len);
1598 } else {
1599 int i;
1600 char buf1[64];
1602 for(i = 0; i < len; i++) {
1603 unix_write(s->fd_out, buf + i, 1);
1604 if (buf[i] == '\n') {
1605 int64_t ti;
1606 int secs;
1608 ti = get_clock();
1609 if (term_timestamps_start == -1)
1610 term_timestamps_start = ti;
1611 ti -= term_timestamps_start;
1612 secs = ti / 1000000000;
1613 snprintf(buf1, sizeof(buf1),
1614 "[%02d:%02d:%02d.%03d] ",
1615 secs / 3600,
1616 (secs / 60) % 60,
1617 secs % 60,
1618 (int)((ti / 1000000) % 1000));
1619 unix_write(s->fd_out, buf1, strlen(buf1));
1622 return len;
1626 /* init terminal so that we can grab keys */
1627 static struct termios oldtty;
1628 static int old_fd0_flags;
1630 static void term_exit(void)
1632 tcsetattr (0, TCSANOW, &oldtty);
1633 fcntl(0, F_SETFL, old_fd0_flags);
1636 static void term_init(void)
1638 struct termios tty;
1640 tcgetattr (0, &tty);
1641 oldtty = tty;
1642 old_fd0_flags = fcntl(0, F_GETFL);
1644 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1645 |INLCR|IGNCR|ICRNL|IXON);
1646 tty.c_oflag |= OPOST;
1647 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1648 /* if graphical mode, we allow Ctrl-C handling */
1649 if (nographic)
1650 tty.c_lflag &= ~ISIG;
1651 tty.c_cflag &= ~(CSIZE|PARENB);
1652 tty.c_cflag |= CS8;
1653 tty.c_cc[VMIN] = 1;
1654 tty.c_cc[VTIME] = 0;
1656 tcsetattr (0, TCSANOW, &tty);
1658 atexit(term_exit);
1660 fcntl(0, F_SETFL, O_NONBLOCK);
1663 static CharDriverState *qemu_chr_open_stdio(void)
1665 CharDriverState *chr;
1667 if (nographic) {
1668 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1669 return NULL;
1670 chr = qemu_chr_open_fd(0, 1);
1671 chr->chr_write = stdio_write;
1672 if (stdio_nb_clients == 0)
1673 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1674 client_index = stdio_nb_clients;
1675 } else {
1676 if (stdio_nb_clients != 0)
1677 return NULL;
1678 chr = qemu_chr_open_fd(0, 1);
1680 stdio_clients[stdio_nb_clients++] = chr;
1681 if (stdio_nb_clients == 1) {
1682 /* set the terminal in raw mode */
1683 term_init();
1685 return chr;
1688 #if defined(__linux__)
1689 static CharDriverState *qemu_chr_open_pty(void)
1691 struct termios tty;
1692 char slave_name[1024];
1693 int master_fd, slave_fd;
1695 /* Not satisfying */
1696 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1697 return NULL;
1700 /* Disabling local echo and line-buffered output */
1701 tcgetattr (master_fd, &tty);
1702 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1703 tty.c_cc[VMIN] = 1;
1704 tty.c_cc[VTIME] = 0;
1705 tcsetattr (master_fd, TCSAFLUSH, &tty);
1707 fprintf(stderr, "char device redirected to %s\n", slave_name);
1708 return qemu_chr_open_fd(master_fd, master_fd);
1711 static void tty_serial_init(int fd, int speed,
1712 int parity, int data_bits, int stop_bits)
1714 struct termios tty;
1715 speed_t spd;
1717 #if 0
1718 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1719 speed, parity, data_bits, stop_bits);
1720 #endif
1721 tcgetattr (fd, &tty);
1723 switch(speed) {
1724 case 50:
1725 spd = B50;
1726 break;
1727 case 75:
1728 spd = B75;
1729 break;
1730 case 300:
1731 spd = B300;
1732 break;
1733 case 600:
1734 spd = B600;
1735 break;
1736 case 1200:
1737 spd = B1200;
1738 break;
1739 case 2400:
1740 spd = B2400;
1741 break;
1742 case 4800:
1743 spd = B4800;
1744 break;
1745 case 9600:
1746 spd = B9600;
1747 break;
1748 case 19200:
1749 spd = B19200;
1750 break;
1751 case 38400:
1752 spd = B38400;
1753 break;
1754 case 57600:
1755 spd = B57600;
1756 break;
1757 default:
1758 case 115200:
1759 spd = B115200;
1760 break;
1763 cfsetispeed(&tty, spd);
1764 cfsetospeed(&tty, spd);
1766 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1767 |INLCR|IGNCR|ICRNL|IXON);
1768 tty.c_oflag |= OPOST;
1769 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1770 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1771 switch(data_bits) {
1772 default:
1773 case 8:
1774 tty.c_cflag |= CS8;
1775 break;
1776 case 7:
1777 tty.c_cflag |= CS7;
1778 break;
1779 case 6:
1780 tty.c_cflag |= CS6;
1781 break;
1782 case 5:
1783 tty.c_cflag |= CS5;
1784 break;
1786 switch(parity) {
1787 default:
1788 case 'N':
1789 break;
1790 case 'E':
1791 tty.c_cflag |= PARENB;
1792 break;
1793 case 'O':
1794 tty.c_cflag |= PARENB | PARODD;
1795 break;
1797 if (stop_bits == 2)
1798 tty.c_cflag |= CSTOPB;
1800 tcsetattr (fd, TCSANOW, &tty);
1803 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1805 FDCharDriver *s = chr->opaque;
1807 switch(cmd) {
1808 case CHR_IOCTL_SERIAL_SET_PARAMS:
1810 QEMUSerialSetParams *ssp = arg;
1811 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1812 ssp->data_bits, ssp->stop_bits);
1814 break;
1815 case CHR_IOCTL_SERIAL_SET_BREAK:
1817 int enable = *(int *)arg;
1818 if (enable)
1819 tcsendbreak(s->fd_in, 1);
1821 break;
1822 default:
1823 return -ENOTSUP;
1825 return 0;
1828 static CharDriverState *qemu_chr_open_tty(const char *filename)
1830 CharDriverState *chr;
1831 int fd;
1833 fd = open(filename, O_RDWR | O_NONBLOCK);
1834 if (fd < 0)
1835 return NULL;
1836 fcntl(fd, F_SETFL, O_NONBLOCK);
1837 tty_serial_init(fd, 115200, 'N', 8, 1);
1838 chr = qemu_chr_open_fd(fd, fd);
1839 if (!chr)
1840 return NULL;
1841 chr->chr_ioctl = tty_serial_ioctl;
1842 qemu_chr_reset(chr);
1843 return chr;
1846 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1848 int fd = (int)chr->opaque;
1849 uint8_t b;
1851 switch(cmd) {
1852 case CHR_IOCTL_PP_READ_DATA:
1853 if (ioctl(fd, PPRDATA, &b) < 0)
1854 return -ENOTSUP;
1855 *(uint8_t *)arg = b;
1856 break;
1857 case CHR_IOCTL_PP_WRITE_DATA:
1858 b = *(uint8_t *)arg;
1859 if (ioctl(fd, PPWDATA, &b) < 0)
1860 return -ENOTSUP;
1861 break;
1862 case CHR_IOCTL_PP_READ_CONTROL:
1863 if (ioctl(fd, PPRCONTROL, &b) < 0)
1864 return -ENOTSUP;
1865 *(uint8_t *)arg = b;
1866 break;
1867 case CHR_IOCTL_PP_WRITE_CONTROL:
1868 b = *(uint8_t *)arg;
1869 if (ioctl(fd, PPWCONTROL, &b) < 0)
1870 return -ENOTSUP;
1871 break;
1872 case CHR_IOCTL_PP_READ_STATUS:
1873 if (ioctl(fd, PPRSTATUS, &b) < 0)
1874 return -ENOTSUP;
1875 *(uint8_t *)arg = b;
1876 break;
1877 default:
1878 return -ENOTSUP;
1880 return 0;
1883 static CharDriverState *qemu_chr_open_pp(const char *filename)
1885 CharDriverState *chr;
1886 int fd;
1888 fd = open(filename, O_RDWR);
1889 if (fd < 0)
1890 return NULL;
1892 if (ioctl(fd, PPCLAIM) < 0) {
1893 close(fd);
1894 return NULL;
1897 chr = qemu_mallocz(sizeof(CharDriverState));
1898 if (!chr) {
1899 close(fd);
1900 return NULL;
1902 chr->opaque = (void *)fd;
1903 chr->chr_write = null_chr_write;
1904 chr->chr_add_read_handler = null_chr_add_read_handler;
1905 chr->chr_ioctl = pp_ioctl;
1907 qemu_chr_reset(chr);
1909 return chr;
1912 #else
1913 static CharDriverState *qemu_chr_open_pty(void)
1915 return NULL;
1917 #endif
1919 #endif /* !defined(_WIN32) */
1921 #ifdef _WIN32
1922 typedef struct {
1923 IOCanRWHandler *fd_can_read;
1924 IOReadHandler *fd_read;
1925 void *win_opaque;
1926 int max_size;
1927 HANDLE hcom, hrecv, hsend;
1928 OVERLAPPED orecv, osend;
1929 BOOL fpipe;
1930 DWORD len;
1931 } WinCharState;
1933 #define NSENDBUF 2048
1934 #define NRECVBUF 2048
1935 #define MAXCONNECT 1
1936 #define NTIMEOUT 5000
1938 static int win_chr_poll(void *opaque);
1939 static int win_chr_pipe_poll(void *opaque);
1941 static void win_chr_close2(WinCharState *s)
1943 if (s->hsend) {
1944 CloseHandle(s->hsend);
1945 s->hsend = NULL;
1947 if (s->hrecv) {
1948 CloseHandle(s->hrecv);
1949 s->hrecv = NULL;
1951 if (s->hcom) {
1952 CloseHandle(s->hcom);
1953 s->hcom = NULL;
1955 if (s->fpipe)
1956 qemu_del_polling_cb(win_chr_pipe_poll, s);
1957 else
1958 qemu_del_polling_cb(win_chr_poll, s);
1961 static void win_chr_close(CharDriverState *chr)
1963 WinCharState *s = chr->opaque;
1964 win_chr_close2(s);
1967 static int win_chr_init(WinCharState *s, const char *filename)
1969 COMMCONFIG comcfg;
1970 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1971 COMSTAT comstat;
1972 DWORD size;
1973 DWORD err;
1975 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1976 if (!s->hsend) {
1977 fprintf(stderr, "Failed CreateEvent\n");
1978 goto fail;
1980 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1981 if (!s->hrecv) {
1982 fprintf(stderr, "Failed CreateEvent\n");
1983 goto fail;
1986 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1987 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1988 if (s->hcom == INVALID_HANDLE_VALUE) {
1989 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1990 s->hcom = NULL;
1991 goto fail;
1994 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1995 fprintf(stderr, "Failed SetupComm\n");
1996 goto fail;
1999 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2000 size = sizeof(COMMCONFIG);
2001 GetDefaultCommConfig(filename, &comcfg, &size);
2002 comcfg.dcb.DCBlength = sizeof(DCB);
2003 CommConfigDialog(filename, NULL, &comcfg);
2005 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2006 fprintf(stderr, "Failed SetCommState\n");
2007 goto fail;
2010 if (!SetCommMask(s->hcom, EV_ERR)) {
2011 fprintf(stderr, "Failed SetCommMask\n");
2012 goto fail;
2015 cto.ReadIntervalTimeout = MAXDWORD;
2016 if (!SetCommTimeouts(s->hcom, &cto)) {
2017 fprintf(stderr, "Failed SetCommTimeouts\n");
2018 goto fail;
2021 if (!ClearCommError(s->hcom, &err, &comstat)) {
2022 fprintf(stderr, "Failed ClearCommError\n");
2023 goto fail;
2025 qemu_add_polling_cb(win_chr_poll, s);
2026 return 0;
2028 fail:
2029 win_chr_close2(s);
2030 return -1;
2033 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2035 WinCharState *s = chr->opaque;
2036 DWORD len, ret, size, err;
2038 len = len1;
2039 ZeroMemory(&s->osend, sizeof(s->osend));
2040 s->osend.hEvent = s->hsend;
2041 while (len > 0) {
2042 if (s->hsend)
2043 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2044 else
2045 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2046 if (!ret) {
2047 err = GetLastError();
2048 if (err == ERROR_IO_PENDING) {
2049 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2050 if (ret) {
2051 buf += size;
2052 len -= size;
2053 } else {
2054 break;
2056 } else {
2057 break;
2059 } else {
2060 buf += size;
2061 len -= size;
2064 return len1 - len;
2067 static int win_chr_read_poll(WinCharState *s)
2069 s->max_size = s->fd_can_read(s->win_opaque);
2070 return s->max_size;
2073 static void win_chr_readfile(WinCharState *s)
2075 int ret, err;
2076 uint8_t buf[1024];
2077 DWORD size;
2079 ZeroMemory(&s->orecv, sizeof(s->orecv));
2080 s->orecv.hEvent = s->hrecv;
2081 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2082 if (!ret) {
2083 err = GetLastError();
2084 if (err == ERROR_IO_PENDING) {
2085 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2089 if (size > 0) {
2090 s->fd_read(s->win_opaque, buf, size);
2094 static void win_chr_read(WinCharState *s)
2096 if (s->len > s->max_size)
2097 s->len = s->max_size;
2098 if (s->len == 0)
2099 return;
2101 win_chr_readfile(s);
2104 static int win_chr_poll(void *opaque)
2106 WinCharState *s = opaque;
2107 COMSTAT status;
2108 DWORD comerr;
2110 ClearCommError(s->hcom, &comerr, &status);
2111 if (status.cbInQue > 0) {
2112 s->len = status.cbInQue;
2113 win_chr_read_poll(s);
2114 win_chr_read(s);
2115 return 1;
2117 return 0;
2120 static void win_chr_add_read_handler(CharDriverState *chr,
2121 IOCanRWHandler *fd_can_read,
2122 IOReadHandler *fd_read, void *opaque)
2124 WinCharState *s = chr->opaque;
2126 s->fd_can_read = fd_can_read;
2127 s->fd_read = fd_read;
2128 s->win_opaque = opaque;
2131 static CharDriverState *qemu_chr_open_win(const char *filename)
2133 CharDriverState *chr;
2134 WinCharState *s;
2136 chr = qemu_mallocz(sizeof(CharDriverState));
2137 if (!chr)
2138 return NULL;
2139 s = qemu_mallocz(sizeof(WinCharState));
2140 if (!s) {
2141 free(chr);
2142 return NULL;
2144 chr->opaque = s;
2145 chr->chr_write = win_chr_write;
2146 chr->chr_add_read_handler = win_chr_add_read_handler;
2147 chr->chr_close = win_chr_close;
2149 if (win_chr_init(s, filename) < 0) {
2150 free(s);
2151 free(chr);
2152 return NULL;
2154 qemu_chr_reset(chr);
2155 return chr;
2158 static int win_chr_pipe_poll(void *opaque)
2160 WinCharState *s = opaque;
2161 DWORD size;
2163 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2164 if (size > 0) {
2165 s->len = size;
2166 win_chr_read_poll(s);
2167 win_chr_read(s);
2168 return 1;
2170 return 0;
2173 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2175 OVERLAPPED ov;
2176 int ret;
2177 DWORD size;
2178 char openname[256];
2180 s->fpipe = TRUE;
2182 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2183 if (!s->hsend) {
2184 fprintf(stderr, "Failed CreateEvent\n");
2185 goto fail;
2187 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2188 if (!s->hrecv) {
2189 fprintf(stderr, "Failed CreateEvent\n");
2190 goto fail;
2193 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2194 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2195 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2196 PIPE_WAIT,
2197 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2198 if (s->hcom == INVALID_HANDLE_VALUE) {
2199 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2200 s->hcom = NULL;
2201 goto fail;
2204 ZeroMemory(&ov, sizeof(ov));
2205 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2206 ret = ConnectNamedPipe(s->hcom, &ov);
2207 if (ret) {
2208 fprintf(stderr, "Failed ConnectNamedPipe\n");
2209 goto fail;
2212 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2213 if (!ret) {
2214 fprintf(stderr, "Failed GetOverlappedResult\n");
2215 if (ov.hEvent) {
2216 CloseHandle(ov.hEvent);
2217 ov.hEvent = NULL;
2219 goto fail;
2222 if (ov.hEvent) {
2223 CloseHandle(ov.hEvent);
2224 ov.hEvent = NULL;
2226 qemu_add_polling_cb(win_chr_pipe_poll, s);
2227 return 0;
2229 fail:
2230 win_chr_close2(s);
2231 return -1;
2235 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2237 CharDriverState *chr;
2238 WinCharState *s;
2240 chr = qemu_mallocz(sizeof(CharDriverState));
2241 if (!chr)
2242 return NULL;
2243 s = qemu_mallocz(sizeof(WinCharState));
2244 if (!s) {
2245 free(chr);
2246 return NULL;
2248 chr->opaque = s;
2249 chr->chr_write = win_chr_write;
2250 chr->chr_add_read_handler = win_chr_add_read_handler;
2251 chr->chr_close = win_chr_close;
2253 if (win_chr_pipe_init(s, filename) < 0) {
2254 free(s);
2255 free(chr);
2256 return NULL;
2258 qemu_chr_reset(chr);
2259 return chr;
2262 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2264 CharDriverState *chr;
2265 WinCharState *s;
2267 chr = qemu_mallocz(sizeof(CharDriverState));
2268 if (!chr)
2269 return NULL;
2270 s = qemu_mallocz(sizeof(WinCharState));
2271 if (!s) {
2272 free(chr);
2273 return NULL;
2275 s->hcom = fd_out;
2276 chr->opaque = s;
2277 chr->chr_write = win_chr_write;
2278 chr->chr_add_read_handler = win_chr_add_read_handler;
2279 qemu_chr_reset(chr);
2280 return chr;
2283 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2285 HANDLE fd_out;
2287 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2288 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2289 if (fd_out == INVALID_HANDLE_VALUE)
2290 return NULL;
2292 return qemu_chr_open_win_file(fd_out);
2294 #endif
2296 /***********************************************************/
2297 /* UDP Net console */
2299 typedef struct {
2300 IOCanRWHandler *fd_can_read;
2301 IOReadHandler *fd_read;
2302 void *fd_opaque;
2303 int fd;
2304 struct sockaddr_in daddr;
2305 char buf[1024];
2306 int bufcnt;
2307 int bufptr;
2308 int max_size;
2309 } NetCharDriver;
2311 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2313 NetCharDriver *s = chr->opaque;
2315 return sendto(s->fd, buf, len, 0,
2316 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2319 static int udp_chr_read_poll(void *opaque)
2321 CharDriverState *chr = opaque;
2322 NetCharDriver *s = chr->opaque;
2324 s->max_size = s->fd_can_read(s->fd_opaque);
2326 /* If there were any stray characters in the queue process them
2327 * first
2329 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2330 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2331 s->bufptr++;
2332 s->max_size = s->fd_can_read(s->fd_opaque);
2334 return s->max_size;
2337 static void udp_chr_read(void *opaque)
2339 CharDriverState *chr = opaque;
2340 NetCharDriver *s = chr->opaque;
2342 if (s->max_size == 0)
2343 return;
2344 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2345 s->bufptr = s->bufcnt;
2346 if (s->bufcnt <= 0)
2347 return;
2349 s->bufptr = 0;
2350 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2351 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2352 s->bufptr++;
2353 s->max_size = s->fd_can_read(s->fd_opaque);
2357 static void udp_chr_add_read_handler(CharDriverState *chr,
2358 IOCanRWHandler *fd_can_read,
2359 IOReadHandler *fd_read, void *opaque)
2361 NetCharDriver *s = chr->opaque;
2363 if (s->fd >= 0) {
2364 s->fd_can_read = fd_can_read;
2365 s->fd_read = fd_read;
2366 s->fd_opaque = opaque;
2367 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2368 udp_chr_read, NULL, chr);
2372 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2373 #ifndef _WIN32
2374 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2375 #endif
2376 int parse_host_src_port(struct sockaddr_in *haddr,
2377 struct sockaddr_in *saddr,
2378 const char *str);
2380 static CharDriverState *qemu_chr_open_udp(const char *def)
2382 CharDriverState *chr = NULL;
2383 NetCharDriver *s = NULL;
2384 int fd = -1;
2385 struct sockaddr_in saddr;
2387 chr = qemu_mallocz(sizeof(CharDriverState));
2388 if (!chr)
2389 goto return_err;
2390 s = qemu_mallocz(sizeof(NetCharDriver));
2391 if (!s)
2392 goto return_err;
2394 fd = socket(PF_INET, SOCK_DGRAM, 0);
2395 if (fd < 0) {
2396 perror("socket(PF_INET, SOCK_DGRAM)");
2397 goto return_err;
2400 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2401 printf("Could not parse: %s\n", def);
2402 goto return_err;
2405 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2407 perror("bind");
2408 goto return_err;
2411 s->fd = fd;
2412 s->bufcnt = 0;
2413 s->bufptr = 0;
2414 chr->opaque = s;
2415 chr->chr_write = udp_chr_write;
2416 chr->chr_add_read_handler = udp_chr_add_read_handler;
2417 return chr;
2419 return_err:
2420 if (chr)
2421 free(chr);
2422 if (s)
2423 free(s);
2424 if (fd >= 0)
2425 closesocket(fd);
2426 return NULL;
2429 /***********************************************************/
2430 /* TCP Net console */
2432 typedef struct {
2433 IOCanRWHandler *fd_can_read;
2434 IOReadHandler *fd_read;
2435 void *fd_opaque;
2436 int fd, listen_fd;
2437 int connected;
2438 int max_size;
2439 int do_telnetopt;
2440 int is_unix;
2441 } TCPCharDriver;
2443 static void tcp_chr_accept(void *opaque);
2445 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2447 TCPCharDriver *s = chr->opaque;
2448 if (s->connected) {
2449 return send_all(s->fd, buf, len);
2450 } else {
2451 /* XXX: indicate an error ? */
2452 return len;
2456 static int tcp_chr_read_poll(void *opaque)
2458 CharDriverState *chr = opaque;
2459 TCPCharDriver *s = chr->opaque;
2460 if (!s->connected)
2461 return 0;
2462 if (!s->fd_can_read)
2463 return 0;
2464 s->max_size = s->fd_can_read(s->fd_opaque);
2465 return s->max_size;
2468 #define IAC 255
2469 #define IAC_BREAK 243
2470 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2471 TCPCharDriver *s,
2472 char *buf, int *size)
2474 /* Handle any telnet client's basic IAC options to satisfy char by
2475 * char mode with no echo. All IAC options will be removed from
2476 * the buf and the do_telnetopt variable will be used to track the
2477 * state of the width of the IAC information.
2479 * IAC commands come in sets of 3 bytes with the exception of the
2480 * "IAC BREAK" command and the double IAC.
2483 int i;
2484 int j = 0;
2486 for (i = 0; i < *size; i++) {
2487 if (s->do_telnetopt > 1) {
2488 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2489 /* Double IAC means send an IAC */
2490 if (j != i)
2491 buf[j] = buf[i];
2492 j++;
2493 s->do_telnetopt = 1;
2494 } else {
2495 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2496 /* Handle IAC break commands by sending a serial break */
2497 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2498 s->do_telnetopt++;
2500 s->do_telnetopt++;
2502 if (s->do_telnetopt >= 4) {
2503 s->do_telnetopt = 1;
2505 } else {
2506 if ((unsigned char)buf[i] == IAC) {
2507 s->do_telnetopt = 2;
2508 } else {
2509 if (j != i)
2510 buf[j] = buf[i];
2511 j++;
2515 *size = j;
2518 static void tcp_chr_read(void *opaque)
2520 CharDriverState *chr = opaque;
2521 TCPCharDriver *s = chr->opaque;
2522 uint8_t buf[1024];
2523 int len, size;
2525 if (!s->connected || s->max_size <= 0)
2526 return;
2527 len = sizeof(buf);
2528 if (len > s->max_size)
2529 len = s->max_size;
2530 size = recv(s->fd, buf, len, 0);
2531 if (size == 0) {
2532 /* connection closed */
2533 s->connected = 0;
2534 if (s->listen_fd >= 0) {
2535 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2537 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2538 closesocket(s->fd);
2539 s->fd = -1;
2540 } else if (size > 0) {
2541 if (s->do_telnetopt)
2542 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2543 if (size > 0)
2544 s->fd_read(s->fd_opaque, buf, size);
2548 static void tcp_chr_add_read_handler(CharDriverState *chr,
2549 IOCanRWHandler *fd_can_read,
2550 IOReadHandler *fd_read, void *opaque)
2552 TCPCharDriver *s = chr->opaque;
2554 s->fd_can_read = fd_can_read;
2555 s->fd_read = fd_read;
2556 s->fd_opaque = opaque;
2559 static void tcp_chr_connect(void *opaque)
2561 CharDriverState *chr = opaque;
2562 TCPCharDriver *s = chr->opaque;
2564 s->connected = 1;
2565 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2566 tcp_chr_read, NULL, chr);
2567 qemu_chr_reset(chr);
2570 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2571 static void tcp_chr_telnet_init(int fd)
2573 char buf[3];
2574 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2575 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2576 send(fd, (char *)buf, 3, 0);
2577 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2578 send(fd, (char *)buf, 3, 0);
2579 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2580 send(fd, (char *)buf, 3, 0);
2581 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2582 send(fd, (char *)buf, 3, 0);
2585 static void tcp_chr_accept(void *opaque)
2587 CharDriverState *chr = opaque;
2588 TCPCharDriver *s = chr->opaque;
2589 struct sockaddr_in saddr;
2590 #ifndef _WIN32
2591 struct sockaddr_un uaddr;
2592 #endif
2593 struct sockaddr *addr;
2594 socklen_t len;
2595 int fd;
2597 for(;;) {
2598 #ifndef _WIN32
2599 if (s->is_unix) {
2600 len = sizeof(uaddr);
2601 addr = (struct sockaddr *)&uaddr;
2602 } else
2603 #endif
2605 len = sizeof(saddr);
2606 addr = (struct sockaddr *)&saddr;
2608 fd = accept(s->listen_fd, addr, &len);
2609 if (fd < 0 && errno != EINTR) {
2610 return;
2611 } else if (fd >= 0) {
2612 if (s->do_telnetopt)
2613 tcp_chr_telnet_init(fd);
2614 break;
2617 socket_set_nonblock(fd);
2618 s->fd = fd;
2619 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2620 tcp_chr_connect(chr);
2623 static void tcp_chr_close(CharDriverState *chr)
2625 TCPCharDriver *s = chr->opaque;
2626 if (s->fd >= 0)
2627 closesocket(s->fd);
2628 if (s->listen_fd >= 0)
2629 closesocket(s->listen_fd);
2630 qemu_free(s);
2633 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2634 int is_telnet,
2635 int is_unix)
2637 CharDriverState *chr = NULL;
2638 TCPCharDriver *s = NULL;
2639 int fd = -1, ret, err, val;
2640 int is_listen = 0;
2641 int is_waitconnect = 1;
2642 const char *ptr;
2643 struct sockaddr_in saddr;
2644 #ifndef _WIN32
2645 struct sockaddr_un uaddr;
2646 #endif
2647 struct sockaddr *addr;
2648 socklen_t addrlen;
2650 #ifndef _WIN32
2651 if (is_unix) {
2652 addr = (struct sockaddr *)&uaddr;
2653 addrlen = sizeof(uaddr);
2654 if (parse_unix_path(&uaddr, host_str) < 0)
2655 goto fail;
2656 } else
2657 #endif
2659 addr = (struct sockaddr *)&saddr;
2660 addrlen = sizeof(saddr);
2661 if (parse_host_port(&saddr, host_str) < 0)
2662 goto fail;
2665 ptr = host_str;
2666 while((ptr = strchr(ptr,','))) {
2667 ptr++;
2668 if (!strncmp(ptr,"server",6)) {
2669 is_listen = 1;
2670 } else if (!strncmp(ptr,"nowait",6)) {
2671 is_waitconnect = 0;
2672 } else {
2673 printf("Unknown option: %s\n", ptr);
2674 goto fail;
2677 if (!is_listen)
2678 is_waitconnect = 0;
2680 chr = qemu_mallocz(sizeof(CharDriverState));
2681 if (!chr)
2682 goto fail;
2683 s = qemu_mallocz(sizeof(TCPCharDriver));
2684 if (!s)
2685 goto fail;
2687 #ifndef _WIN32
2688 if (is_unix)
2689 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2690 else
2691 #endif
2692 fd = socket(PF_INET, SOCK_STREAM, 0);
2694 if (fd < 0)
2695 goto fail;
2697 if (!is_waitconnect)
2698 socket_set_nonblock(fd);
2700 s->connected = 0;
2701 s->fd = -1;
2702 s->listen_fd = -1;
2703 s->is_unix = is_unix;
2705 chr->opaque = s;
2706 chr->chr_write = tcp_chr_write;
2707 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2708 chr->chr_close = tcp_chr_close;
2710 if (is_listen) {
2711 /* allow fast reuse */
2712 #ifndef _WIN32
2713 if (is_unix) {
2714 char path[109];
2715 strncpy(path, uaddr.sun_path, 108);
2716 path[108] = 0;
2717 unlink(path);
2718 } else
2719 #endif
2721 val = 1;
2722 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2725 ret = bind(fd, addr, addrlen);
2726 if (ret < 0)
2727 goto fail;
2729 ret = listen(fd, 0);
2730 if (ret < 0)
2731 goto fail;
2733 s->listen_fd = fd;
2734 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2735 if (is_telnet)
2736 s->do_telnetopt = 1;
2737 } else {
2738 for(;;) {
2739 ret = connect(fd, addr, addrlen);
2740 if (ret < 0) {
2741 err = socket_error();
2742 if (err == EINTR || err == EWOULDBLOCK) {
2743 } else if (err == EINPROGRESS) {
2744 break;
2745 } else {
2746 goto fail;
2748 } else {
2749 s->connected = 1;
2750 break;
2753 s->fd = fd;
2754 if (s->connected)
2755 tcp_chr_connect(chr);
2756 else
2757 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2760 if (is_listen && is_waitconnect) {
2761 printf("QEMU waiting for connection on: %s\n", host_str);
2762 tcp_chr_accept(chr);
2763 socket_set_nonblock(s->listen_fd);
2766 return chr;
2767 fail:
2768 if (fd >= 0)
2769 closesocket(fd);
2770 qemu_free(s);
2771 qemu_free(chr);
2772 return NULL;
2775 CharDriverState *qemu_chr_open(const char *filename)
2777 const char *p;
2779 if (!strcmp(filename, "vc")) {
2780 return text_console_init(&display_state);
2781 } else if (!strcmp(filename, "null")) {
2782 return qemu_chr_open_null();
2783 } else
2784 if (strstart(filename, "tcp:", &p)) {
2785 return qemu_chr_open_tcp(p, 0, 0);
2786 } else
2787 if (strstart(filename, "telnet:", &p)) {
2788 return qemu_chr_open_tcp(p, 1, 0);
2789 } else
2790 if (strstart(filename, "udp:", &p)) {
2791 return qemu_chr_open_udp(p);
2792 } else
2793 #ifndef _WIN32
2794 if (strstart(filename, "unix:", &p)) {
2795 return qemu_chr_open_tcp(p, 0, 1);
2796 } else if (strstart(filename, "file:", &p)) {
2797 return qemu_chr_open_file_out(p);
2798 } else if (strstart(filename, "pipe:", &p)) {
2799 return qemu_chr_open_pipe(p);
2800 } else if (!strcmp(filename, "pty")) {
2801 return qemu_chr_open_pty();
2802 } else if (!strcmp(filename, "stdio")) {
2803 return qemu_chr_open_stdio();
2804 } else
2805 #endif
2806 #if defined(__linux__)
2807 if (strstart(filename, "/dev/parport", NULL)) {
2808 return qemu_chr_open_pp(filename);
2809 } else
2810 if (strstart(filename, "/dev/", NULL)) {
2811 return qemu_chr_open_tty(filename);
2812 } else
2813 #endif
2814 #ifdef _WIN32
2815 if (strstart(filename, "COM", NULL)) {
2816 return qemu_chr_open_win(filename);
2817 } else
2818 if (strstart(filename, "pipe:", &p)) {
2819 return qemu_chr_open_win_pipe(p);
2820 } else
2821 if (strstart(filename, "file:", &p)) {
2822 return qemu_chr_open_win_file_out(p);
2824 #endif
2826 return NULL;
2830 void qemu_chr_close(CharDriverState *chr)
2832 if (chr->chr_close)
2833 chr->chr_close(chr);
2836 /***********************************************************/
2837 /* network device redirectors */
2839 void hex_dump(FILE *f, const uint8_t *buf, int size)
2841 int len, i, j, c;
2843 for(i=0;i<size;i+=16) {
2844 len = size - i;
2845 if (len > 16)
2846 len = 16;
2847 fprintf(f, "%08x ", i);
2848 for(j=0;j<16;j++) {
2849 if (j < len)
2850 fprintf(f, " %02x", buf[i+j]);
2851 else
2852 fprintf(f, " ");
2854 fprintf(f, " ");
2855 for(j=0;j<len;j++) {
2856 c = buf[i+j];
2857 if (c < ' ' || c > '~')
2858 c = '.';
2859 fprintf(f, "%c", c);
2861 fprintf(f, "\n");
2865 static int parse_macaddr(uint8_t *macaddr, const char *p)
2867 int i;
2868 for(i = 0; i < 6; i++) {
2869 macaddr[i] = strtol(p, (char **)&p, 16);
2870 if (i == 5) {
2871 if (*p != '\0')
2872 return -1;
2873 } else {
2874 if (*p != ':')
2875 return -1;
2876 p++;
2879 return 0;
2882 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2884 const char *p, *p1;
2885 int len;
2886 p = *pp;
2887 p1 = strchr(p, sep);
2888 if (!p1)
2889 return -1;
2890 len = p1 - p;
2891 p1++;
2892 if (buf_size > 0) {
2893 if (len > buf_size - 1)
2894 len = buf_size - 1;
2895 memcpy(buf, p, len);
2896 buf[len] = '\0';
2898 *pp = p1;
2899 return 0;
2902 int parse_host_src_port(struct sockaddr_in *haddr,
2903 struct sockaddr_in *saddr,
2904 const char *input_str)
2906 char *str = strdup(input_str);
2907 char *host_str = str;
2908 char *src_str;
2909 char *ptr;
2912 * Chop off any extra arguments at the end of the string which
2913 * would start with a comma, then fill in the src port information
2914 * if it was provided else use the "any address" and "any port".
2916 if ((ptr = strchr(str,',')))
2917 *ptr = '\0';
2919 if ((src_str = strchr(input_str,'@'))) {
2920 *src_str = '\0';
2921 src_str++;
2924 if (parse_host_port(haddr, host_str) < 0)
2925 goto fail;
2927 if (!src_str || *src_str == '\0')
2928 src_str = ":0";
2930 if (parse_host_port(saddr, src_str) < 0)
2931 goto fail;
2933 free(str);
2934 return(0);
2936 fail:
2937 free(str);
2938 return -1;
2941 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2943 char buf[512];
2944 struct hostent *he;
2945 const char *p, *r;
2946 int port;
2948 p = str;
2949 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2950 return -1;
2951 saddr->sin_family = AF_INET;
2952 if (buf[0] == '\0') {
2953 saddr->sin_addr.s_addr = 0;
2954 } else {
2955 if (isdigit(buf[0])) {
2956 if (!inet_aton(buf, &saddr->sin_addr))
2957 return -1;
2958 } else {
2959 if ((he = gethostbyname(buf)) == NULL)
2960 return - 1;
2961 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2964 port = strtol(p, (char **)&r, 0);
2965 if (r == p)
2966 return -1;
2967 saddr->sin_port = htons(port);
2968 return 0;
2971 #ifndef _WIN32
2972 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2974 const char *p;
2975 int len;
2977 len = MIN(108, strlen(str));
2978 p = strchr(str, ',');
2979 if (p)
2980 len = MIN(len, p - str);
2982 memset(uaddr, 0, sizeof(*uaddr));
2984 uaddr->sun_family = AF_UNIX;
2985 memcpy(uaddr->sun_path, str, len);
2987 return 0;
2989 #endif
2991 /* find or alloc a new VLAN */
2992 VLANState *qemu_find_vlan(int id)
2994 VLANState **pvlan, *vlan;
2995 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2996 if (vlan->id == id)
2997 return vlan;
2999 vlan = qemu_mallocz(sizeof(VLANState));
3000 if (!vlan)
3001 return NULL;
3002 vlan->id = id;
3003 vlan->next = NULL;
3004 pvlan = &first_vlan;
3005 while (*pvlan != NULL)
3006 pvlan = &(*pvlan)->next;
3007 *pvlan = vlan;
3008 return vlan;
3011 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3012 IOReadHandler *fd_read,
3013 IOCanRWHandler *fd_can_read,
3014 void *opaque)
3016 VLANClientState *vc, **pvc;
3017 vc = qemu_mallocz(sizeof(VLANClientState));
3018 if (!vc)
3019 return NULL;
3020 vc->fd_read = fd_read;
3021 vc->fd_can_read = fd_can_read;
3022 vc->opaque = opaque;
3023 vc->vlan = vlan;
3025 vc->next = NULL;
3026 pvc = &vlan->first_client;
3027 while (*pvc != NULL)
3028 pvc = &(*pvc)->next;
3029 *pvc = vc;
3030 return vc;
3033 int qemu_can_send_packet(VLANClientState *vc1)
3035 VLANState *vlan = vc1->vlan;
3036 VLANClientState *vc;
3038 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3039 if (vc != vc1) {
3040 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3041 return 0;
3044 return 1;
3047 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3049 VLANState *vlan = vc1->vlan;
3050 VLANClientState *vc;
3052 #if 0
3053 printf("vlan %d send:\n", vlan->id);
3054 hex_dump(stdout, buf, size);
3055 #endif
3056 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3057 if (vc != vc1) {
3058 vc->fd_read(vc->opaque, buf, size);
3063 #if defined(CONFIG_SLIRP)
3065 /* slirp network adapter */
3067 static int slirp_inited;
3068 static VLANClientState *slirp_vc;
3070 int slirp_can_output(void)
3072 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3075 void slirp_output(const uint8_t *pkt, int pkt_len)
3077 #if 0
3078 printf("slirp output:\n");
3079 hex_dump(stdout, pkt, pkt_len);
3080 #endif
3081 if (!slirp_vc)
3082 return;
3083 qemu_send_packet(slirp_vc, pkt, pkt_len);
3086 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3088 #if 0
3089 printf("slirp input:\n");
3090 hex_dump(stdout, buf, size);
3091 #endif
3092 slirp_input(buf, size);
3095 static int net_slirp_init(VLANState *vlan)
3097 if (!slirp_inited) {
3098 slirp_inited = 1;
3099 slirp_init();
3101 slirp_vc = qemu_new_vlan_client(vlan,
3102 slirp_receive, NULL, NULL);
3103 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3104 return 0;
3107 static void net_slirp_redir(const char *redir_str)
3109 int is_udp;
3110 char buf[256], *r;
3111 const char *p;
3112 struct in_addr guest_addr;
3113 int host_port, guest_port;
3115 if (!slirp_inited) {
3116 slirp_inited = 1;
3117 slirp_init();
3120 p = redir_str;
3121 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3122 goto fail;
3123 if (!strcmp(buf, "tcp")) {
3124 is_udp = 0;
3125 } else if (!strcmp(buf, "udp")) {
3126 is_udp = 1;
3127 } else {
3128 goto fail;
3131 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3132 goto fail;
3133 host_port = strtol(buf, &r, 0);
3134 if (r == buf)
3135 goto fail;
3137 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3138 goto fail;
3139 if (buf[0] == '\0') {
3140 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3142 if (!inet_aton(buf, &guest_addr))
3143 goto fail;
3145 guest_port = strtol(p, &r, 0);
3146 if (r == p)
3147 goto fail;
3149 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3150 fprintf(stderr, "qemu: could not set up redirection\n");
3151 exit(1);
3153 return;
3154 fail:
3155 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3156 exit(1);
3159 #ifndef _WIN32
3161 char smb_dir[1024];
3163 static void smb_exit(void)
3165 DIR *d;
3166 struct dirent *de;
3167 char filename[1024];
3169 /* erase all the files in the directory */
3170 d = opendir(smb_dir);
3171 for(;;) {
3172 de = readdir(d);
3173 if (!de)
3174 break;
3175 if (strcmp(de->d_name, ".") != 0 &&
3176 strcmp(de->d_name, "..") != 0) {
3177 snprintf(filename, sizeof(filename), "%s/%s",
3178 smb_dir, de->d_name);
3179 unlink(filename);
3182 closedir(d);
3183 rmdir(smb_dir);
3186 /* automatic user mode samba server configuration */
3187 void net_slirp_smb(const char *exported_dir)
3189 char smb_conf[1024];
3190 char smb_cmdline[1024];
3191 FILE *f;
3193 if (!slirp_inited) {
3194 slirp_inited = 1;
3195 slirp_init();
3198 /* XXX: better tmp dir construction */
3199 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3200 if (mkdir(smb_dir, 0700) < 0) {
3201 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3202 exit(1);
3204 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3206 f = fopen(smb_conf, "w");
3207 if (!f) {
3208 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3209 exit(1);
3211 fprintf(f,
3212 "[global]\n"
3213 "private dir=%s\n"
3214 "smb ports=0\n"
3215 "socket address=127.0.0.1\n"
3216 "pid directory=%s\n"
3217 "lock directory=%s\n"
3218 "log file=%s/log.smbd\n"
3219 "smb passwd file=%s/smbpasswd\n"
3220 "security = share\n"
3221 "[qemu]\n"
3222 "path=%s\n"
3223 "read only=no\n"
3224 "guest ok=yes\n",
3225 smb_dir,
3226 smb_dir,
3227 smb_dir,
3228 smb_dir,
3229 smb_dir,
3230 exported_dir
3232 fclose(f);
3233 atexit(smb_exit);
3235 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3236 SMBD_COMMAND, smb_conf);
3238 slirp_add_exec(0, smb_cmdline, 4, 139);
3241 #endif /* !defined(_WIN32) */
3243 #endif /* CONFIG_SLIRP */
3245 #if !defined(_WIN32)
3247 typedef struct TAPState {
3248 VLANClientState *vc;
3249 int fd;
3250 } TAPState;
3252 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3254 TAPState *s = opaque;
3255 int ret;
3256 for(;;) {
3257 ret = write(s->fd, buf, size);
3258 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3259 } else {
3260 break;
3265 static void tap_send(void *opaque)
3267 TAPState *s = opaque;
3268 uint8_t buf[4096];
3269 int size;
3271 size = read(s->fd, buf, sizeof(buf));
3272 if (size > 0) {
3273 qemu_send_packet(s->vc, buf, size);
3277 /* fd support */
3279 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3281 TAPState *s;
3283 s = qemu_mallocz(sizeof(TAPState));
3284 if (!s)
3285 return NULL;
3286 s->fd = fd;
3287 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3288 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3289 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3290 return s;
3293 #ifdef _BSD
3294 static int tap_open(char *ifname, int ifname_size)
3296 int fd;
3297 char *dev;
3298 struct stat s;
3300 fd = open("/dev/tap", O_RDWR);
3301 if (fd < 0) {
3302 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3303 return -1;
3306 fstat(fd, &s);
3307 dev = devname(s.st_rdev, S_IFCHR);
3308 pstrcpy(ifname, ifname_size, dev);
3310 fcntl(fd, F_SETFL, O_NONBLOCK);
3311 return fd;
3313 #elif defined(__sun__)
3314 static int tap_open(char *ifname, int ifname_size)
3316 fprintf(stderr, "warning: tap_open not yet implemented\n");
3317 return -1;
3319 #else
3320 static int tap_open(char *ifname, int ifname_size)
3322 struct ifreq ifr;
3323 int fd, ret;
3325 fd = open("/dev/net/tun", O_RDWR);
3326 if (fd < 0) {
3327 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3328 return -1;
3330 memset(&ifr, 0, sizeof(ifr));
3331 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3332 if (ifname[0] != '\0')
3333 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3334 else
3335 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3336 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3337 if (ret != 0) {
3338 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3339 close(fd);
3340 return -1;
3342 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3343 fcntl(fd, F_SETFL, O_NONBLOCK);
3344 return fd;
3346 #endif
3348 static int net_tap_init(VLANState *vlan, const char *ifname1,
3349 const char *setup_script)
3351 TAPState *s;
3352 int pid, status, fd;
3353 char *args[3];
3354 char **parg;
3355 char ifname[128];
3357 if (ifname1 != NULL)
3358 pstrcpy(ifname, sizeof(ifname), ifname1);
3359 else
3360 ifname[0] = '\0';
3361 fd = tap_open(ifname, sizeof(ifname));
3362 if (fd < 0)
3363 return -1;
3365 if (!setup_script)
3366 setup_script = "";
3367 if (setup_script[0] != '\0') {
3368 /* try to launch network init script */
3369 pid = fork();
3370 if (pid >= 0) {
3371 if (pid == 0) {
3372 parg = args;
3373 *parg++ = (char *)setup_script;
3374 *parg++ = ifname;
3375 *parg++ = NULL;
3376 execv(setup_script, args);
3377 _exit(1);
3379 while (waitpid(pid, &status, 0) != pid);
3380 if (!WIFEXITED(status) ||
3381 WEXITSTATUS(status) != 0) {
3382 fprintf(stderr, "%s: could not launch network script\n",
3383 setup_script);
3384 return -1;
3388 s = net_tap_fd_init(vlan, fd);
3389 if (!s)
3390 return -1;
3391 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3392 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3393 return 0;
3396 #endif /* !_WIN32 */
3398 /* network connection */
3399 typedef struct NetSocketState {
3400 VLANClientState *vc;
3401 int fd;
3402 int state; /* 0 = getting length, 1 = getting data */
3403 int index;
3404 int packet_len;
3405 uint8_t buf[4096];
3406 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3407 } NetSocketState;
3409 typedef struct NetSocketListenState {
3410 VLANState *vlan;
3411 int fd;
3412 } NetSocketListenState;
3414 /* XXX: we consider we can send the whole packet without blocking */
3415 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3417 NetSocketState *s = opaque;
3418 uint32_t len;
3419 len = htonl(size);
3421 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3422 send_all(s->fd, buf, size);
3425 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3427 NetSocketState *s = opaque;
3428 sendto(s->fd, buf, size, 0,
3429 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3432 static void net_socket_send(void *opaque)
3434 NetSocketState *s = opaque;
3435 int l, size, err;
3436 uint8_t buf1[4096];
3437 const uint8_t *buf;
3439 size = recv(s->fd, buf1, sizeof(buf1), 0);
3440 if (size < 0) {
3441 err = socket_error();
3442 if (err != EWOULDBLOCK)
3443 goto eoc;
3444 } else if (size == 0) {
3445 /* end of connection */
3446 eoc:
3447 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3448 closesocket(s->fd);
3449 return;
3451 buf = buf1;
3452 while (size > 0) {
3453 /* reassemble a packet from the network */
3454 switch(s->state) {
3455 case 0:
3456 l = 4 - s->index;
3457 if (l > size)
3458 l = size;
3459 memcpy(s->buf + s->index, buf, l);
3460 buf += l;
3461 size -= l;
3462 s->index += l;
3463 if (s->index == 4) {
3464 /* got length */
3465 s->packet_len = ntohl(*(uint32_t *)s->buf);
3466 s->index = 0;
3467 s->state = 1;
3469 break;
3470 case 1:
3471 l = s->packet_len - s->index;
3472 if (l > size)
3473 l = size;
3474 memcpy(s->buf + s->index, buf, l);
3475 s->index += l;
3476 buf += l;
3477 size -= l;
3478 if (s->index >= s->packet_len) {
3479 qemu_send_packet(s->vc, s->buf, s->packet_len);
3480 s->index = 0;
3481 s->state = 0;
3483 break;
3488 static void net_socket_send_dgram(void *opaque)
3490 NetSocketState *s = opaque;
3491 int size;
3493 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3494 if (size < 0)
3495 return;
3496 if (size == 0) {
3497 /* end of connection */
3498 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3499 return;
3501 qemu_send_packet(s->vc, s->buf, size);
3504 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3506 struct ip_mreq imr;
3507 int fd;
3508 int val, ret;
3509 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3510 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3511 inet_ntoa(mcastaddr->sin_addr),
3512 (int)ntohl(mcastaddr->sin_addr.s_addr));
3513 return -1;
3516 fd = socket(PF_INET, SOCK_DGRAM, 0);
3517 if (fd < 0) {
3518 perror("socket(PF_INET, SOCK_DGRAM)");
3519 return -1;
3522 val = 1;
3523 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3524 (const char *)&val, sizeof(val));
3525 if (ret < 0) {
3526 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3527 goto fail;
3530 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3531 if (ret < 0) {
3532 perror("bind");
3533 goto fail;
3536 /* Add host to multicast group */
3537 imr.imr_multiaddr = mcastaddr->sin_addr;
3538 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3540 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3541 (const char *)&imr, sizeof(struct ip_mreq));
3542 if (ret < 0) {
3543 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3544 goto fail;
3547 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3548 val = 1;
3549 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3550 (const char *)&val, sizeof(val));
3551 if (ret < 0) {
3552 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3553 goto fail;
3556 socket_set_nonblock(fd);
3557 return fd;
3558 fail:
3559 if (fd >= 0)
3560 closesocket(fd);
3561 return -1;
3564 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3565 int is_connected)
3567 struct sockaddr_in saddr;
3568 int newfd;
3569 socklen_t saddr_len;
3570 NetSocketState *s;
3572 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3573 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3574 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3577 if (is_connected) {
3578 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3579 /* must be bound */
3580 if (saddr.sin_addr.s_addr==0) {
3581 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3582 fd);
3583 return NULL;
3585 /* clone dgram socket */
3586 newfd = net_socket_mcast_create(&saddr);
3587 if (newfd < 0) {
3588 /* error already reported by net_socket_mcast_create() */
3589 close(fd);
3590 return NULL;
3592 /* clone newfd to fd, close newfd */
3593 dup2(newfd, fd);
3594 close(newfd);
3596 } else {
3597 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3598 fd, strerror(errno));
3599 return NULL;
3603 s = qemu_mallocz(sizeof(NetSocketState));
3604 if (!s)
3605 return NULL;
3606 s->fd = fd;
3608 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3609 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3611 /* mcast: save bound address as dst */
3612 if (is_connected) s->dgram_dst=saddr;
3614 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3615 "socket: fd=%d (%s mcast=%s:%d)",
3616 fd, is_connected? "cloned" : "",
3617 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3618 return s;
3621 static void net_socket_connect(void *opaque)
3623 NetSocketState *s = opaque;
3624 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3627 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3628 int is_connected)
3630 NetSocketState *s;
3631 s = qemu_mallocz(sizeof(NetSocketState));
3632 if (!s)
3633 return NULL;
3634 s->fd = fd;
3635 s->vc = qemu_new_vlan_client(vlan,
3636 net_socket_receive, NULL, s);
3637 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3638 "socket: fd=%d", fd);
3639 if (is_connected) {
3640 net_socket_connect(s);
3641 } else {
3642 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3644 return s;
3647 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3648 int is_connected)
3650 int so_type=-1, optlen=sizeof(so_type);
3652 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3653 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3654 return NULL;
3656 switch(so_type) {
3657 case SOCK_DGRAM:
3658 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3659 case SOCK_STREAM:
3660 return net_socket_fd_init_stream(vlan, fd, is_connected);
3661 default:
3662 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3663 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3664 return net_socket_fd_init_stream(vlan, fd, is_connected);
3666 return NULL;
3669 static void net_socket_accept(void *opaque)
3671 NetSocketListenState *s = opaque;
3672 NetSocketState *s1;
3673 struct sockaddr_in saddr;
3674 socklen_t len;
3675 int fd;
3677 for(;;) {
3678 len = sizeof(saddr);
3679 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3680 if (fd < 0 && errno != EINTR) {
3681 return;
3682 } else if (fd >= 0) {
3683 break;
3686 s1 = net_socket_fd_init(s->vlan, fd, 1);
3687 if (!s1) {
3688 closesocket(fd);
3689 } else {
3690 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3691 "socket: connection from %s:%d",
3692 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3696 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3698 NetSocketListenState *s;
3699 int fd, val, ret;
3700 struct sockaddr_in saddr;
3702 if (parse_host_port(&saddr, host_str) < 0)
3703 return -1;
3705 s = qemu_mallocz(sizeof(NetSocketListenState));
3706 if (!s)
3707 return -1;
3709 fd = socket(PF_INET, SOCK_STREAM, 0);
3710 if (fd < 0) {
3711 perror("socket");
3712 return -1;
3714 socket_set_nonblock(fd);
3716 /* allow fast reuse */
3717 val = 1;
3718 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3720 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3721 if (ret < 0) {
3722 perror("bind");
3723 return -1;
3725 ret = listen(fd, 0);
3726 if (ret < 0) {
3727 perror("listen");
3728 return -1;
3730 s->vlan = vlan;
3731 s->fd = fd;
3732 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3733 return 0;
3736 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3738 NetSocketState *s;
3739 int fd, connected, ret, err;
3740 struct sockaddr_in saddr;
3742 if (parse_host_port(&saddr, host_str) < 0)
3743 return -1;
3745 fd = socket(PF_INET, SOCK_STREAM, 0);
3746 if (fd < 0) {
3747 perror("socket");
3748 return -1;
3750 socket_set_nonblock(fd);
3752 connected = 0;
3753 for(;;) {
3754 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3755 if (ret < 0) {
3756 err = socket_error();
3757 if (err == EINTR || err == EWOULDBLOCK) {
3758 } else if (err == EINPROGRESS) {
3759 break;
3760 } else {
3761 perror("connect");
3762 closesocket(fd);
3763 return -1;
3765 } else {
3766 connected = 1;
3767 break;
3770 s = net_socket_fd_init(vlan, fd, connected);
3771 if (!s)
3772 return -1;
3773 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3774 "socket: connect to %s:%d",
3775 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3776 return 0;
3779 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3781 NetSocketState *s;
3782 int fd;
3783 struct sockaddr_in saddr;
3785 if (parse_host_port(&saddr, host_str) < 0)
3786 return -1;
3789 fd = net_socket_mcast_create(&saddr);
3790 if (fd < 0)
3791 return -1;
3793 s = net_socket_fd_init(vlan, fd, 0);
3794 if (!s)
3795 return -1;
3797 s->dgram_dst = saddr;
3799 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3800 "socket: mcast=%s:%d",
3801 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3802 return 0;
3806 static int get_param_value(char *buf, int buf_size,
3807 const char *tag, const char *str)
3809 const char *p;
3810 char *q;
3811 char option[128];
3813 p = str;
3814 for(;;) {
3815 q = option;
3816 while (*p != '\0' && *p != '=') {
3817 if ((q - option) < sizeof(option) - 1)
3818 *q++ = *p;
3819 p++;
3821 *q = '\0';
3822 if (*p != '=')
3823 break;
3824 p++;
3825 if (!strcmp(tag, option)) {
3826 q = buf;
3827 while (*p != '\0' && *p != ',') {
3828 if ((q - buf) < buf_size - 1)
3829 *q++ = *p;
3830 p++;
3832 *q = '\0';
3833 return q - buf;
3834 } else {
3835 while (*p != '\0' && *p != ',') {
3836 p++;
3839 if (*p != ',')
3840 break;
3841 p++;
3843 return 0;
3846 static int net_client_init(const char *str)
3848 const char *p;
3849 char *q;
3850 char device[64];
3851 char buf[1024];
3852 int vlan_id, ret;
3853 VLANState *vlan;
3855 p = str;
3856 q = device;
3857 while (*p != '\0' && *p != ',') {
3858 if ((q - device) < sizeof(device) - 1)
3859 *q++ = *p;
3860 p++;
3862 *q = '\0';
3863 if (*p == ',')
3864 p++;
3865 vlan_id = 0;
3866 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3867 vlan_id = strtol(buf, NULL, 0);
3869 vlan = qemu_find_vlan(vlan_id);
3870 if (!vlan) {
3871 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3872 return -1;
3874 if (!strcmp(device, "nic")) {
3875 NICInfo *nd;
3876 uint8_t *macaddr;
3878 if (nb_nics >= MAX_NICS) {
3879 fprintf(stderr, "Too Many NICs\n");
3880 return -1;
3882 nd = &nd_table[nb_nics];
3883 macaddr = nd->macaddr;
3884 macaddr[0] = 0x52;
3885 macaddr[1] = 0x54;
3886 macaddr[2] = 0x00;
3887 macaddr[3] = 0x12;
3888 macaddr[4] = 0x34;
3889 macaddr[5] = 0x56 + nb_nics;
3891 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3892 if (parse_macaddr(macaddr, buf) < 0) {
3893 fprintf(stderr, "invalid syntax for ethernet address\n");
3894 return -1;
3897 if (get_param_value(buf, sizeof(buf), "model", p)) {
3898 nd->model = strdup(buf);
3900 nd->vlan = vlan;
3901 nb_nics++;
3902 ret = 0;
3903 } else
3904 if (!strcmp(device, "none")) {
3905 /* does nothing. It is needed to signal that no network cards
3906 are wanted */
3907 ret = 0;
3908 } else
3909 #ifdef CONFIG_SLIRP
3910 if (!strcmp(device, "user")) {
3911 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3912 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3914 ret = net_slirp_init(vlan);
3915 } else
3916 #endif
3917 #ifdef _WIN32
3918 if (!strcmp(device, "tap")) {
3919 char ifname[64];
3920 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3921 fprintf(stderr, "tap: no interface name\n");
3922 return -1;
3924 ret = tap_win32_init(vlan, ifname);
3925 } else
3926 #else
3927 if (!strcmp(device, "tap")) {
3928 char ifname[64];
3929 char setup_script[1024];
3930 int fd;
3931 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3932 fd = strtol(buf, NULL, 0);
3933 ret = -1;
3934 if (net_tap_fd_init(vlan, fd))
3935 ret = 0;
3936 } else {
3937 get_param_value(ifname, sizeof(ifname), "ifname", p);
3938 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3939 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3941 ret = net_tap_init(vlan, ifname, setup_script);
3943 } else
3944 #endif
3945 if (!strcmp(device, "socket")) {
3946 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3947 int fd;
3948 fd = strtol(buf, NULL, 0);
3949 ret = -1;
3950 if (net_socket_fd_init(vlan, fd, 1))
3951 ret = 0;
3952 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3953 ret = net_socket_listen_init(vlan, buf);
3954 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3955 ret = net_socket_connect_init(vlan, buf);
3956 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3957 ret = net_socket_mcast_init(vlan, buf);
3958 } else {
3959 fprintf(stderr, "Unknown socket options: %s\n", p);
3960 return -1;
3962 } else
3964 fprintf(stderr, "Unknown network device: %s\n", device);
3965 return -1;
3967 if (ret < 0) {
3968 fprintf(stderr, "Could not initialize device '%s'\n", device);
3971 return ret;
3974 void do_info_network(void)
3976 VLANState *vlan;
3977 VLANClientState *vc;
3979 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3980 term_printf("VLAN %d devices:\n", vlan->id);
3981 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3982 term_printf(" %s\n", vc->info_str);
3986 /* Parse IDE and SCSI disk options */
3987 static int disk_options_init(int num_ide_disks,
3988 char ide_disk_options[][DISK_OPTIONS_SIZE],
3989 int snapshot,
3990 int num_scsi_disks,
3991 char scsi_disk_options[][DISK_OPTIONS_SIZE],
3992 int cdrom_index,
3993 int cyls,
3994 int heads,
3995 int secs,
3996 int translation)
3998 char buf[256];
3999 char dev_name[64];
4000 int id, i, j;
4001 int cdrom_device;
4002 int ide_cdrom_created = 0;
4003 int scsi_index;
4004 scsi_host_adapters temp_adapter;
4006 /* Process any IDE disks/cdroms */
4007 for (i=0; i< num_ide_disks; i++) {
4008 for (j=0; j<MAX_DISKS; j++) {
4009 if (ide_disk_options[j][0] == '\0')
4010 continue;
4012 if (get_param_value(buf, sizeof(buf),"type",ide_disk_options[j])) {
4013 if (!strcmp(buf, "disk")) {
4014 cdrom_device = 0;
4015 } else if (!strcmp(buf, "cdrom")) {
4016 cdrom_device = 1;
4017 ide_cdrom_created = 1;
4018 } else {
4019 fprintf(stderr, "qemu: invalid IDE disk type= value: %s\n", buf);
4020 return -1;
4022 } else {
4023 cdrom_device = 0;
4026 if (cdrom_device) {
4027 snprintf(dev_name, sizeof(dev_name), "cdrom%c", i + '0');
4028 } else {
4029 snprintf(dev_name, sizeof(dev_name), "hd%c", i + 'a');
4032 if (!(get_param_value(buf, sizeof(buf),"img",ide_disk_options[j]))) {
4033 fprintf(stderr, "qemu: missing IDE disk img= value.\n");
4034 return -1;
4037 if (!(bs_table[i] = bdrv_new(dev_name))) {
4038 fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
4039 return -1;
4042 if (cdrom_device) {
4043 bdrv_set_type_hint(bs_table[i], BDRV_TYPE_CDROM);
4046 if (bdrv_open(bs_table[i], buf, snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
4047 fprintf(stderr, "qemu: could not open hard disk image: '%s'\n",
4048 buf);
4049 return -1;
4051 if (i == 0 && cyls != 0) {
4052 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4053 bdrv_set_translation_hint(bs_table[i], translation);
4055 ide_disk_options[j][0] = '\0';
4057 if (i == cdrom_index) {
4058 cdrom_index = -1;
4060 break; /* finished with this IDE device*/
4064 if (cdrom_index >= 0 && (!ide_cdrom_created)) {
4065 bs_table[cdrom_index] = bdrv_new("cdrom");
4066 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4069 for(i = 0; i < num_scsi_disks; i++) {
4071 #if !defined(TARGET_SPARC) || defined(TARGET_SPARC64)
4072 temp_adapter = SCSI_LSI_53C895A;
4073 scsi_hba_lsi++;
4074 #else
4075 temp_adapter = SCSI_ESP;
4076 #endif
4078 /*Check for sdx= parameter */
4079 if (get_param_value(buf, sizeof(buf), "sdx", scsi_disk_options[i])) {
4080 if (buf[0] >= 'a' && buf[0] <= 'g') {
4081 scsi_index = buf[0] - 'a';
4082 } else{
4083 fprintf(stderr, "qemu: sdx= option for SCSI must be one letter from a-g. %s \n",buf);
4084 exit(1);
4086 } else {
4087 scsi_index = 0;
4090 /* Check for SCSI id specified. */
4091 if (get_param_value(buf, sizeof(buf),"id",scsi_disk_options[i])) {
4092 id = strtol(buf, NULL, 0);
4093 if (id < 0 || id > 6) {
4094 fprintf(stderr, "qemu: SCSI id must be from 0-6: %d\n", id);
4095 return -1;
4097 /* Check if id already used */
4098 for(j = 0; j < MAX_SCSI_DISKS; j++) {
4099 if (scsi_disks_info[j].device_type != SCSI_NONE &&
4100 j != i &&
4101 scsi_disks_info[j].adapter == temp_adapter &&
4102 scsi_disks_info[j].id == id ) {
4103 fprintf(stderr, "qemu: SCSI id already used: %u\n", id);
4104 return -1;
4107 } else {
4108 id = -1;
4110 scsi_disks_info[i].adapter = temp_adapter;
4111 scsi_disks_info[i].id = id;
4113 if (get_param_value(buf, sizeof(buf),"type",scsi_disk_options[i])) {
4114 if (!strcmp(buf, "disk")) {
4115 cdrom_device = 0;
4116 } else if (!strcmp(buf, "cdrom")) {
4117 cdrom_device = 1;
4118 } else {
4119 fprintf(stderr, "qemu: invalid SCSI disk type= value: %s\n", buf);
4120 return -1;
4122 } else {
4123 cdrom_device = 0;
4126 if (cdrom_device) {
4127 snprintf(dev_name, sizeof(buf), "cdrom%c", scsi_index + '0');
4128 scsi_disks_info[scsi_index].device_type = SCSI_CDROM;
4129 } else {
4130 snprintf(dev_name, sizeof(buf), "sd%c", scsi_index + 'a');
4131 scsi_disks_info[scsi_index].device_type = SCSI_DISK;
4134 if (!(bs_scsi_table[scsi_index] = bdrv_new(dev_name))) {
4135 fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
4136 return -1;
4139 /* Get image filename from options and then try to open it */
4140 if (get_param_value(buf, sizeof(buf),"img",scsi_disk_options[i])) {
4141 if (bdrv_open(bs_scsi_table[scsi_index], buf, 0) < 0) {
4142 fprintf(stderr, "qemu: could not open SCSI disk image img='%s'\n",buf);
4143 return -1;
4145 } else {
4146 fprintf(stderr, "qemu: SCSI disk image not specified for sd%c \n", i + 'a');
4147 return -1;
4149 if (cdrom_device) {
4150 bdrv_set_type_hint(bs_scsi_table[scsi_index], BDRV_TYPE_CDROM);
4154 return 0;
4158 /***********************************************************/
4159 /* USB devices */
4161 static USBPort *used_usb_ports;
4162 static USBPort *free_usb_ports;
4164 /* ??? Maybe change this to register a hub to keep track of the topology. */
4165 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4166 usb_attachfn attach)
4168 port->opaque = opaque;
4169 port->index = index;
4170 port->attach = attach;
4171 port->next = free_usb_ports;
4172 free_usb_ports = port;
4175 static int usb_device_add(const char *devname)
4177 const char *p;
4178 USBDevice *dev;
4179 USBPort *port;
4181 if (!free_usb_ports)
4182 return -1;
4184 if (strstart(devname, "host:", &p)) {
4185 dev = usb_host_device_open(p);
4186 } else if (!strcmp(devname, "mouse")) {
4187 dev = usb_mouse_init();
4188 } else if (!strcmp(devname, "tablet")) {
4189 dev = usb_tablet_init();
4190 } else if (strstart(devname, "disk:", &p)) {
4191 dev = usb_msd_init(p);
4192 } else {
4193 return -1;
4195 if (!dev)
4196 return -1;
4198 /* Find a USB port to add the device to. */
4199 port = free_usb_ports;
4200 if (!port->next) {
4201 USBDevice *hub;
4203 /* Create a new hub and chain it on. */
4204 free_usb_ports = NULL;
4205 port->next = used_usb_ports;
4206 used_usb_ports = port;
4208 hub = usb_hub_init(VM_USB_HUB_SIZE);
4209 usb_attach(port, hub);
4210 port = free_usb_ports;
4213 free_usb_ports = port->next;
4214 port->next = used_usb_ports;
4215 used_usb_ports = port;
4216 usb_attach(port, dev);
4217 return 0;
4220 static int usb_device_del(const char *devname)
4222 USBPort *port;
4223 USBPort **lastp;
4224 USBDevice *dev;
4225 int bus_num, addr;
4226 const char *p;
4228 if (!used_usb_ports)
4229 return -1;
4231 p = strchr(devname, '.');
4232 if (!p)
4233 return -1;
4234 bus_num = strtoul(devname, NULL, 0);
4235 addr = strtoul(p + 1, NULL, 0);
4236 if (bus_num != 0)
4237 return -1;
4239 lastp = &used_usb_ports;
4240 port = used_usb_ports;
4241 while (port && port->dev->addr != addr) {
4242 lastp = &port->next;
4243 port = port->next;
4246 if (!port)
4247 return -1;
4249 dev = port->dev;
4250 *lastp = port->next;
4251 usb_attach(port, NULL);
4252 dev->handle_destroy(dev);
4253 port->next = free_usb_ports;
4254 free_usb_ports = port;
4255 return 0;
4258 void do_usb_add(const char *devname)
4260 int ret;
4261 ret = usb_device_add(devname);
4262 if (ret < 0)
4263 term_printf("Could not add USB device '%s'\n", devname);
4266 void do_usb_del(const char *devname)
4268 int ret;
4269 ret = usb_device_del(devname);
4270 if (ret < 0)
4271 term_printf("Could not remove USB device '%s'\n", devname);
4274 void usb_info(void)
4276 USBDevice *dev;
4277 USBPort *port;
4278 const char *speed_str;
4280 if (!usb_enabled) {
4281 term_printf("USB support not enabled\n");
4282 return;
4285 for (port = used_usb_ports; port; port = port->next) {
4286 dev = port->dev;
4287 if (!dev)
4288 continue;
4289 switch(dev->speed) {
4290 case USB_SPEED_LOW:
4291 speed_str = "1.5";
4292 break;
4293 case USB_SPEED_FULL:
4294 speed_str = "12";
4295 break;
4296 case USB_SPEED_HIGH:
4297 speed_str = "480";
4298 break;
4299 default:
4300 speed_str = "?";
4301 break;
4303 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4304 0, dev->addr, speed_str, dev->devname);
4308 /***********************************************************/
4309 /* pid file */
4311 static char *pid_filename;
4313 /* Remove PID file. Called on normal exit */
4315 static void remove_pidfile(void)
4317 unlink (pid_filename);
4320 static void create_pidfile(const char *filename)
4322 struct stat pidstat;
4323 FILE *f;
4325 /* Try to write our PID to the named file */
4326 if (stat(filename, &pidstat) < 0) {
4327 if (errno == ENOENT) {
4328 if ((f = fopen (filename, "w")) == NULL) {
4329 perror("Opening pidfile");
4330 exit(1);
4332 fprintf(f, "%d\n", getpid());
4333 fclose(f);
4334 pid_filename = qemu_strdup(filename);
4335 if (!pid_filename) {
4336 fprintf(stderr, "Could not save PID filename");
4337 exit(1);
4339 atexit(remove_pidfile);
4341 } else {
4342 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4343 filename);
4344 exit(1);
4348 /***********************************************************/
4349 /* dumb display */
4351 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4355 static void dumb_resize(DisplayState *ds, int w, int h)
4359 static void dumb_refresh(DisplayState *ds)
4361 vga_hw_update();
4364 void dumb_display_init(DisplayState *ds)
4366 ds->data = NULL;
4367 ds->linesize = 0;
4368 ds->depth = 0;
4369 ds->dpy_update = dumb_update;
4370 ds->dpy_resize = dumb_resize;
4371 ds->dpy_refresh = dumb_refresh;
4374 /***********************************************************/
4375 /* I/O handling */
4377 #define MAX_IO_HANDLERS 64
4379 typedef struct IOHandlerRecord {
4380 int fd;
4381 IOCanRWHandler *fd_read_poll;
4382 IOHandler *fd_read;
4383 IOHandler *fd_write;
4384 void *opaque;
4385 /* temporary data */
4386 struct pollfd *ufd;
4387 struct IOHandlerRecord *next;
4388 } IOHandlerRecord;
4390 static IOHandlerRecord *first_io_handler;
4392 /* XXX: fd_read_poll should be suppressed, but an API change is
4393 necessary in the character devices to suppress fd_can_read(). */
4394 int qemu_set_fd_handler2(int fd,
4395 IOCanRWHandler *fd_read_poll,
4396 IOHandler *fd_read,
4397 IOHandler *fd_write,
4398 void *opaque)
4400 IOHandlerRecord **pioh, *ioh;
4402 if (!fd_read && !fd_write) {
4403 pioh = &first_io_handler;
4404 for(;;) {
4405 ioh = *pioh;
4406 if (ioh == NULL)
4407 break;
4408 if (ioh->fd == fd) {
4409 *pioh = ioh->next;
4410 qemu_free(ioh);
4411 break;
4413 pioh = &ioh->next;
4415 } else {
4416 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4417 if (ioh->fd == fd)
4418 goto found;
4420 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4421 if (!ioh)
4422 return -1;
4423 ioh->next = first_io_handler;
4424 first_io_handler = ioh;
4425 found:
4426 ioh->fd = fd;
4427 ioh->fd_read_poll = fd_read_poll;
4428 ioh->fd_read = fd_read;
4429 ioh->fd_write = fd_write;
4430 ioh->opaque = opaque;
4432 return 0;
4435 int qemu_set_fd_handler(int fd,
4436 IOHandler *fd_read,
4437 IOHandler *fd_write,
4438 void *opaque)
4440 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4443 /***********************************************************/
4444 /* Polling handling */
4446 typedef struct PollingEntry {
4447 PollingFunc *func;
4448 void *opaque;
4449 struct PollingEntry *next;
4450 } PollingEntry;
4452 static PollingEntry *first_polling_entry;
4454 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4456 PollingEntry **ppe, *pe;
4457 pe = qemu_mallocz(sizeof(PollingEntry));
4458 if (!pe)
4459 return -1;
4460 pe->func = func;
4461 pe->opaque = opaque;
4462 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4463 *ppe = pe;
4464 return 0;
4467 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4469 PollingEntry **ppe, *pe;
4470 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4471 pe = *ppe;
4472 if (pe->func == func && pe->opaque == opaque) {
4473 *ppe = pe->next;
4474 qemu_free(pe);
4475 break;
4480 #ifdef _WIN32
4481 /***********************************************************/
4482 /* Wait objects support */
4483 typedef struct WaitObjects {
4484 int num;
4485 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4486 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4487 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4488 } WaitObjects;
4490 static WaitObjects wait_objects = {0};
4492 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4494 WaitObjects *w = &wait_objects;
4496 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4497 return -1;
4498 w->events[w->num] = handle;
4499 w->func[w->num] = func;
4500 w->opaque[w->num] = opaque;
4501 w->num++;
4502 return 0;
4505 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4507 int i, found;
4508 WaitObjects *w = &wait_objects;
4510 found = 0;
4511 for (i = 0; i < w->num; i++) {
4512 if (w->events[i] == handle)
4513 found = 1;
4514 if (found) {
4515 w->events[i] = w->events[i + 1];
4516 w->func[i] = w->func[i + 1];
4517 w->opaque[i] = w->opaque[i + 1];
4520 if (found)
4521 w->num--;
4523 #endif
4525 /***********************************************************/
4526 /* savevm/loadvm support */
4528 #define IO_BUF_SIZE 32768
4530 struct QEMUFile {
4531 FILE *outfile;
4532 BlockDriverState *bs;
4533 int is_file;
4534 int is_writable;
4535 int64_t base_offset;
4536 int64_t buf_offset; /* start of buffer when writing, end of buffer
4537 when reading */
4538 int buf_index;
4539 int buf_size; /* 0 when writing */
4540 uint8_t buf[IO_BUF_SIZE];
4543 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4545 QEMUFile *f;
4547 f = qemu_mallocz(sizeof(QEMUFile));
4548 if (!f)
4549 return NULL;
4550 if (!strcmp(mode, "wb")) {
4551 f->is_writable = 1;
4552 } else if (!strcmp(mode, "rb")) {
4553 f->is_writable = 0;
4554 } else {
4555 goto fail;
4557 f->outfile = fopen(filename, mode);
4558 if (!f->outfile)
4559 goto fail;
4560 f->is_file = 1;
4561 return f;
4562 fail:
4563 if (f->outfile)
4564 fclose(f->outfile);
4565 qemu_free(f);
4566 return NULL;
4569 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4571 QEMUFile *f;
4573 f = qemu_mallocz(sizeof(QEMUFile));
4574 if (!f)
4575 return NULL;
4576 f->is_file = 0;
4577 f->bs = bs;
4578 f->is_writable = is_writable;
4579 f->base_offset = offset;
4580 return f;
4583 void qemu_fflush(QEMUFile *f)
4585 if (!f->is_writable)
4586 return;
4587 if (f->buf_index > 0) {
4588 if (f->is_file) {
4589 fseek(f->outfile, f->buf_offset, SEEK_SET);
4590 fwrite(f->buf, 1, f->buf_index, f->outfile);
4591 } else {
4592 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4593 f->buf, f->buf_index);
4595 f->buf_offset += f->buf_index;
4596 f->buf_index = 0;
4600 static void qemu_fill_buffer(QEMUFile *f)
4602 int len;
4604 if (f->is_writable)
4605 return;
4606 if (f->is_file) {
4607 fseek(f->outfile, f->buf_offset, SEEK_SET);
4608 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4609 if (len < 0)
4610 len = 0;
4611 } else {
4612 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4613 f->buf, IO_BUF_SIZE);
4614 if (len < 0)
4615 len = 0;
4617 f->buf_index = 0;
4618 f->buf_size = len;
4619 f->buf_offset += len;
4622 void qemu_fclose(QEMUFile *f)
4624 if (f->is_writable)
4625 qemu_fflush(f);
4626 if (f->is_file) {
4627 fclose(f->outfile);
4629 qemu_free(f);
4632 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4634 int l;
4635 while (size > 0) {
4636 l = IO_BUF_SIZE - f->buf_index;
4637 if (l > size)
4638 l = size;
4639 memcpy(f->buf + f->buf_index, buf, l);
4640 f->buf_index += l;
4641 buf += l;
4642 size -= l;
4643 if (f->buf_index >= IO_BUF_SIZE)
4644 qemu_fflush(f);
4648 void qemu_put_byte(QEMUFile *f, int v)
4650 f->buf[f->buf_index++] = v;
4651 if (f->buf_index >= IO_BUF_SIZE)
4652 qemu_fflush(f);
4655 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4657 int size, l;
4659 size = size1;
4660 while (size > 0) {
4661 l = f->buf_size - f->buf_index;
4662 if (l == 0) {
4663 qemu_fill_buffer(f);
4664 l = f->buf_size - f->buf_index;
4665 if (l == 0)
4666 break;
4668 if (l > size)
4669 l = size;
4670 memcpy(buf, f->buf + f->buf_index, l);
4671 f->buf_index += l;
4672 buf += l;
4673 size -= l;
4675 return size1 - size;
4678 int qemu_get_byte(QEMUFile *f)
4680 if (f->buf_index >= f->buf_size) {
4681 qemu_fill_buffer(f);
4682 if (f->buf_index >= f->buf_size)
4683 return 0;
4685 return f->buf[f->buf_index++];
4688 int64_t qemu_ftell(QEMUFile *f)
4690 return f->buf_offset - f->buf_size + f->buf_index;
4693 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4695 if (whence == SEEK_SET) {
4696 /* nothing to do */
4697 } else if (whence == SEEK_CUR) {
4698 pos += qemu_ftell(f);
4699 } else {
4700 /* SEEK_END not supported */
4701 return -1;
4703 if (f->is_writable) {
4704 qemu_fflush(f);
4705 f->buf_offset = pos;
4706 } else {
4707 f->buf_offset = pos;
4708 f->buf_index = 0;
4709 f->buf_size = 0;
4711 return pos;
4714 void qemu_put_be16(QEMUFile *f, unsigned int v)
4716 qemu_put_byte(f, v >> 8);
4717 qemu_put_byte(f, v);
4720 void qemu_put_be32(QEMUFile *f, unsigned int v)
4722 qemu_put_byte(f, v >> 24);
4723 qemu_put_byte(f, v >> 16);
4724 qemu_put_byte(f, v >> 8);
4725 qemu_put_byte(f, v);
4728 void qemu_put_be64(QEMUFile *f, uint64_t v)
4730 qemu_put_be32(f, v >> 32);
4731 qemu_put_be32(f, v);
4734 unsigned int qemu_get_be16(QEMUFile *f)
4736 unsigned int v;
4737 v = qemu_get_byte(f) << 8;
4738 v |= qemu_get_byte(f);
4739 return v;
4742 unsigned int qemu_get_be32(QEMUFile *f)
4744 unsigned int v;
4745 v = qemu_get_byte(f) << 24;
4746 v |= qemu_get_byte(f) << 16;
4747 v |= qemu_get_byte(f) << 8;
4748 v |= qemu_get_byte(f);
4749 return v;
4752 uint64_t qemu_get_be64(QEMUFile *f)
4754 uint64_t v;
4755 v = (uint64_t)qemu_get_be32(f) << 32;
4756 v |= qemu_get_be32(f);
4757 return v;
4760 typedef struct SaveStateEntry {
4761 char idstr[256];
4762 int instance_id;
4763 int version_id;
4764 SaveStateHandler *save_state;
4765 LoadStateHandler *load_state;
4766 void *opaque;
4767 struct SaveStateEntry *next;
4768 } SaveStateEntry;
4770 static SaveStateEntry *first_se;
4772 int register_savevm(const char *idstr,
4773 int instance_id,
4774 int version_id,
4775 SaveStateHandler *save_state,
4776 LoadStateHandler *load_state,
4777 void *opaque)
4779 SaveStateEntry *se, **pse;
4781 se = qemu_malloc(sizeof(SaveStateEntry));
4782 if (!se)
4783 return -1;
4784 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4785 se->instance_id = instance_id;
4786 se->version_id = version_id;
4787 se->save_state = save_state;
4788 se->load_state = load_state;
4789 se->opaque = opaque;
4790 se->next = NULL;
4792 /* add at the end of list */
4793 pse = &first_se;
4794 while (*pse != NULL)
4795 pse = &(*pse)->next;
4796 *pse = se;
4797 return 0;
4800 #define QEMU_VM_FILE_MAGIC 0x5145564d
4801 #define QEMU_VM_FILE_VERSION 0x00000002
4803 int qemu_savevm_state(QEMUFile *f)
4805 SaveStateEntry *se;
4806 int len, ret;
4807 int64_t cur_pos, len_pos, total_len_pos;
4809 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4810 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4811 total_len_pos = qemu_ftell(f);
4812 qemu_put_be64(f, 0); /* total size */
4814 for(se = first_se; se != NULL; se = se->next) {
4815 /* ID string */
4816 len = strlen(se->idstr);
4817 qemu_put_byte(f, len);
4818 qemu_put_buffer(f, se->idstr, len);
4820 qemu_put_be32(f, se->instance_id);
4821 qemu_put_be32(f, se->version_id);
4823 /* record size: filled later */
4824 len_pos = qemu_ftell(f);
4825 qemu_put_be32(f, 0);
4827 se->save_state(f, se->opaque);
4829 /* fill record size */
4830 cur_pos = qemu_ftell(f);
4831 len = cur_pos - len_pos - 4;
4832 qemu_fseek(f, len_pos, SEEK_SET);
4833 qemu_put_be32(f, len);
4834 qemu_fseek(f, cur_pos, SEEK_SET);
4836 cur_pos = qemu_ftell(f);
4837 qemu_fseek(f, total_len_pos, SEEK_SET);
4838 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4839 qemu_fseek(f, cur_pos, SEEK_SET);
4841 ret = 0;
4842 return ret;
4845 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4847 SaveStateEntry *se;
4849 for(se = first_se; se != NULL; se = se->next) {
4850 if (!strcmp(se->idstr, idstr) &&
4851 instance_id == se->instance_id)
4852 return se;
4854 return NULL;
4857 int qemu_loadvm_state(QEMUFile *f)
4859 SaveStateEntry *se;
4860 int len, ret, instance_id, record_len, version_id;
4861 int64_t total_len, end_pos, cur_pos;
4862 unsigned int v;
4863 char idstr[256];
4865 v = qemu_get_be32(f);
4866 if (v != QEMU_VM_FILE_MAGIC)
4867 goto fail;
4868 v = qemu_get_be32(f);
4869 if (v != QEMU_VM_FILE_VERSION) {
4870 fail:
4871 ret = -1;
4872 goto the_end;
4874 total_len = qemu_get_be64(f);
4875 end_pos = total_len + qemu_ftell(f);
4876 for(;;) {
4877 if (qemu_ftell(f) >= end_pos)
4878 break;
4879 len = qemu_get_byte(f);
4880 qemu_get_buffer(f, idstr, len);
4881 idstr[len] = '\0';
4882 instance_id = qemu_get_be32(f);
4883 version_id = qemu_get_be32(f);
4884 record_len = qemu_get_be32(f);
4885 #if 0
4886 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4887 idstr, instance_id, version_id, record_len);
4888 #endif
4889 cur_pos = qemu_ftell(f);
4890 se = find_se(idstr, instance_id);
4891 if (!se) {
4892 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4893 instance_id, idstr);
4894 } else {
4895 ret = se->load_state(f, se->opaque, version_id);
4896 if (ret < 0) {
4897 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4898 instance_id, idstr);
4901 /* always seek to exact end of record */
4902 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4904 ret = 0;
4905 the_end:
4906 return ret;
4909 /* device can contain snapshots */
4910 static int bdrv_can_snapshot(BlockDriverState *bs)
4912 return (bs &&
4913 !bdrv_is_removable(bs) &&
4914 !bdrv_is_read_only(bs));
4917 /* device must be snapshots in order to have a reliable snapshot */
4918 static int bdrv_has_snapshot(BlockDriverState *bs)
4920 return (bs &&
4921 !bdrv_is_removable(bs) &&
4922 !bdrv_is_read_only(bs));
4925 static BlockDriverState *get_bs_snapshots(void)
4927 BlockDriverState *bs;
4928 int i;
4930 if (bs_snapshots)
4931 return bs_snapshots;
4932 for(i = 0; i <= MAX_DISKS; i++) {
4933 bs = bs_table[i];
4934 if (bdrv_can_snapshot(bs))
4935 goto ok;
4937 return NULL;
4939 bs_snapshots = bs;
4940 return bs;
4943 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4944 const char *name)
4946 QEMUSnapshotInfo *sn_tab, *sn;
4947 int nb_sns, i, ret;
4949 ret = -ENOENT;
4950 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4951 if (nb_sns < 0)
4952 return ret;
4953 for(i = 0; i < nb_sns; i++) {
4954 sn = &sn_tab[i];
4955 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4956 *sn_info = *sn;
4957 ret = 0;
4958 break;
4961 qemu_free(sn_tab);
4962 return ret;
4965 void do_savevm(const char *name)
4967 BlockDriverState *bs, *bs1;
4968 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4969 int must_delete, ret, i;
4970 BlockDriverInfo bdi1, *bdi = &bdi1;
4971 QEMUFile *f;
4972 int saved_vm_running;
4973 #ifdef _WIN32
4974 struct _timeb tb;
4975 #else
4976 struct timeval tv;
4977 #endif
4979 bs = get_bs_snapshots();
4980 if (!bs) {
4981 term_printf("No block device can accept snapshots\n");
4982 return;
4985 /* ??? Should this occur after vm_stop? */
4986 qemu_aio_flush();
4988 saved_vm_running = vm_running;
4989 vm_stop(0);
4991 must_delete = 0;
4992 if (name) {
4993 ret = bdrv_snapshot_find(bs, old_sn, name);
4994 if (ret >= 0) {
4995 must_delete = 1;
4998 memset(sn, 0, sizeof(*sn));
4999 if (must_delete) {
5000 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5001 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5002 } else {
5003 if (name)
5004 pstrcpy(sn->name, sizeof(sn->name), name);
5007 /* fill auxiliary fields */
5008 #ifdef _WIN32
5009 _ftime(&tb);
5010 sn->date_sec = tb.time;
5011 sn->date_nsec = tb.millitm * 1000000;
5012 #else
5013 gettimeofday(&tv, NULL);
5014 sn->date_sec = tv.tv_sec;
5015 sn->date_nsec = tv.tv_usec * 1000;
5016 #endif
5017 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5019 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5020 term_printf("Device %s does not support VM state snapshots\n",
5021 bdrv_get_device_name(bs));
5022 goto the_end;
5025 /* save the VM state */
5026 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5027 if (!f) {
5028 term_printf("Could not open VM state file\n");
5029 goto the_end;
5031 ret = qemu_savevm_state(f);
5032 sn->vm_state_size = qemu_ftell(f);
5033 qemu_fclose(f);
5034 if (ret < 0) {
5035 term_printf("Error %d while writing VM\n", ret);
5036 goto the_end;
5039 /* create the snapshots */
5041 for(i = 0; i < MAX_DISKS; i++) {
5042 bs1 = bs_table[i];
5043 if (bdrv_has_snapshot(bs1)) {
5044 if (must_delete) {
5045 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5046 if (ret < 0) {
5047 term_printf("Error while deleting snapshot on '%s'\n",
5048 bdrv_get_device_name(bs1));
5051 ret = bdrv_snapshot_create(bs1, sn);
5052 if (ret < 0) {
5053 term_printf("Error while creating snapshot on '%s'\n",
5054 bdrv_get_device_name(bs1));
5059 the_end:
5060 if (saved_vm_running)
5061 vm_start();
5064 void do_loadvm(const char *name)
5066 BlockDriverState *bs, *bs1;
5067 BlockDriverInfo bdi1, *bdi = &bdi1;
5068 QEMUFile *f;
5069 int i, ret;
5070 int saved_vm_running;
5072 bs = get_bs_snapshots();
5073 if (!bs) {
5074 term_printf("No block device supports snapshots\n");
5075 return;
5078 /* Flush all IO requests so they don't interfere with the new state. */
5079 qemu_aio_flush();
5081 saved_vm_running = vm_running;
5082 vm_stop(0);
5084 for(i = 0; i <= MAX_DISKS; i++) {
5085 bs1 = bs_table[i];
5086 if (bdrv_has_snapshot(bs1)) {
5087 ret = bdrv_snapshot_goto(bs1, name);
5088 if (ret < 0) {
5089 if (bs != bs1)
5090 term_printf("Warning: ");
5091 switch(ret) {
5092 case -ENOTSUP:
5093 term_printf("Snapshots not supported on device '%s'\n",
5094 bdrv_get_device_name(bs1));
5095 break;
5096 case -ENOENT:
5097 term_printf("Could not find snapshot '%s' on device '%s'\n",
5098 name, bdrv_get_device_name(bs1));
5099 break;
5100 default:
5101 term_printf("Error %d while activating snapshot on '%s'\n",
5102 ret, bdrv_get_device_name(bs1));
5103 break;
5105 /* fatal on snapshot block device */
5106 if (bs == bs1)
5107 goto the_end;
5112 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5113 term_printf("Device %s does not support VM state snapshots\n",
5114 bdrv_get_device_name(bs));
5115 return;
5118 /* restore the VM state */
5119 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5120 if (!f) {
5121 term_printf("Could not open VM state file\n");
5122 goto the_end;
5124 ret = qemu_loadvm_state(f);
5125 qemu_fclose(f);
5126 if (ret < 0) {
5127 term_printf("Error %d while loading VM state\n", ret);
5129 the_end:
5130 if (saved_vm_running)
5131 vm_start();
5134 void do_delvm(const char *name)
5136 BlockDriverState *bs, *bs1;
5137 int i, ret;
5139 bs = get_bs_snapshots();
5140 if (!bs) {
5141 term_printf("No block device supports snapshots\n");
5142 return;
5145 for(i = 0; i <= MAX_DISKS; i++) {
5146 bs1 = bs_table[i];
5147 if (bdrv_has_snapshot(bs1)) {
5148 ret = bdrv_snapshot_delete(bs1, name);
5149 if (ret < 0) {
5150 if (ret == -ENOTSUP)
5151 term_printf("Snapshots not supported on device '%s'\n",
5152 bdrv_get_device_name(bs1));
5153 else
5154 term_printf("Error %d while deleting snapshot on '%s'\n",
5155 ret, bdrv_get_device_name(bs1));
5161 void do_info_snapshots(void)
5163 BlockDriverState *bs, *bs1;
5164 QEMUSnapshotInfo *sn_tab, *sn;
5165 int nb_sns, i;
5166 char buf[256];
5168 bs = get_bs_snapshots();
5169 if (!bs) {
5170 term_printf("No available block device supports snapshots\n");
5171 return;
5173 term_printf("Snapshot devices:");
5174 for(i = 0; i <= MAX_DISKS; i++) {
5175 bs1 = bs_table[i];
5176 if (bdrv_has_snapshot(bs1)) {
5177 if (bs == bs1)
5178 term_printf(" %s", bdrv_get_device_name(bs1));
5181 term_printf("\n");
5183 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5184 if (nb_sns < 0) {
5185 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5186 return;
5188 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5189 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5190 for(i = 0; i < nb_sns; i++) {
5191 sn = &sn_tab[i];
5192 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5194 qemu_free(sn_tab);
5197 /***********************************************************/
5198 /* cpu save/restore */
5200 #if defined(TARGET_I386)
5202 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5204 qemu_put_be32(f, dt->selector);
5205 qemu_put_betl(f, dt->base);
5206 qemu_put_be32(f, dt->limit);
5207 qemu_put_be32(f, dt->flags);
5210 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5212 dt->selector = qemu_get_be32(f);
5213 dt->base = qemu_get_betl(f);
5214 dt->limit = qemu_get_be32(f);
5215 dt->flags = qemu_get_be32(f);
5218 void cpu_save(QEMUFile *f, void *opaque)
5220 CPUState *env = opaque;
5221 uint16_t fptag, fpus, fpuc, fpregs_format;
5222 uint32_t hflags;
5223 int i;
5225 for(i = 0; i < CPU_NB_REGS; i++)
5226 qemu_put_betls(f, &env->regs[i]);
5227 qemu_put_betls(f, &env->eip);
5228 qemu_put_betls(f, &env->eflags);
5229 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5230 qemu_put_be32s(f, &hflags);
5232 /* FPU */
5233 fpuc = env->fpuc;
5234 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5235 fptag = 0;
5236 for(i = 0; i < 8; i++) {
5237 fptag |= ((!env->fptags[i]) << i);
5240 qemu_put_be16s(f, &fpuc);
5241 qemu_put_be16s(f, &fpus);
5242 qemu_put_be16s(f, &fptag);
5244 #ifdef USE_X86LDOUBLE
5245 fpregs_format = 0;
5246 #else
5247 fpregs_format = 1;
5248 #endif
5249 qemu_put_be16s(f, &fpregs_format);
5251 for(i = 0; i < 8; i++) {
5252 #ifdef USE_X86LDOUBLE
5254 uint64_t mant;
5255 uint16_t exp;
5256 /* we save the real CPU data (in case of MMX usage only 'mant'
5257 contains the MMX register */
5258 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5259 qemu_put_be64(f, mant);
5260 qemu_put_be16(f, exp);
5262 #else
5263 /* if we use doubles for float emulation, we save the doubles to
5264 avoid losing information in case of MMX usage. It can give
5265 problems if the image is restored on a CPU where long
5266 doubles are used instead. */
5267 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5268 #endif
5271 for(i = 0; i < 6; i++)
5272 cpu_put_seg(f, &env->segs[i]);
5273 cpu_put_seg(f, &env->ldt);
5274 cpu_put_seg(f, &env->tr);
5275 cpu_put_seg(f, &env->gdt);
5276 cpu_put_seg(f, &env->idt);
5278 qemu_put_be32s(f, &env->sysenter_cs);
5279 qemu_put_be32s(f, &env->sysenter_esp);
5280 qemu_put_be32s(f, &env->sysenter_eip);
5282 qemu_put_betls(f, &env->cr[0]);
5283 qemu_put_betls(f, &env->cr[2]);
5284 qemu_put_betls(f, &env->cr[3]);
5285 qemu_put_betls(f, &env->cr[4]);
5287 for(i = 0; i < 8; i++)
5288 qemu_put_betls(f, &env->dr[i]);
5290 /* MMU */
5291 qemu_put_be32s(f, &env->a20_mask);
5293 /* XMM */
5294 qemu_put_be32s(f, &env->mxcsr);
5295 for(i = 0; i < CPU_NB_REGS; i++) {
5296 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5297 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5300 #ifdef TARGET_X86_64
5301 qemu_put_be64s(f, &env->efer);
5302 qemu_put_be64s(f, &env->star);
5303 qemu_put_be64s(f, &env->lstar);
5304 qemu_put_be64s(f, &env->cstar);
5305 qemu_put_be64s(f, &env->fmask);
5306 qemu_put_be64s(f, &env->kernelgsbase);
5307 #endif
5308 qemu_put_be32s(f, &env->smbase);
5311 #ifdef USE_X86LDOUBLE
5312 /* XXX: add that in a FPU generic layer */
5313 union x86_longdouble {
5314 uint64_t mant;
5315 uint16_t exp;
5318 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5319 #define EXPBIAS1 1023
5320 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5321 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5323 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5325 int e;
5326 /* mantissa */
5327 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5328 /* exponent + sign */
5329 e = EXPD1(temp) - EXPBIAS1 + 16383;
5330 e |= SIGND1(temp) >> 16;
5331 p->exp = e;
5333 #endif
5335 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5337 CPUState *env = opaque;
5338 int i, guess_mmx;
5339 uint32_t hflags;
5340 uint16_t fpus, fpuc, fptag, fpregs_format;
5342 if (version_id != 3 && version_id != 4)
5343 return -EINVAL;
5344 for(i = 0; i < CPU_NB_REGS; i++)
5345 qemu_get_betls(f, &env->regs[i]);
5346 qemu_get_betls(f, &env->eip);
5347 qemu_get_betls(f, &env->eflags);
5348 qemu_get_be32s(f, &hflags);
5350 qemu_get_be16s(f, &fpuc);
5351 qemu_get_be16s(f, &fpus);
5352 qemu_get_be16s(f, &fptag);
5353 qemu_get_be16s(f, &fpregs_format);
5355 /* NOTE: we cannot always restore the FPU state if the image come
5356 from a host with a different 'USE_X86LDOUBLE' define. We guess
5357 if we are in an MMX state to restore correctly in that case. */
5358 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5359 for(i = 0; i < 8; i++) {
5360 uint64_t mant;
5361 uint16_t exp;
5363 switch(fpregs_format) {
5364 case 0:
5365 mant = qemu_get_be64(f);
5366 exp = qemu_get_be16(f);
5367 #ifdef USE_X86LDOUBLE
5368 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5369 #else
5370 /* difficult case */
5371 if (guess_mmx)
5372 env->fpregs[i].mmx.MMX_Q(0) = mant;
5373 else
5374 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5375 #endif
5376 break;
5377 case 1:
5378 mant = qemu_get_be64(f);
5379 #ifdef USE_X86LDOUBLE
5381 union x86_longdouble *p;
5382 /* difficult case */
5383 p = (void *)&env->fpregs[i];
5384 if (guess_mmx) {
5385 p->mant = mant;
5386 p->exp = 0xffff;
5387 } else {
5388 fp64_to_fp80(p, mant);
5391 #else
5392 env->fpregs[i].mmx.MMX_Q(0) = mant;
5393 #endif
5394 break;
5395 default:
5396 return -EINVAL;
5400 env->fpuc = fpuc;
5401 /* XXX: restore FPU round state */
5402 env->fpstt = (fpus >> 11) & 7;
5403 env->fpus = fpus & ~0x3800;
5404 fptag ^= 0xff;
5405 for(i = 0; i < 8; i++) {
5406 env->fptags[i] = (fptag >> i) & 1;
5409 for(i = 0; i < 6; i++)
5410 cpu_get_seg(f, &env->segs[i]);
5411 cpu_get_seg(f, &env->ldt);
5412 cpu_get_seg(f, &env->tr);
5413 cpu_get_seg(f, &env->gdt);
5414 cpu_get_seg(f, &env->idt);
5416 qemu_get_be32s(f, &env->sysenter_cs);
5417 qemu_get_be32s(f, &env->sysenter_esp);
5418 qemu_get_be32s(f, &env->sysenter_eip);
5420 qemu_get_betls(f, &env->cr[0]);
5421 qemu_get_betls(f, &env->cr[2]);
5422 qemu_get_betls(f, &env->cr[3]);
5423 qemu_get_betls(f, &env->cr[4]);
5425 for(i = 0; i < 8; i++)
5426 qemu_get_betls(f, &env->dr[i]);
5428 /* MMU */
5429 qemu_get_be32s(f, &env->a20_mask);
5431 qemu_get_be32s(f, &env->mxcsr);
5432 for(i = 0; i < CPU_NB_REGS; i++) {
5433 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5434 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5437 #ifdef TARGET_X86_64
5438 qemu_get_be64s(f, &env->efer);
5439 qemu_get_be64s(f, &env->star);
5440 qemu_get_be64s(f, &env->lstar);
5441 qemu_get_be64s(f, &env->cstar);
5442 qemu_get_be64s(f, &env->fmask);
5443 qemu_get_be64s(f, &env->kernelgsbase);
5444 #endif
5445 if (version_id >= 4)
5446 qemu_get_be32s(f, &env->smbase);
5448 /* XXX: compute hflags from scratch, except for CPL and IIF */
5449 env->hflags = hflags;
5450 tlb_flush(env, 1);
5451 return 0;
5454 #elif defined(TARGET_PPC)
5455 void cpu_save(QEMUFile *f, void *opaque)
5459 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5461 return 0;
5464 #elif defined(TARGET_MIPS)
5465 void cpu_save(QEMUFile *f, void *opaque)
5469 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5471 return 0;
5474 #elif defined(TARGET_SPARC)
5475 void cpu_save(QEMUFile *f, void *opaque)
5477 CPUState *env = opaque;
5478 int i;
5479 uint32_t tmp;
5481 for(i = 0; i < 8; i++)
5482 qemu_put_betls(f, &env->gregs[i]);
5483 for(i = 0; i < NWINDOWS * 16; i++)
5484 qemu_put_betls(f, &env->regbase[i]);
5486 /* FPU */
5487 for(i = 0; i < TARGET_FPREGS; i++) {
5488 union {
5489 float32 f;
5490 uint32_t i;
5491 } u;
5492 u.f = env->fpr[i];
5493 qemu_put_be32(f, u.i);
5496 qemu_put_betls(f, &env->pc);
5497 qemu_put_betls(f, &env->npc);
5498 qemu_put_betls(f, &env->y);
5499 tmp = GET_PSR(env);
5500 qemu_put_be32(f, tmp);
5501 qemu_put_betls(f, &env->fsr);
5502 qemu_put_betls(f, &env->tbr);
5503 #ifndef TARGET_SPARC64
5504 qemu_put_be32s(f, &env->wim);
5505 /* MMU */
5506 for(i = 0; i < 16; i++)
5507 qemu_put_be32s(f, &env->mmuregs[i]);
5508 #endif
5511 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5513 CPUState *env = opaque;
5514 int i;
5515 uint32_t tmp;
5517 for(i = 0; i < 8; i++)
5518 qemu_get_betls(f, &env->gregs[i]);
5519 for(i = 0; i < NWINDOWS * 16; i++)
5520 qemu_get_betls(f, &env->regbase[i]);
5522 /* FPU */
5523 for(i = 0; i < TARGET_FPREGS; i++) {
5524 union {
5525 float32 f;
5526 uint32_t i;
5527 } u;
5528 u.i = qemu_get_be32(f);
5529 env->fpr[i] = u.f;
5532 qemu_get_betls(f, &env->pc);
5533 qemu_get_betls(f, &env->npc);
5534 qemu_get_betls(f, &env->y);
5535 tmp = qemu_get_be32(f);
5536 env->cwp = 0; /* needed to ensure that the wrapping registers are
5537 correctly updated */
5538 PUT_PSR(env, tmp);
5539 qemu_get_betls(f, &env->fsr);
5540 qemu_get_betls(f, &env->tbr);
5541 #ifndef TARGET_SPARC64
5542 qemu_get_be32s(f, &env->wim);
5543 /* MMU */
5544 for(i = 0; i < 16; i++)
5545 qemu_get_be32s(f, &env->mmuregs[i]);
5546 #endif
5547 tlb_flush(env, 1);
5548 return 0;
5551 #elif defined(TARGET_ARM)
5553 /* ??? Need to implement these. */
5554 void cpu_save(QEMUFile *f, void *opaque)
5558 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5560 return 0;
5563 #else
5565 #warning No CPU save/restore functions
5567 #endif
5569 /***********************************************************/
5570 /* ram save/restore */
5572 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5574 int v;
5576 v = qemu_get_byte(f);
5577 switch(v) {
5578 case 0:
5579 if (qemu_get_buffer(f, buf, len) != len)
5580 return -EIO;
5581 break;
5582 case 1:
5583 v = qemu_get_byte(f);
5584 memset(buf, v, len);
5585 break;
5586 default:
5587 return -EINVAL;
5589 return 0;
5592 static int ram_load_v1(QEMUFile *f, void *opaque)
5594 int i, ret;
5596 if (qemu_get_be32(f) != phys_ram_size)
5597 return -EINVAL;
5598 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5599 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5600 if (ret)
5601 return ret;
5603 return 0;
5606 #define BDRV_HASH_BLOCK_SIZE 1024
5607 #define IOBUF_SIZE 4096
5608 #define RAM_CBLOCK_MAGIC 0xfabe
5610 typedef struct RamCompressState {
5611 z_stream zstream;
5612 QEMUFile *f;
5613 uint8_t buf[IOBUF_SIZE];
5614 } RamCompressState;
5616 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5618 int ret;
5619 memset(s, 0, sizeof(*s));
5620 s->f = f;
5621 ret = deflateInit2(&s->zstream, 1,
5622 Z_DEFLATED, 15,
5623 9, Z_DEFAULT_STRATEGY);
5624 if (ret != Z_OK)
5625 return -1;
5626 s->zstream.avail_out = IOBUF_SIZE;
5627 s->zstream.next_out = s->buf;
5628 return 0;
5631 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5633 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5634 qemu_put_be16(s->f, len);
5635 qemu_put_buffer(s->f, buf, len);
5638 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5640 int ret;
5642 s->zstream.avail_in = len;
5643 s->zstream.next_in = (uint8_t *)buf;
5644 while (s->zstream.avail_in > 0) {
5645 ret = deflate(&s->zstream, Z_NO_FLUSH);
5646 if (ret != Z_OK)
5647 return -1;
5648 if (s->zstream.avail_out == 0) {
5649 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5650 s->zstream.avail_out = IOBUF_SIZE;
5651 s->zstream.next_out = s->buf;
5654 return 0;
5657 static void ram_compress_close(RamCompressState *s)
5659 int len, ret;
5661 /* compress last bytes */
5662 for(;;) {
5663 ret = deflate(&s->zstream, Z_FINISH);
5664 if (ret == Z_OK || ret == Z_STREAM_END) {
5665 len = IOBUF_SIZE - s->zstream.avail_out;
5666 if (len > 0) {
5667 ram_put_cblock(s, s->buf, len);
5669 s->zstream.avail_out = IOBUF_SIZE;
5670 s->zstream.next_out = s->buf;
5671 if (ret == Z_STREAM_END)
5672 break;
5673 } else {
5674 goto fail;
5677 fail:
5678 deflateEnd(&s->zstream);
5681 typedef struct RamDecompressState {
5682 z_stream zstream;
5683 QEMUFile *f;
5684 uint8_t buf[IOBUF_SIZE];
5685 } RamDecompressState;
5687 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5689 int ret;
5690 memset(s, 0, sizeof(*s));
5691 s->f = f;
5692 ret = inflateInit(&s->zstream);
5693 if (ret != Z_OK)
5694 return -1;
5695 return 0;
5698 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5700 int ret, clen;
5702 s->zstream.avail_out = len;
5703 s->zstream.next_out = buf;
5704 while (s->zstream.avail_out > 0) {
5705 if (s->zstream.avail_in == 0) {
5706 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5707 return -1;
5708 clen = qemu_get_be16(s->f);
5709 if (clen > IOBUF_SIZE)
5710 return -1;
5711 qemu_get_buffer(s->f, s->buf, clen);
5712 s->zstream.avail_in = clen;
5713 s->zstream.next_in = s->buf;
5715 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5716 if (ret != Z_OK && ret != Z_STREAM_END) {
5717 return -1;
5720 return 0;
5723 static void ram_decompress_close(RamDecompressState *s)
5725 inflateEnd(&s->zstream);
5728 static void ram_save(QEMUFile *f, void *opaque)
5730 int i;
5731 RamCompressState s1, *s = &s1;
5732 uint8_t buf[10];
5734 qemu_put_be32(f, phys_ram_size);
5735 if (ram_compress_open(s, f) < 0)
5736 return;
5737 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5738 #if 0
5739 if (tight_savevm_enabled) {
5740 int64_t sector_num;
5741 int j;
5743 /* find if the memory block is available on a virtual
5744 block device */
5745 sector_num = -1;
5746 for(j = 0; j < MAX_DISKS; j++) {
5747 if (bs_table[j]) {
5748 sector_num = bdrv_hash_find(bs_table[j],
5749 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5750 if (sector_num >= 0)
5751 break;
5754 if (j == MAX_DISKS)
5755 goto normal_compress;
5756 buf[0] = 1;
5757 buf[1] = j;
5758 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5759 ram_compress_buf(s, buf, 10);
5760 } else
5761 #endif
5763 // normal_compress:
5764 buf[0] = 0;
5765 ram_compress_buf(s, buf, 1);
5766 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5769 ram_compress_close(s);
5772 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5774 RamDecompressState s1, *s = &s1;
5775 uint8_t buf[10];
5776 int i;
5778 if (version_id == 1)
5779 return ram_load_v1(f, opaque);
5780 if (version_id != 2)
5781 return -EINVAL;
5782 if (qemu_get_be32(f) != phys_ram_size)
5783 return -EINVAL;
5784 if (ram_decompress_open(s, f) < 0)
5785 return -EINVAL;
5786 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5787 if (ram_decompress_buf(s, buf, 1) < 0) {
5788 fprintf(stderr, "Error while reading ram block header\n");
5789 goto error;
5791 if (buf[0] == 0) {
5792 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5793 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5794 goto error;
5796 } else
5797 #if 0
5798 if (buf[0] == 1) {
5799 int bs_index;
5800 int64_t sector_num;
5802 ram_decompress_buf(s, buf + 1, 9);
5803 bs_index = buf[1];
5804 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5805 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5806 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5807 goto error;
5809 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5810 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5811 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5812 bs_index, sector_num);
5813 goto error;
5815 } else
5816 #endif
5818 error:
5819 printf("Error block header\n");
5820 return -EINVAL;
5823 ram_decompress_close(s);
5824 return 0;
5827 /***********************************************************/
5828 /* bottom halves (can be seen as timers which expire ASAP) */
5830 struct QEMUBH {
5831 QEMUBHFunc *cb;
5832 void *opaque;
5833 int scheduled;
5834 QEMUBH *next;
5837 static QEMUBH *first_bh = NULL;
5839 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5841 QEMUBH *bh;
5842 bh = qemu_mallocz(sizeof(QEMUBH));
5843 if (!bh)
5844 return NULL;
5845 bh->cb = cb;
5846 bh->opaque = opaque;
5847 return bh;
5850 int qemu_bh_poll(void)
5852 QEMUBH *bh, **pbh;
5853 int ret;
5855 ret = 0;
5856 for(;;) {
5857 pbh = &first_bh;
5858 bh = *pbh;
5859 if (!bh)
5860 break;
5861 ret = 1;
5862 *pbh = bh->next;
5863 bh->scheduled = 0;
5864 bh->cb(bh->opaque);
5866 return ret;
5869 void qemu_bh_schedule(QEMUBH *bh)
5871 CPUState *env = cpu_single_env;
5872 if (bh->scheduled)
5873 return;
5874 bh->scheduled = 1;
5875 bh->next = first_bh;
5876 first_bh = bh;
5878 /* stop the currently executing CPU to execute the BH ASAP */
5879 if (env) {
5880 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5884 void qemu_bh_cancel(QEMUBH *bh)
5886 QEMUBH **pbh;
5887 if (bh->scheduled) {
5888 pbh = &first_bh;
5889 while (*pbh != bh)
5890 pbh = &(*pbh)->next;
5891 *pbh = bh->next;
5892 bh->scheduled = 0;
5896 void qemu_bh_delete(QEMUBH *bh)
5898 qemu_bh_cancel(bh);
5899 qemu_free(bh);
5902 /***********************************************************/
5903 /* machine registration */
5905 QEMUMachine *first_machine = NULL;
5907 int qemu_register_machine(QEMUMachine *m)
5909 QEMUMachine **pm;
5910 pm = &first_machine;
5911 while (*pm != NULL)
5912 pm = &(*pm)->next;
5913 m->next = NULL;
5914 *pm = m;
5915 return 0;
5918 QEMUMachine *find_machine(const char *name)
5920 QEMUMachine *m;
5922 for(m = first_machine; m != NULL; m = m->next) {
5923 if (!strcmp(m->name, name))
5924 return m;
5926 return NULL;
5929 /***********************************************************/
5930 /* main execution loop */
5932 void gui_update(void *opaque)
5934 display_state.dpy_refresh(&display_state);
5935 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5938 struct vm_change_state_entry {
5939 VMChangeStateHandler *cb;
5940 void *opaque;
5941 LIST_ENTRY (vm_change_state_entry) entries;
5944 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5946 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5947 void *opaque)
5949 VMChangeStateEntry *e;
5951 e = qemu_mallocz(sizeof (*e));
5952 if (!e)
5953 return NULL;
5955 e->cb = cb;
5956 e->opaque = opaque;
5957 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5958 return e;
5961 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5963 LIST_REMOVE (e, entries);
5964 qemu_free (e);
5967 static void vm_state_notify(int running)
5969 VMChangeStateEntry *e;
5971 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5972 e->cb(e->opaque, running);
5976 /* XXX: support several handlers */
5977 static VMStopHandler *vm_stop_cb;
5978 static void *vm_stop_opaque;
5980 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5982 vm_stop_cb = cb;
5983 vm_stop_opaque = opaque;
5984 return 0;
5987 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5989 vm_stop_cb = NULL;
5992 void vm_start(void)
5994 if (!vm_running) {
5995 cpu_enable_ticks();
5996 vm_running = 1;
5997 vm_state_notify(1);
6001 void vm_stop(int reason)
6003 if (vm_running) {
6004 cpu_disable_ticks();
6005 vm_running = 0;
6006 if (reason != 0) {
6007 if (vm_stop_cb) {
6008 vm_stop_cb(vm_stop_opaque, reason);
6011 vm_state_notify(0);
6015 /* reset/shutdown handler */
6017 typedef struct QEMUResetEntry {
6018 QEMUResetHandler *func;
6019 void *opaque;
6020 struct QEMUResetEntry *next;
6021 } QEMUResetEntry;
6023 static QEMUResetEntry *first_reset_entry;
6024 static int reset_requested;
6025 static int shutdown_requested;
6026 static int powerdown_requested;
6028 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6030 QEMUResetEntry **pre, *re;
6032 pre = &first_reset_entry;
6033 while (*pre != NULL)
6034 pre = &(*pre)->next;
6035 re = qemu_mallocz(sizeof(QEMUResetEntry));
6036 re->func = func;
6037 re->opaque = opaque;
6038 re->next = NULL;
6039 *pre = re;
6042 static void qemu_system_reset(void)
6044 QEMUResetEntry *re;
6046 /* reset all devices */
6047 for(re = first_reset_entry; re != NULL; re = re->next) {
6048 re->func(re->opaque);
6052 void qemu_system_reset_request(void)
6054 if (no_reboot) {
6055 shutdown_requested = 1;
6056 } else {
6057 reset_requested = 1;
6059 if (cpu_single_env)
6060 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6063 void qemu_system_shutdown_request(void)
6065 shutdown_requested = 1;
6066 if (cpu_single_env)
6067 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6070 void qemu_system_powerdown_request(void)
6072 powerdown_requested = 1;
6073 if (cpu_single_env)
6074 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6077 void main_loop_wait(int timeout)
6079 IOHandlerRecord *ioh, *ioh_next;
6080 fd_set rfds, wfds, xfds;
6081 int ret, nfds;
6082 struct timeval tv;
6083 PollingEntry *pe;
6086 /* XXX: need to suppress polling by better using win32 events */
6087 ret = 0;
6088 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6089 ret |= pe->func(pe->opaque);
6091 #ifdef _WIN32
6092 if (ret == 0 && timeout > 0) {
6093 int err;
6094 WaitObjects *w = &wait_objects;
6096 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6097 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6098 if (w->func[ret - WAIT_OBJECT_0])
6099 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6100 } else if (ret == WAIT_TIMEOUT) {
6101 } else {
6102 err = GetLastError();
6103 fprintf(stderr, "Wait error %d %d\n", ret, err);
6106 #endif
6107 /* poll any events */
6108 /* XXX: separate device handlers from system ones */
6109 nfds = -1;
6110 FD_ZERO(&rfds);
6111 FD_ZERO(&wfds);
6112 FD_ZERO(&xfds);
6113 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6114 if (ioh->fd_read &&
6115 (!ioh->fd_read_poll ||
6116 ioh->fd_read_poll(ioh->opaque) != 0)) {
6117 FD_SET(ioh->fd, &rfds);
6118 if (ioh->fd > nfds)
6119 nfds = ioh->fd;
6121 if (ioh->fd_write) {
6122 FD_SET(ioh->fd, &wfds);
6123 if (ioh->fd > nfds)
6124 nfds = ioh->fd;
6128 tv.tv_sec = 0;
6129 #ifdef _WIN32
6130 tv.tv_usec = 0;
6131 #else
6132 tv.tv_usec = timeout * 1000;
6133 #endif
6134 #if defined(CONFIG_SLIRP)
6135 if (slirp_inited) {
6136 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6138 #endif
6139 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6140 if (ret > 0) {
6141 /* XXX: better handling of removal */
6142 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
6143 ioh_next = ioh->next;
6144 if (FD_ISSET(ioh->fd, &rfds)) {
6145 ioh->fd_read(ioh->opaque);
6147 if (FD_ISSET(ioh->fd, &wfds)) {
6148 ioh->fd_write(ioh->opaque);
6152 #if defined(CONFIG_SLIRP)
6153 if (slirp_inited) {
6154 if (ret < 0) {
6155 FD_ZERO(&rfds);
6156 FD_ZERO(&wfds);
6157 FD_ZERO(&xfds);
6159 slirp_select_poll(&rfds, &wfds, &xfds);
6161 #endif
6162 qemu_aio_poll();
6163 qemu_bh_poll();
6165 if (vm_running) {
6166 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6167 qemu_get_clock(vm_clock));
6168 /* run dma transfers, if any */
6169 DMA_run();
6172 /* real time timers */
6173 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6174 qemu_get_clock(rt_clock));
6177 static CPUState *cur_cpu;
6179 int main_loop(void)
6181 int ret, timeout;
6182 #ifdef CONFIG_PROFILER
6183 int64_t ti;
6184 #endif
6185 CPUState *env;
6187 cur_cpu = first_cpu;
6188 for(;;) {
6189 if (vm_running) {
6191 env = cur_cpu;
6192 for(;;) {
6193 /* get next cpu */
6194 env = env->next_cpu;
6195 if (!env)
6196 env = first_cpu;
6197 #ifdef CONFIG_PROFILER
6198 ti = profile_getclock();
6199 #endif
6200 ret = cpu_exec(env);
6201 #ifdef CONFIG_PROFILER
6202 qemu_time += profile_getclock() - ti;
6203 #endif
6204 if (ret != EXCP_HALTED)
6205 break;
6206 /* all CPUs are halted ? */
6207 if (env == cur_cpu) {
6208 ret = EXCP_HLT;
6209 break;
6212 cur_cpu = env;
6214 if (shutdown_requested) {
6215 ret = EXCP_INTERRUPT;
6216 break;
6218 if (reset_requested) {
6219 reset_requested = 0;
6220 qemu_system_reset();
6221 ret = EXCP_INTERRUPT;
6223 if (powerdown_requested) {
6224 powerdown_requested = 0;
6225 qemu_system_powerdown();
6226 ret = EXCP_INTERRUPT;
6228 if (ret == EXCP_DEBUG) {
6229 vm_stop(EXCP_DEBUG);
6231 /* if hlt instruction, we wait until the next IRQ */
6232 /* XXX: use timeout computed from timers */
6233 if (ret == EXCP_HLT)
6234 timeout = 10;
6235 else
6236 timeout = 0;
6237 } else {
6238 timeout = 10;
6240 #ifdef CONFIG_PROFILER
6241 ti = profile_getclock();
6242 #endif
6243 main_loop_wait(timeout);
6244 #ifdef CONFIG_PROFILER
6245 dev_time += profile_getclock() - ti;
6246 #endif
6248 cpu_disable_ticks();
6249 return ret;
6252 void help(void)
6254 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6255 "usage: %s [options] [disk_image]\n"
6256 "\n"
6257 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6258 "\n"
6259 "Standard options:\n"
6260 "-M machine select emulated machine (-M ? for list)\n"
6261 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6262 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6263 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6264 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6265 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6266 "-disk ide,img=file[,hdx=a..dd][,type=disk|cdrom] \n"
6267 " defaults are: hdx=a,type=disk \n"
6268 "-disk scsi,img=file[,sdx=a..g][,type=disk|cdrom][,id=n] \n"
6269 " defaults are: sdx=a,type=disk,id='auto assign' \n"
6270 "-snapshot write to temporary files instead of disk image files\n"
6271 #ifdef CONFIG_SDL
6272 "-no-quit disable SDL window close capability\n"
6273 #endif
6274 #ifdef TARGET_I386
6275 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6276 #endif
6277 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6278 "-smp n set the number of CPUs to 'n' [default=1]\n"
6279 "-nographic disable graphical output and redirect serial I/Os to console\n"
6280 #ifndef _WIN32
6281 "-k language use keyboard layout (for example \"fr\" for French)\n"
6282 #endif
6283 #ifdef HAS_AUDIO
6284 "-audio-help print list of audio drivers and their options\n"
6285 "-soundhw c1,... enable audio support\n"
6286 " and only specified sound cards (comma separated list)\n"
6287 " use -soundhw ? to get the list of supported cards\n"
6288 " use -soundhw all to enable all of them\n"
6289 #endif
6290 "-localtime set the real time clock to local time [default=utc]\n"
6291 "-full-screen start in full screen\n"
6292 #ifdef TARGET_I386
6293 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6294 #endif
6295 "-usb enable the USB driver (will be the default soon)\n"
6296 "-usbdevice name add the host or guest USB device 'name'\n"
6297 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6298 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6299 #endif
6300 "\n"
6301 "Network options:\n"
6302 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6303 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6304 #ifdef CONFIG_SLIRP
6305 "-net user[,vlan=n][,hostname=host]\n"
6306 " connect the user mode network stack to VLAN 'n' and send\n"
6307 " hostname 'host' to DHCP clients\n"
6308 #endif
6309 #ifdef _WIN32
6310 "-net tap[,vlan=n],ifname=name\n"
6311 " connect the host TAP network interface to VLAN 'n'\n"
6312 #else
6313 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6314 " connect the host TAP network interface to VLAN 'n' and use\n"
6315 " the network script 'file' (default=%s);\n"
6316 " use 'fd=h' to connect to an already opened TAP interface\n"
6317 #endif
6318 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6319 " connect the vlan 'n' to another VLAN using a socket connection\n"
6320 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6321 " connect the vlan 'n' to multicast maddr and port\n"
6322 "-net none use it alone to have zero network devices; if no -net option\n"
6323 " is provided, the default is '-net nic -net user'\n"
6324 "\n"
6325 #ifdef CONFIG_SLIRP
6326 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6327 #ifndef _WIN32
6328 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6329 #endif
6330 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6331 " redirect TCP or UDP connections from host to guest [-net user]\n"
6332 #endif
6333 "\n"
6334 "Linux boot specific:\n"
6335 "-kernel bzImage use 'bzImage' as kernel image\n"
6336 "-append cmdline use 'cmdline' as kernel command line\n"
6337 "-initrd file use 'file' as initial ram disk\n"
6338 "\n"
6339 "Debug/Expert options:\n"
6340 "-monitor dev redirect the monitor to char device 'dev'\n"
6341 "-serial dev redirect the serial port to char device 'dev'\n"
6342 "-parallel dev redirect the parallel port to char device 'dev'\n"
6343 "-pidfile file Write PID to 'file'\n"
6344 "-S freeze CPU at startup (use 'c' to start execution)\n"
6345 "-s wait gdb connection to port %d\n"
6346 "-p port change gdb connection port\n"
6347 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6348 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6349 " translation (t=none or lba) (usually qemu can guess them)\n"
6350 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6351 #ifdef USE_KQEMU
6352 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6353 "-no-kqemu disable KQEMU kernel module usage\n"
6354 #endif
6355 #ifdef USE_CODE_COPY
6356 "-no-code-copy disable code copy acceleration\n"
6357 #endif
6358 #ifdef TARGET_I386
6359 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6360 " (default is CL-GD5446 PCI VGA)\n"
6361 "-no-acpi disable ACPI\n"
6362 #endif
6363 "-no-reboot exit instead of rebooting\n"
6364 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6365 "-vnc display start a VNC server on display\n"
6366 #ifndef _WIN32
6367 "-daemonize daemonize QEMU after initializing\n"
6368 #endif
6369 "-option-rom rom load a file, rom, into the option ROM space\n"
6370 "\n"
6371 "During emulation, the following keys are useful:\n"
6372 "ctrl-alt-f toggle full screen\n"
6373 "ctrl-alt-n switch to virtual console 'n'\n"
6374 "ctrl-alt toggle mouse and keyboard grab\n"
6375 "\n"
6376 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6378 "qemu",
6379 DEFAULT_RAM_SIZE,
6380 #ifndef _WIN32
6381 DEFAULT_NETWORK_SCRIPT,
6382 #endif
6383 DEFAULT_GDBSTUB_PORT,
6384 "/tmp/qemu.log");
6385 exit(1);
6388 #define HAS_ARG 0x0001
6390 enum {
6391 QEMU_OPTION_h,
6393 QEMU_OPTION_M,
6394 QEMU_OPTION_fda,
6395 QEMU_OPTION_fdb,
6396 QEMU_OPTION_hda,
6397 QEMU_OPTION_hdb,
6398 QEMU_OPTION_hdc,
6399 QEMU_OPTION_hdd,
6400 QEMU_OPTION_cdrom,
6401 QEMU_OPTION_boot,
6402 QEMU_OPTION_snapshot,
6403 #ifdef TARGET_I386
6404 QEMU_OPTION_no_fd_bootchk,
6405 #endif
6406 QEMU_OPTION_m,
6407 QEMU_OPTION_nographic,
6408 #ifdef HAS_AUDIO
6409 QEMU_OPTION_audio_help,
6410 QEMU_OPTION_soundhw,
6411 #endif
6413 QEMU_OPTION_net,
6414 QEMU_OPTION_tftp,
6415 QEMU_OPTION_smb,
6416 QEMU_OPTION_redir,
6418 QEMU_OPTION_kernel,
6419 QEMU_OPTION_append,
6420 QEMU_OPTION_initrd,
6422 QEMU_OPTION_S,
6423 QEMU_OPTION_s,
6424 QEMU_OPTION_p,
6425 QEMU_OPTION_d,
6426 QEMU_OPTION_hdachs,
6427 QEMU_OPTION_L,
6428 QEMU_OPTION_no_code_copy,
6429 QEMU_OPTION_k,
6430 QEMU_OPTION_localtime,
6431 QEMU_OPTION_cirrusvga,
6432 QEMU_OPTION_g,
6433 QEMU_OPTION_std_vga,
6434 QEMU_OPTION_monitor,
6435 QEMU_OPTION_serial,
6436 QEMU_OPTION_parallel,
6437 QEMU_OPTION_loadvm,
6438 QEMU_OPTION_full_screen,
6439 QEMU_OPTION_no_quit,
6440 QEMU_OPTION_pidfile,
6441 QEMU_OPTION_no_kqemu,
6442 QEMU_OPTION_kernel_kqemu,
6443 QEMU_OPTION_win2k_hack,
6444 QEMU_OPTION_usb,
6445 QEMU_OPTION_usbdevice,
6446 QEMU_OPTION_smp,
6447 QEMU_OPTION_vnc,
6448 QEMU_OPTION_no_acpi,
6449 QEMU_OPTION_no_reboot,
6450 QEMU_OPTION_daemonize,
6451 QEMU_OPTION_disk,
6452 QEMU_OPTION_option_rom,
6455 typedef struct QEMUOption {
6456 const char *name;
6457 int flags;
6458 int index;
6459 } QEMUOption;
6461 const QEMUOption qemu_options[] = {
6462 { "h", 0, QEMU_OPTION_h },
6464 { "M", HAS_ARG, QEMU_OPTION_M },
6465 { "fda", HAS_ARG, QEMU_OPTION_fda },
6466 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6467 { "hda", HAS_ARG, QEMU_OPTION_hda },
6468 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6469 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6470 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6471 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6472 { "boot", HAS_ARG, QEMU_OPTION_boot },
6473 { "snapshot", 0, QEMU_OPTION_snapshot },
6474 #ifdef TARGET_I386
6475 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6476 #endif
6477 { "m", HAS_ARG, QEMU_OPTION_m },
6478 { "nographic", 0, QEMU_OPTION_nographic },
6479 { "k", HAS_ARG, QEMU_OPTION_k },
6480 #ifdef HAS_AUDIO
6481 { "audio-help", 0, QEMU_OPTION_audio_help },
6482 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6483 #endif
6485 { "net", HAS_ARG, QEMU_OPTION_net},
6486 #ifdef CONFIG_SLIRP
6487 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6488 #ifndef _WIN32
6489 { "smb", HAS_ARG, QEMU_OPTION_smb },
6490 #endif
6491 { "redir", HAS_ARG, QEMU_OPTION_redir },
6492 #endif
6494 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6495 { "append", HAS_ARG, QEMU_OPTION_append },
6496 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6498 { "S", 0, QEMU_OPTION_S },
6499 { "s", 0, QEMU_OPTION_s },
6500 { "p", HAS_ARG, QEMU_OPTION_p },
6501 { "d", HAS_ARG, QEMU_OPTION_d },
6502 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6503 { "L", HAS_ARG, QEMU_OPTION_L },
6504 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6505 #ifdef USE_KQEMU
6506 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6507 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6508 #endif
6509 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6510 { "g", 1, QEMU_OPTION_g },
6511 #endif
6512 { "localtime", 0, QEMU_OPTION_localtime },
6513 { "std-vga", 0, QEMU_OPTION_std_vga },
6514 { "monitor", 1, QEMU_OPTION_monitor },
6515 { "serial", 1, QEMU_OPTION_serial },
6516 { "parallel", 1, QEMU_OPTION_parallel },
6517 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6518 { "full-screen", 0, QEMU_OPTION_full_screen },
6519 #ifdef CONFIG_SDL
6520 { "no-quit", 0, QEMU_OPTION_no_quit },
6521 #endif
6522 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6523 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6524 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6525 { "smp", HAS_ARG, QEMU_OPTION_smp },
6526 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6527 { "disk", HAS_ARG, QEMU_OPTION_disk },
6529 /* temporary options */
6530 { "usb", 0, QEMU_OPTION_usb },
6531 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6532 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6533 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6534 { "daemonize", 0, QEMU_OPTION_daemonize },
6535 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6536 { NULL },
6539 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6541 /* this stack is only used during signal handling */
6542 #define SIGNAL_STACK_SIZE 32768
6544 static uint8_t *signal_stack;
6546 #endif
6548 /* password input */
6550 static BlockDriverState *get_bdrv(int index)
6552 BlockDriverState *bs;
6554 if (index < 4) {
6555 bs = bs_table[index];
6556 } else if (index < 6) {
6557 bs = fd_table[index - 4];
6558 } else {
6559 bs = NULL;
6561 return bs;
6564 static void read_passwords(void)
6566 BlockDriverState *bs;
6567 int i, j;
6568 char password[256];
6570 for(i = 0; i < 6; i++) {
6571 bs = get_bdrv(i);
6572 if (bs && bdrv_is_encrypted(bs)) {
6573 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6574 for(j = 0; j < 3; j++) {
6575 monitor_readline("Password: ",
6576 1, password, sizeof(password));
6577 if (bdrv_set_key(bs, password) == 0)
6578 break;
6579 term_printf("invalid password\n");
6585 /* XXX: currently we cannot use simultaneously different CPUs */
6586 void register_machines(void)
6588 #if defined(TARGET_I386)
6589 qemu_register_machine(&pc_machine);
6590 qemu_register_machine(&isapc_machine);
6591 #elif defined(TARGET_PPC)
6592 qemu_register_machine(&heathrow_machine);
6593 qemu_register_machine(&core99_machine);
6594 qemu_register_machine(&prep_machine);
6595 #elif defined(TARGET_MIPS)
6596 qemu_register_machine(&mips_machine);
6597 #elif defined(TARGET_SPARC)
6598 #ifdef TARGET_SPARC64
6599 qemu_register_machine(&sun4u_machine);
6600 #else
6601 qemu_register_machine(&sun4m_machine);
6602 #endif
6603 #elif defined(TARGET_ARM)
6604 qemu_register_machine(&integratorcp926_machine);
6605 qemu_register_machine(&integratorcp1026_machine);
6606 qemu_register_machine(&versatilepb_machine);
6607 qemu_register_machine(&versatileab_machine);
6608 qemu_register_machine(&realview_machine);
6609 #elif defined(TARGET_SH4)
6610 qemu_register_machine(&shix_machine);
6611 #else
6612 #error unsupported CPU
6613 #endif
6616 #ifdef HAS_AUDIO
6617 struct soundhw soundhw[] = {
6618 #ifdef TARGET_I386
6620 "pcspk",
6621 "PC speaker",
6624 { .init_isa = pcspk_audio_init }
6626 #endif
6628 "sb16",
6629 "Creative Sound Blaster 16",
6632 { .init_isa = SB16_init }
6635 #ifdef CONFIG_ADLIB
6637 "adlib",
6638 #ifdef HAS_YMF262
6639 "Yamaha YMF262 (OPL3)",
6640 #else
6641 "Yamaha YM3812 (OPL2)",
6642 #endif
6645 { .init_isa = Adlib_init }
6647 #endif
6649 #ifdef CONFIG_GUS
6651 "gus",
6652 "Gravis Ultrasound GF1",
6655 { .init_isa = GUS_init }
6657 #endif
6660 "es1370",
6661 "ENSONIQ AudioPCI ES1370",
6664 { .init_pci = es1370_init }
6667 { NULL, NULL, 0, 0, { NULL } }
6670 static void select_soundhw (const char *optarg)
6672 struct soundhw *c;
6674 if (*optarg == '?') {
6675 show_valid_cards:
6677 printf ("Valid sound card names (comma separated):\n");
6678 for (c = soundhw; c->name; ++c) {
6679 printf ("%-11s %s\n", c->name, c->descr);
6681 printf ("\n-soundhw all will enable all of the above\n");
6682 exit (*optarg != '?');
6684 else {
6685 size_t l;
6686 const char *p;
6687 char *e;
6688 int bad_card = 0;
6690 if (!strcmp (optarg, "all")) {
6691 for (c = soundhw; c->name; ++c) {
6692 c->enabled = 1;
6694 return;
6697 p = optarg;
6698 while (*p) {
6699 e = strchr (p, ',');
6700 l = !e ? strlen (p) : (size_t) (e - p);
6702 for (c = soundhw; c->name; ++c) {
6703 if (!strncmp (c->name, p, l)) {
6704 c->enabled = 1;
6705 break;
6709 if (!c->name) {
6710 if (l > 80) {
6711 fprintf (stderr,
6712 "Unknown sound card name (too big to show)\n");
6714 else {
6715 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6716 (int) l, p);
6718 bad_card = 1;
6720 p += l + (e != NULL);
6723 if (bad_card)
6724 goto show_valid_cards;
6727 #endif
6729 #ifdef _WIN32
6730 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6732 exit(STATUS_CONTROL_C_EXIT);
6733 return TRUE;
6735 #endif
6737 #define MAX_NET_CLIENTS 32
6739 int main(int argc, char **argv)
6741 #ifdef CONFIG_GDBSTUB
6742 int use_gdbstub, gdbstub_port;
6743 #endif
6744 int i, cdrom_index;
6745 int snapshot, linux_boot;
6746 const char *initrd_filename;
6747 const char *fd_filename[MAX_FD];
6748 char scsi_options[MAX_SCSI_DISKS] [DISK_OPTIONS_SIZE];
6749 char ide_options[MAX_DISKS] [DISK_OPTIONS_SIZE];
6750 int num_ide_disks;
6751 int num_scsi_disks;
6752 const char *kernel_filename, *kernel_cmdline;
6753 DisplayState *ds = &display_state;
6754 int cyls, heads, secs, translation;
6755 int start_emulation = 1;
6756 char net_clients[MAX_NET_CLIENTS][256];
6757 int nb_net_clients;
6758 int optind;
6759 const char *r, *optarg;
6760 CharDriverState *monitor_hd;
6761 char monitor_device[128];
6762 char serial_devices[MAX_SERIAL_PORTS][128];
6763 int serial_device_index;
6764 char parallel_devices[MAX_PARALLEL_PORTS][128];
6765 int parallel_device_index;
6766 const char *loadvm = NULL;
6767 QEMUMachine *machine;
6768 char usb_devices[MAX_USB_CMDLINE][128];
6769 int usb_devices_index;
6770 int fds[2];
6772 LIST_INIT (&vm_change_state_head);
6773 #ifndef _WIN32
6775 struct sigaction act;
6776 sigfillset(&act.sa_mask);
6777 act.sa_flags = 0;
6778 act.sa_handler = SIG_IGN;
6779 sigaction(SIGPIPE, &act, NULL);
6781 #else
6782 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6783 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6784 QEMU to run on a single CPU */
6786 HANDLE h;
6787 DWORD mask, smask;
6788 int i;
6789 h = GetCurrentProcess();
6790 if (GetProcessAffinityMask(h, &mask, &smask)) {
6791 for(i = 0; i < 32; i++) {
6792 if (mask & (1 << i))
6793 break;
6795 if (i != 32) {
6796 mask = 1 << i;
6797 SetProcessAffinityMask(h, mask);
6801 #endif
6803 register_machines();
6804 machine = first_machine;
6805 initrd_filename = NULL;
6806 for(i = 0; i < MAX_SCSI_DISKS; i++) {
6807 scsi_disks_info[i].device_type = SCSI_NONE;
6808 bs_scsi_table[i] = NULL;
6811 num_ide_disks = 0;
6812 num_scsi_disks = 0;
6814 for(i = 0; i < MAX_FD; i++)
6815 fd_filename[i] = NULL;
6816 for(i = 0; i < MAX_DISKS; i++) {
6817 ide_options[i][0] = '\0';
6819 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6820 vga_ram_size = VGA_RAM_SIZE;
6821 bios_size = BIOS_SIZE;
6822 #ifdef CONFIG_GDBSTUB
6823 use_gdbstub = 0;
6824 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6825 #endif
6826 snapshot = 0;
6827 nographic = 0;
6828 kernel_filename = NULL;
6829 kernel_cmdline = "";
6830 #ifdef TARGET_PPC
6831 cdrom_index = 1;
6832 #else
6833 cdrom_index = 2;
6834 #endif
6835 cyls = heads = secs = 0;
6836 translation = BIOS_ATA_TRANSLATION_AUTO;
6837 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6839 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6840 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6841 serial_devices[i][0] = '\0';
6842 serial_device_index = 0;
6844 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6845 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6846 parallel_devices[i][0] = '\0';
6847 parallel_device_index = 0;
6849 usb_devices_index = 0;
6851 nb_net_clients = 0;
6853 nb_nics = 0;
6854 /* default mac address of the first network interface */
6856 optind = 1;
6857 for(;;) {
6858 if (optind >= argc)
6859 break;
6860 r = argv[optind];
6861 if (r[0] != '-') {
6863 /* Build new disk IDE syntax string */
6864 pstrcpy(ide_options[0],
6866 "hdx=a,img=");
6867 /*Add on image filename */
6868 pstrcpy(&(ide_options[0][13]),
6869 sizeof(ide_options[0])-13,
6870 argv[optind++]);
6871 num_ide_disks++;
6872 } else {
6873 const QEMUOption *popt;
6875 optind++;
6876 popt = qemu_options;
6877 for(;;) {
6878 if (!popt->name) {
6879 fprintf(stderr, "%s: invalid option -- '%s'\n",
6880 argv[0], r);
6881 exit(1);
6883 if (!strcmp(popt->name, r + 1))
6884 break;
6885 popt++;
6887 if (popt->flags & HAS_ARG) {
6888 if (optind >= argc) {
6889 fprintf(stderr, "%s: option '%s' requires an argument\n",
6890 argv[0], r);
6891 exit(1);
6893 optarg = argv[optind++];
6894 } else {
6895 optarg = NULL;
6898 switch(popt->index) {
6899 case QEMU_OPTION_M:
6900 machine = find_machine(optarg);
6901 if (!machine) {
6902 QEMUMachine *m;
6903 printf("Supported machines are:\n");
6904 for(m = first_machine; m != NULL; m = m->next) {
6905 printf("%-10s %s%s\n",
6906 m->name, m->desc,
6907 m == first_machine ? " (default)" : "");
6909 exit(1);
6911 break;
6912 case QEMU_OPTION_initrd:
6913 initrd_filename = optarg;
6914 break;
6915 case QEMU_OPTION_hda:
6916 case QEMU_OPTION_hdb:
6917 case QEMU_OPTION_hdc:
6918 case QEMU_OPTION_hdd:
6920 int hd_index;
6921 const char newIDE_DiskSyntax [][10] = {
6922 "hdx=a,img=", "hdx=b,img=", "hdx=c,img=", "hdx=d,img=" };
6924 hd_index = popt->index - QEMU_OPTION_hda;
6925 if (num_ide_disks >= MAX_DISKS) {
6926 fprintf(stderr, "qemu: too many IDE disks defined.\n");
6927 exit(1);
6929 /* Build new disk IDE syntax string */
6930 pstrcpy(ide_options[hd_index],
6932 newIDE_DiskSyntax[hd_index]);
6933 /* Add on image filename */
6934 pstrcpy(&(ide_options[hd_index][10]),
6935 sizeof(ide_options[0])-10,
6936 optarg);
6937 num_ide_disks++;
6939 break;
6940 case QEMU_OPTION_disk: /*Combined IDE and SCSI, for disk and CDROM */
6942 const char *p_input_char;
6943 char *p_output_string;
6944 char device[64];
6945 int disk_index;
6947 p_input_char = optarg;
6948 p_output_string = device;
6949 while (*p_input_char != '\0' && *p_input_char != ',') {
6950 if ((p_output_string - device) < sizeof(device) - 1)
6951 *p_output_string++ = *p_input_char;
6952 p_input_char++;
6954 *p_output_string = '\0';
6955 if (*p_input_char == ',')
6956 p_input_char++;
6958 if (!strcmp(device, "scsi")) {
6959 if (num_scsi_disks >= MAX_SCSI_DISKS) {
6960 fprintf(stderr, "qemu: too many SCSI disks defined.\n");
6961 exit(1);
6963 pstrcpy(scsi_options[num_scsi_disks],
6964 sizeof(scsi_options[0]),
6965 p_input_char);
6966 num_scsi_disks++;
6967 } else if (!strcmp(device,"ide")) {
6968 if (num_ide_disks >= MAX_DISKS) {
6969 fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6970 exit(1);
6972 disk_index = 0; /* default is hda */
6973 if (get_param_value(device, sizeof(device),"hdx",p_input_char)) {
6974 if (device[0] >= 'a' && device[0] <= 'd') {
6975 disk_index = device[0] - 'a';
6976 } else {
6977 fprintf(stderr, "qemu: invalid IDE disk hdx= value: %s\n", device);
6978 return -1;
6981 else disk_index=0;
6982 pstrcpy(ide_options[disk_index],
6983 sizeof(ide_options[0]),
6984 p_input_char);
6985 num_ide_disks++;
6986 } else {
6987 fprintf(stderr, "qemu: -disk option must specify IDE or SCSI: %s \n",device);
6988 exit(1);
6991 break;
6992 case QEMU_OPTION_snapshot:
6993 snapshot = 1;
6994 break;
6995 case QEMU_OPTION_hdachs:
6997 const char *p;
6998 p = optarg;
6999 cyls = strtol(p, (char **)&p, 0);
7000 if (cyls < 1 || cyls > 16383)
7001 goto chs_fail;
7002 if (*p != ',')
7003 goto chs_fail;
7004 p++;
7005 heads = strtol(p, (char **)&p, 0);
7006 if (heads < 1 || heads > 16)
7007 goto chs_fail;
7008 if (*p != ',')
7009 goto chs_fail;
7010 p++;
7011 secs = strtol(p, (char **)&p, 0);
7012 if (secs < 1 || secs > 63)
7013 goto chs_fail;
7014 if (*p == ',') {
7015 p++;
7016 if (!strcmp(p, "none"))
7017 translation = BIOS_ATA_TRANSLATION_NONE;
7018 else if (!strcmp(p, "lba"))
7019 translation = BIOS_ATA_TRANSLATION_LBA;
7020 else if (!strcmp(p, "auto"))
7021 translation = BIOS_ATA_TRANSLATION_AUTO;
7022 else
7023 goto chs_fail;
7024 } else if (*p != '\0') {
7025 chs_fail:
7026 fprintf(stderr, "qemu: invalid physical CHS format\n");
7027 exit(1);
7030 break;
7031 case QEMU_OPTION_nographic:
7032 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7033 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7034 nographic = 1;
7035 break;
7036 case QEMU_OPTION_kernel:
7037 kernel_filename = optarg;
7038 break;
7039 case QEMU_OPTION_append:
7040 kernel_cmdline = optarg;
7041 break;
7042 case QEMU_OPTION_cdrom:
7043 #if !defined(TARGET_SPARC) || defined(TARGET_SPARC64)
7044 /* Assume boot cdrom is IDE */
7046 char buf[22];
7047 if (num_ide_disks >= MAX_DISKS) {
7048 fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
7049 exit(1);
7051 snprintf(buf, sizeof(buf), "type=cdrom,hdx=%c,img=", cdrom_index + 'a');
7052 /* Build new disk IDE syntax string */
7053 pstrcpy(ide_options[cdrom_index],
7055 buf);
7056 /* Add on image filename */
7057 pstrcpy(&(ide_options[cdrom_index][21]),
7058 sizeof(ide_options[0])-21,
7059 optarg);
7060 num_ide_disks++;
7062 #else
7063 /* Assume boot cdrom is SCSI */
7065 char buf[27];
7066 if (num_scsi_disks >= MAX_SCSI_DISKS) {
7067 fprintf(stderr, "qemu: too many SCSI disks/cdroms defined.\n");
7068 exit(1);
7070 snprintf(buf, sizeof(buf), "type=cdrom,sdx=%c,id=%d,img=",
7071 num_scsi_disks + 'a', num_scsi_disks + 2);
7072 /* Build new disk SCSI syntax string */
7073 pstrcpy(scsi_options[num_scsi_disks],
7075 buf);
7076 /* Add on image filename */
7077 pstrcpy(&(scsi_options[num_scsi_disks][26]),
7078 sizeof(scsi_options[0])-26,
7079 optarg);
7080 num_scsi_disks++;
7082 #endif
7083 break;
7084 case QEMU_OPTION_boot:
7085 boot_device = optarg[0];
7086 if (boot_device != 'a' &&
7087 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7088 // Network boot
7089 boot_device != 'n' &&
7090 #endif
7091 boot_device != 'c' && boot_device != 'd') {
7092 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7093 exit(1);
7095 break;
7096 case QEMU_OPTION_fda:
7097 fd_filename[0] = optarg;
7098 break;
7099 case QEMU_OPTION_fdb:
7100 fd_filename[1] = optarg;
7101 break;
7102 #ifdef TARGET_I386
7103 case QEMU_OPTION_no_fd_bootchk:
7104 fd_bootchk = 0;
7105 break;
7106 #endif
7107 case QEMU_OPTION_no_code_copy:
7108 code_copy_enabled = 0;
7109 break;
7110 case QEMU_OPTION_net:
7111 if (nb_net_clients >= MAX_NET_CLIENTS) {
7112 fprintf(stderr, "qemu: too many network clients\n");
7113 exit(1);
7115 pstrcpy(net_clients[nb_net_clients],
7116 sizeof(net_clients[0]),
7117 optarg);
7118 nb_net_clients++;
7119 break;
7120 #ifdef CONFIG_SLIRP
7121 case QEMU_OPTION_tftp:
7122 tftp_prefix = optarg;
7123 break;
7124 #ifndef _WIN32
7125 case QEMU_OPTION_smb:
7126 net_slirp_smb(optarg);
7127 break;
7128 #endif
7129 case QEMU_OPTION_redir:
7130 net_slirp_redir(optarg);
7131 break;
7132 #endif
7133 #ifdef HAS_AUDIO
7134 case QEMU_OPTION_audio_help:
7135 AUD_help ();
7136 exit (0);
7137 break;
7138 case QEMU_OPTION_soundhw:
7139 select_soundhw (optarg);
7140 break;
7141 #endif
7142 case QEMU_OPTION_h:
7143 help();
7144 break;
7145 case QEMU_OPTION_m:
7146 ram_size = atoi(optarg) * 1024 * 1024;
7147 if (ram_size <= 0)
7148 help();
7149 if (ram_size > PHYS_RAM_MAX_SIZE) {
7150 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7151 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7152 exit(1);
7154 break;
7155 case QEMU_OPTION_d:
7157 int mask;
7158 CPULogItem *item;
7160 mask = cpu_str_to_log_mask(optarg);
7161 if (!mask) {
7162 printf("Log items (comma separated):\n");
7163 for(item = cpu_log_items; item->mask != 0; item++) {
7164 printf("%-10s %s\n", item->name, item->help);
7166 exit(1);
7168 cpu_set_log(mask);
7170 break;
7171 #ifdef CONFIG_GDBSTUB
7172 case QEMU_OPTION_s:
7173 use_gdbstub = 1;
7174 break;
7175 case QEMU_OPTION_p:
7176 gdbstub_port = atoi(optarg);
7177 break;
7178 #endif
7179 case QEMU_OPTION_L:
7180 bios_dir = optarg;
7181 break;
7182 case QEMU_OPTION_S:
7183 start_emulation = 0;
7184 break;
7185 case QEMU_OPTION_k:
7186 keyboard_layout = optarg;
7187 break;
7188 case QEMU_OPTION_localtime:
7189 rtc_utc = 0;
7190 break;
7191 case QEMU_OPTION_cirrusvga:
7192 cirrus_vga_enabled = 1;
7193 break;
7194 case QEMU_OPTION_std_vga:
7195 cirrus_vga_enabled = 0;
7196 break;
7197 case QEMU_OPTION_g:
7199 const char *p;
7200 int w, h, depth;
7201 p = optarg;
7202 w = strtol(p, (char **)&p, 10);
7203 if (w <= 0) {
7204 graphic_error:
7205 fprintf(stderr, "qemu: invalid resolution or depth\n");
7206 exit(1);
7208 if (*p != 'x')
7209 goto graphic_error;
7210 p++;
7211 h = strtol(p, (char **)&p, 10);
7212 if (h <= 0)
7213 goto graphic_error;
7214 if (*p == 'x') {
7215 p++;
7216 depth = strtol(p, (char **)&p, 10);
7217 if (depth != 8 && depth != 15 && depth != 16 &&
7218 depth != 24 && depth != 32)
7219 goto graphic_error;
7220 } else if (*p == '\0') {
7221 depth = graphic_depth;
7222 } else {
7223 goto graphic_error;
7226 graphic_width = w;
7227 graphic_height = h;
7228 graphic_depth = depth;
7230 break;
7231 case QEMU_OPTION_monitor:
7232 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7233 break;
7234 case QEMU_OPTION_serial:
7235 if (serial_device_index >= MAX_SERIAL_PORTS) {
7236 fprintf(stderr, "qemu: too many serial ports\n");
7237 exit(1);
7239 pstrcpy(serial_devices[serial_device_index],
7240 sizeof(serial_devices[0]), optarg);
7241 serial_device_index++;
7242 break;
7243 case QEMU_OPTION_parallel:
7244 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7245 fprintf(stderr, "qemu: too many parallel ports\n");
7246 exit(1);
7248 pstrcpy(parallel_devices[parallel_device_index],
7249 sizeof(parallel_devices[0]), optarg);
7250 parallel_device_index++;
7251 break;
7252 case QEMU_OPTION_loadvm:
7253 loadvm = optarg;
7254 break;
7255 case QEMU_OPTION_full_screen:
7256 full_screen = 1;
7257 break;
7258 #ifdef CONFIG_SDL
7259 case QEMU_OPTION_no_quit:
7260 no_quit = 1;
7261 break;
7262 #endif
7263 case QEMU_OPTION_pidfile:
7264 create_pidfile(optarg);
7265 break;
7266 #ifdef TARGET_I386
7267 case QEMU_OPTION_win2k_hack:
7268 win2k_install_hack = 1;
7269 break;
7270 #endif
7271 #ifdef USE_KQEMU
7272 case QEMU_OPTION_no_kqemu:
7273 kqemu_allowed = 0;
7274 break;
7275 case QEMU_OPTION_kernel_kqemu:
7276 kqemu_allowed = 2;
7277 break;
7278 #endif
7279 case QEMU_OPTION_usb:
7280 usb_enabled = 1;
7281 break;
7282 case QEMU_OPTION_usbdevice:
7283 usb_enabled = 1;
7284 if (usb_devices_index >= MAX_USB_CMDLINE) {
7285 fprintf(stderr, "Too many USB devices\n");
7286 exit(1);
7288 pstrcpy(usb_devices[usb_devices_index],
7289 sizeof(usb_devices[usb_devices_index]),
7290 optarg);
7291 usb_devices_index++;
7292 break;
7293 case QEMU_OPTION_smp:
7294 smp_cpus = atoi(optarg);
7295 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7296 fprintf(stderr, "Invalid number of CPUs\n");
7297 exit(1);
7299 break;
7300 case QEMU_OPTION_vnc:
7301 vnc_display = optarg;
7302 break;
7303 case QEMU_OPTION_no_acpi:
7304 acpi_enabled = 0;
7305 break;
7306 case QEMU_OPTION_no_reboot:
7307 no_reboot = 1;
7308 break;
7309 case QEMU_OPTION_daemonize:
7310 daemonize = 1;
7311 break;
7312 case QEMU_OPTION_option_rom:
7313 if (nb_option_roms >= MAX_OPTION_ROMS) {
7314 fprintf(stderr, "Too many option ROMs\n");
7315 exit(1);
7317 option_rom[nb_option_roms] = optarg;
7318 nb_option_roms++;
7319 break;
7324 #ifndef _WIN32
7325 if (daemonize && !nographic && vnc_display == NULL) {
7326 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7327 daemonize = 0;
7330 if (daemonize) {
7331 pid_t pid;
7333 if (pipe(fds) == -1)
7334 exit(1);
7336 pid = fork();
7337 if (pid > 0) {
7338 uint8_t status;
7339 ssize_t len;
7341 close(fds[1]);
7343 again:
7344 len = read(fds[0], &status, 1);
7345 if (len == -1 && (errno == EINTR))
7346 goto again;
7348 if (len != 1 || status != 0)
7349 exit(1);
7350 else
7351 exit(0);
7352 } else if (pid < 0)
7353 exit(1);
7355 setsid();
7357 pid = fork();
7358 if (pid > 0)
7359 exit(0);
7360 else if (pid < 0)
7361 exit(1);
7363 umask(027);
7364 chdir("/");
7366 signal(SIGTSTP, SIG_IGN);
7367 signal(SIGTTOU, SIG_IGN);
7368 signal(SIGTTIN, SIG_IGN);
7370 #endif
7372 #ifdef USE_KQEMU
7373 if (smp_cpus > 1)
7374 kqemu_allowed = 0;
7375 #endif
7376 linux_boot = (kernel_filename != NULL);
7378 if (!linux_boot &&
7379 num_ide_disks == 0 &&
7380 num_scsi_disks == 0 &&
7381 fd_filename[0] == '\0')
7382 help();
7384 setvbuf(stdout, NULL, _IOLBF, 0);
7386 init_timers();
7387 init_timer_alarm();
7388 qemu_aio_init();
7390 #ifdef _WIN32
7391 socket_init();
7392 #endif
7394 /* init network clients */
7395 if (nb_net_clients == 0) {
7396 /* if no clients, we use a default config */
7397 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7398 "nic");
7399 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7400 "user");
7401 nb_net_clients = 2;
7404 for(i = 0;i < nb_net_clients; i++) {
7405 if (net_client_init(net_clients[i]) < 0)
7406 exit(1);
7409 #ifdef TARGET_I386
7410 if (boot_device == 'n') {
7411 for (i = 0; i < nb_nics; i++) {
7412 const char *model = nd_table[i].model;
7413 char buf[1024];
7414 if (model == NULL)
7415 model = "ne2k_pci";
7416 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7417 if (get_image_size(buf) > 0) {
7418 option_rom[nb_option_roms] = strdup(buf);
7419 nb_option_roms++;
7420 break;
7423 if (i == nb_nics) {
7424 fprintf(stderr, "No valid PXE rom found for network device\n");
7425 exit(1);
7427 boot_device = 'c'; /* to prevent confusion by the BIOS */
7429 #endif
7431 /* init the memory */
7432 phys_ram_size = ram_size + vga_ram_size + bios_size;
7434 for (i = 0; i < nb_option_roms; i++) {
7435 int ret = get_image_size(option_rom[i]);
7436 if (ret == -1) {
7437 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7438 exit(1);
7440 phys_ram_size += ret;
7443 phys_ram_base = qemu_vmalloc(phys_ram_size);
7444 if (!phys_ram_base) {
7445 fprintf(stderr, "Could not allocate physical memory\n");
7446 exit(1);
7449 bdrv_init();
7451 /* open the virtual block devices, disks or CDRoms */
7452 if (disk_options_init(num_ide_disks,ide_options,snapshot,
7453 num_scsi_disks,scsi_options,
7454 cdrom_index,
7455 cyls, heads, secs, translation)){
7456 exit(1);
7459 /* boot to floppy or default cd if no hard disk */
7460 if (num_ide_disks == 0 && boot_device == 'c') {
7461 if (fd_filename[0] != '\0')
7462 boot_device = 'a';
7463 else
7464 boot_device = 'd';
7467 /* we always create at least one floppy disk */
7468 fd_table[0] = bdrv_new("fda");
7469 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7471 for(i = 0; i < MAX_FD; i++) {
7472 if (fd_filename[i]) {
7473 if (!fd_table[i]) {
7474 char buf[64];
7475 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7476 fd_table[i] = bdrv_new(buf);
7477 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7479 if (fd_filename[i] != '\0') {
7480 if (bdrv_open(fd_table[i], fd_filename[i],
7481 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7482 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7483 fd_filename[i]);
7484 exit(1);
7490 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7491 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7493 init_ioports();
7495 /* terminal init */
7496 if (nographic) {
7497 dumb_display_init(ds);
7498 } else if (vnc_display != NULL) {
7499 vnc_display_init(ds, vnc_display);
7500 } else {
7501 #if defined(CONFIG_SDL)
7502 sdl_display_init(ds, full_screen);
7503 #elif defined(CONFIG_COCOA)
7504 cocoa_display_init(ds, full_screen);
7505 #else
7506 dumb_display_init(ds);
7507 #endif
7510 monitor_hd = qemu_chr_open(monitor_device);
7511 if (!monitor_hd) {
7512 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7513 exit(1);
7515 monitor_init(monitor_hd, !nographic);
7517 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7518 const char *devname = serial_devices[i];
7519 if (devname[0] != '\0' && strcmp(devname, "none")) {
7520 serial_hds[i] = qemu_chr_open(devname);
7521 if (!serial_hds[i]) {
7522 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7523 devname);
7524 exit(1);
7526 if (!strcmp(devname, "vc"))
7527 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7531 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7532 const char *devname = parallel_devices[i];
7533 if (devname[0] != '\0' && strcmp(devname, "none")) {
7534 parallel_hds[i] = qemu_chr_open(devname);
7535 if (!parallel_hds[i]) {
7536 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7537 devname);
7538 exit(1);
7540 if (!strcmp(devname, "vc"))
7541 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7545 machine->init(ram_size, vga_ram_size, boot_device,
7546 ds, fd_filename, snapshot,
7547 kernel_filename, kernel_cmdline, initrd_filename);
7549 /* init USB devices */
7550 if (usb_enabled) {
7551 for(i = 0; i < usb_devices_index; i++) {
7552 if (usb_device_add(usb_devices[i]) < 0) {
7553 fprintf(stderr, "Warning: could not add USB device %s\n",
7554 usb_devices[i]);
7559 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7560 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7562 #ifdef CONFIG_GDBSTUB
7563 if (use_gdbstub) {
7564 if (gdbserver_start(gdbstub_port) < 0) {
7565 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
7566 gdbstub_port);
7567 exit(1);
7568 } else {
7569 printf("Waiting gdb connection on port %d\n", gdbstub_port);
7571 } else
7572 #endif
7573 if (loadvm)
7574 do_loadvm(loadvm);
7577 /* XXX: simplify init */
7578 read_passwords();
7579 if (start_emulation) {
7580 vm_start();
7584 if (daemonize) {
7585 uint8_t status = 0;
7586 ssize_t len;
7587 int fd;
7589 again1:
7590 len = write(fds[1], &status, 1);
7591 if (len == -1 && (errno == EINTR))
7592 goto again1;
7594 if (len != 1)
7595 exit(1);
7597 fd = open("/dev/null", O_RDWR);
7598 if (fd == -1)
7599 exit(1);
7601 dup2(fd, 0);
7602 dup2(fd, 1);
7603 dup2(fd, 2);
7605 close(fd);
7608 main_loop();
7609 quit_timers();
7610 return 0;