Sparc64 build fix (Igor Kovalenko).
[qemu/mini2440.git] / vl.c
blobb4a03fdaebf009cb9e04d20bc02d9cfcf929f334
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"
93 //#define DEBUG_UNUSED_IOPORT
94 //#define DEBUG_IOPORT
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #ifdef TARGET_PPC
99 #define DEFAULT_RAM_SIZE 144
100 #else
101 #define DEFAULT_RAM_SIZE 128
102 #endif
103 /* in ms */
104 #define GUI_REFRESH_INTERVAL 30
106 /* Max number of USB devices that can be specified on the commandline. */
107 #define MAX_USB_CMDLINE 8
109 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
112 #define DISK_OPTIONS_SIZE 256
114 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
115 char phys_ram_file[1024];
116 void *ioport_opaque[MAX_IOPORTS];
117 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
118 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
119 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
120 to store the VM snapshots */
121 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
122 /* point to the block driver where the snapshots are managed */
123 BlockDriverState *bs_snapshots;
124 BlockDriverState *bs_scsi_table[MAX_SCSI_DISKS];
125 SCSIDiskInfo scsi_disks_info[MAX_SCSI_DISKS];
126 int scsi_hba_lsi; /* Count of scsi disks/cdrom using this lsi adapter */
127 int vga_ram_size;
128 int bios_size;
129 static DisplayState display_state;
130 int nographic;
131 const char* keyboard_layout = NULL;
132 int64_t ticks_per_sec;
133 int boot_device = 'c';
134 int ram_size;
135 int pit_min_timer_count = 0;
136 int nb_nics;
137 NICInfo nd_table[MAX_NICS];
138 QEMUTimer *gui_timer;
139 int vm_running;
140 int rtc_utc = 1;
141 int cirrus_vga_enabled = 1;
142 #ifdef TARGET_SPARC
143 int graphic_width = 1024;
144 int graphic_height = 768;
145 #else
146 int graphic_width = 800;
147 int graphic_height = 600;
148 #endif
149 int graphic_depth = 15;
150 int full_screen = 0;
151 int no_quit = 0;
152 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
153 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
154 #ifdef TARGET_I386
155 int win2k_install_hack = 0;
156 #endif
157 int usb_enabled = 0;
158 static VLANState *first_vlan;
159 int smp_cpus = 1;
160 const char *vnc_display;
161 #if defined(TARGET_SPARC)
162 #define MAX_CPUS 16
163 #elif defined(TARGET_I386)
164 #define MAX_CPUS 255
165 #else
166 #define MAX_CPUS 1
167 #endif
168 int acpi_enabled = 1;
169 int fd_bootchk = 1;
170 int no_reboot = 0;
171 int daemonize = 0;
173 /***********************************************************/
174 /* x86 ISA bus support */
176 target_phys_addr_t isa_mem_base = 0;
177 PicState2 *isa_pic;
179 uint32_t default_ioport_readb(void *opaque, uint32_t address)
181 #ifdef DEBUG_UNUSED_IOPORT
182 fprintf(stderr, "inb: port=0x%04x\n", address);
183 #endif
184 return 0xff;
187 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
189 #ifdef DEBUG_UNUSED_IOPORT
190 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
191 #endif
194 /* default is to make two byte accesses */
195 uint32_t default_ioport_readw(void *opaque, uint32_t address)
197 uint32_t data;
198 data = ioport_read_table[0][address](ioport_opaque[address], address);
199 address = (address + 1) & (MAX_IOPORTS - 1);
200 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
201 return data;
204 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
206 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
207 address = (address + 1) & (MAX_IOPORTS - 1);
208 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
211 uint32_t default_ioport_readl(void *opaque, uint32_t address)
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "inl: port=0x%04x\n", address);
215 #endif
216 return 0xffffffff;
219 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
223 #endif
226 void init_ioports(void)
228 int i;
230 for(i = 0; i < MAX_IOPORTS; i++) {
231 ioport_read_table[0][i] = default_ioport_readb;
232 ioport_write_table[0][i] = default_ioport_writeb;
233 ioport_read_table[1][i] = default_ioport_readw;
234 ioport_write_table[1][i] = default_ioport_writew;
235 ioport_read_table[2][i] = default_ioport_readl;
236 ioport_write_table[2][i] = default_ioport_writel;
240 /* size is the word size in byte */
241 int register_ioport_read(int start, int length, int size,
242 IOPortReadFunc *func, void *opaque)
244 int i, bsize;
246 if (size == 1) {
247 bsize = 0;
248 } else if (size == 2) {
249 bsize = 1;
250 } else if (size == 4) {
251 bsize = 2;
252 } else {
253 hw_error("register_ioport_read: invalid size");
254 return -1;
256 for(i = start; i < start + length; i += size) {
257 ioport_read_table[bsize][i] = func;
258 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
259 hw_error("register_ioport_read: invalid opaque");
260 ioport_opaque[i] = opaque;
262 return 0;
265 /* size is the word size in byte */
266 int register_ioport_write(int start, int length, int size,
267 IOPortWriteFunc *func, void *opaque)
269 int i, bsize;
271 if (size == 1) {
272 bsize = 0;
273 } else if (size == 2) {
274 bsize = 1;
275 } else if (size == 4) {
276 bsize = 2;
277 } else {
278 hw_error("register_ioport_write: invalid size");
279 return -1;
281 for(i = start; i < start + length; i += size) {
282 ioport_write_table[bsize][i] = func;
283 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
284 hw_error("register_ioport_write: invalid opaque");
285 ioport_opaque[i] = opaque;
287 return 0;
290 void isa_unassign_ioport(int start, int length)
292 int i;
294 for(i = start; i < start + length; i++) {
295 ioport_read_table[0][i] = default_ioport_readb;
296 ioport_read_table[1][i] = default_ioport_readw;
297 ioport_read_table[2][i] = default_ioport_readl;
299 ioport_write_table[0][i] = default_ioport_writeb;
300 ioport_write_table[1][i] = default_ioport_writew;
301 ioport_write_table[2][i] = default_ioport_writel;
305 /***********************************************************/
307 void pstrcpy(char *buf, int buf_size, const char *str)
309 int c;
310 char *q = buf;
312 if (buf_size <= 0)
313 return;
315 for(;;) {
316 c = *str++;
317 if (c == 0 || q >= buf + buf_size - 1)
318 break;
319 *q++ = c;
321 *q = '\0';
324 /* strcat and truncate. */
325 char *pstrcat(char *buf, int buf_size, const char *s)
327 int len;
328 len = strlen(buf);
329 if (len < buf_size)
330 pstrcpy(buf + len, buf_size - len, s);
331 return buf;
334 int strstart(const char *str, const char *val, const char **ptr)
336 const char *p, *q;
337 p = str;
338 q = val;
339 while (*q != '\0') {
340 if (*p != *q)
341 return 0;
342 p++;
343 q++;
345 if (ptr)
346 *ptr = p;
347 return 1;
350 void cpu_outb(CPUState *env, int addr, int val)
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outb: %04x %02x\n", addr, val);
355 #endif
356 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
363 void cpu_outw(CPUState *env, int addr, int val)
365 #ifdef DEBUG_IOPORT
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outw: %04x %04x\n", addr, val);
368 #endif
369 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
370 #ifdef USE_KQEMU
371 if (env)
372 env->last_io_time = cpu_get_time_fast();
373 #endif
376 void cpu_outl(CPUState *env, int addr, int val)
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "outl: %04x %08x\n", addr, val);
381 #endif
382 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
389 int cpu_inb(CPUState *env, int addr)
391 int val;
392 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inb : %04x %02x\n", addr, val);
396 #endif
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
401 return val;
404 int cpu_inw(CPUState *env, int addr)
406 int val;
407 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inw : %04x %04x\n", addr, val);
411 #endif
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
416 return val;
419 int cpu_inl(CPUState *env, int addr)
421 int val;
422 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 #endif
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
431 return val;
434 /***********************************************************/
435 void hw_error(const char *fmt, ...)
437 va_list ap;
438 CPUState *env;
440 va_start(ap, fmt);
441 fprintf(stderr, "qemu: hardware error: ");
442 vfprintf(stderr, fmt, ap);
443 fprintf(stderr, "\n");
444 for(env = first_cpu; env != NULL; env = env->next_cpu) {
445 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
446 #ifdef TARGET_I386
447 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
448 #else
449 cpu_dump_state(env, stderr, fprintf, 0);
450 #endif
452 va_end(ap);
453 abort();
456 /***********************************************************/
457 /* keyboard/mouse */
459 static QEMUPutKBDEvent *qemu_put_kbd_event;
460 static void *qemu_put_kbd_event_opaque;
461 static QEMUPutMouseEvent *qemu_put_mouse_event;
462 static void *qemu_put_mouse_event_opaque;
463 static int qemu_put_mouse_event_absolute;
465 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
467 qemu_put_kbd_event_opaque = opaque;
468 qemu_put_kbd_event = func;
471 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
473 qemu_put_mouse_event_opaque = opaque;
474 qemu_put_mouse_event = func;
475 qemu_put_mouse_event_absolute = absolute;
478 void kbd_put_keycode(int keycode)
480 if (qemu_put_kbd_event) {
481 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
485 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
487 if (qemu_put_mouse_event) {
488 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
489 dx, dy, dz, buttons_state);
493 int kbd_mouse_is_absolute(void)
495 return qemu_put_mouse_event_absolute;
498 /* compute with 96 bit intermediate result: (a*b)/c */
499 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
501 union {
502 uint64_t ll;
503 struct {
504 #ifdef WORDS_BIGENDIAN
505 uint32_t high, low;
506 #else
507 uint32_t low, high;
508 #endif
509 } l;
510 } u, res;
511 uint64_t rl, rh;
513 u.ll = a;
514 rl = (uint64_t)u.l.low * (uint64_t)b;
515 rh = (uint64_t)u.l.high * (uint64_t)b;
516 rh += (rl >> 32);
517 res.l.high = rh / c;
518 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
519 return res.ll;
522 /***********************************************************/
523 /* real time host monotonic timer */
525 #define QEMU_TIMER_BASE 1000000000LL
527 #ifdef WIN32
529 static int64_t clock_freq;
531 static void init_get_clock(void)
533 LARGE_INTEGER freq;
534 int ret;
535 ret = QueryPerformanceFrequency(&freq);
536 if (ret == 0) {
537 fprintf(stderr, "Could not calibrate ticks\n");
538 exit(1);
540 clock_freq = freq.QuadPart;
543 static int64_t get_clock(void)
545 LARGE_INTEGER ti;
546 QueryPerformanceCounter(&ti);
547 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
550 #else
552 static int use_rt_clock;
554 static void init_get_clock(void)
556 use_rt_clock = 0;
557 #if defined(__linux__)
559 struct timespec ts;
560 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
561 use_rt_clock = 1;
564 #endif
567 static int64_t get_clock(void)
569 #if defined(__linux__)
570 if (use_rt_clock) {
571 struct timespec ts;
572 clock_gettime(CLOCK_MONOTONIC, &ts);
573 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
574 } else
575 #endif
577 /* XXX: using gettimeofday leads to problems if the date
578 changes, so it should be avoided. */
579 struct timeval tv;
580 gettimeofday(&tv, NULL);
581 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
585 #endif
587 /***********************************************************/
588 /* guest cycle counter */
590 static int64_t cpu_ticks_prev;
591 static int64_t cpu_ticks_offset;
592 static int64_t cpu_clock_offset;
593 static int cpu_ticks_enabled;
595 /* return the host CPU cycle counter and handle stop/restart */
596 int64_t cpu_get_ticks(void)
598 if (!cpu_ticks_enabled) {
599 return cpu_ticks_offset;
600 } else {
601 int64_t ticks;
602 ticks = cpu_get_real_ticks();
603 if (cpu_ticks_prev > ticks) {
604 /* Note: non increasing ticks may happen if the host uses
605 software suspend */
606 cpu_ticks_offset += cpu_ticks_prev - ticks;
608 cpu_ticks_prev = ticks;
609 return ticks + cpu_ticks_offset;
613 /* return the host CPU monotonic timer and handle stop/restart */
614 static int64_t cpu_get_clock(void)
616 int64_t ti;
617 if (!cpu_ticks_enabled) {
618 return cpu_clock_offset;
619 } else {
620 ti = get_clock();
621 return ti + cpu_clock_offset;
625 /* enable cpu_get_ticks() */
626 void cpu_enable_ticks(void)
628 if (!cpu_ticks_enabled) {
629 cpu_ticks_offset -= cpu_get_real_ticks();
630 cpu_clock_offset -= get_clock();
631 cpu_ticks_enabled = 1;
635 /* disable cpu_get_ticks() : the clock is stopped. You must not call
636 cpu_get_ticks() after that. */
637 void cpu_disable_ticks(void)
639 if (cpu_ticks_enabled) {
640 cpu_ticks_offset = cpu_get_ticks();
641 cpu_clock_offset = cpu_get_clock();
642 cpu_ticks_enabled = 0;
646 /***********************************************************/
647 /* timers */
649 #define QEMU_TIMER_REALTIME 0
650 #define QEMU_TIMER_VIRTUAL 1
652 struct QEMUClock {
653 int type;
654 /* XXX: add frequency */
657 struct QEMUTimer {
658 QEMUClock *clock;
659 int64_t expire_time;
660 QEMUTimerCB *cb;
661 void *opaque;
662 struct QEMUTimer *next;
665 QEMUClock *rt_clock;
666 QEMUClock *vm_clock;
668 static QEMUTimer *active_timers[2];
669 #ifdef _WIN32
670 static MMRESULT timerID;
671 static HANDLE host_alarm = NULL;
672 static unsigned int period = 1;
673 #else
674 /* frequency of the times() clock tick */
675 static int timer_freq;
676 #endif
678 QEMUClock *qemu_new_clock(int type)
680 QEMUClock *clock;
681 clock = qemu_mallocz(sizeof(QEMUClock));
682 if (!clock)
683 return NULL;
684 clock->type = type;
685 return clock;
688 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
690 QEMUTimer *ts;
692 ts = qemu_mallocz(sizeof(QEMUTimer));
693 ts->clock = clock;
694 ts->cb = cb;
695 ts->opaque = opaque;
696 return ts;
699 void qemu_free_timer(QEMUTimer *ts)
701 qemu_free(ts);
704 /* stop a timer, but do not dealloc it */
705 void qemu_del_timer(QEMUTimer *ts)
707 QEMUTimer **pt, *t;
709 /* NOTE: this code must be signal safe because
710 qemu_timer_expired() can be called from a signal. */
711 pt = &active_timers[ts->clock->type];
712 for(;;) {
713 t = *pt;
714 if (!t)
715 break;
716 if (t == ts) {
717 *pt = t->next;
718 break;
720 pt = &t->next;
724 /* modify the current timer so that it will be fired when current_time
725 >= expire_time. The corresponding callback will be called. */
726 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
728 QEMUTimer **pt, *t;
730 qemu_del_timer(ts);
732 /* add the timer in the sorted list */
733 /* NOTE: this code must be signal safe because
734 qemu_timer_expired() can be called from a signal. */
735 pt = &active_timers[ts->clock->type];
736 for(;;) {
737 t = *pt;
738 if (!t)
739 break;
740 if (t->expire_time > expire_time)
741 break;
742 pt = &t->next;
744 ts->expire_time = expire_time;
745 ts->next = *pt;
746 *pt = ts;
749 int qemu_timer_pending(QEMUTimer *ts)
751 QEMUTimer *t;
752 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
753 if (t == ts)
754 return 1;
756 return 0;
759 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
761 if (!timer_head)
762 return 0;
763 return (timer_head->expire_time <= current_time);
766 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
768 QEMUTimer *ts;
770 for(;;) {
771 ts = *ptimer_head;
772 if (!ts || ts->expire_time > current_time)
773 break;
774 /* remove timer from the list before calling the callback */
775 *ptimer_head = ts->next;
776 ts->next = NULL;
778 /* run the callback (the timer list can be modified) */
779 ts->cb(ts->opaque);
783 int64_t qemu_get_clock(QEMUClock *clock)
785 switch(clock->type) {
786 case QEMU_TIMER_REALTIME:
787 return get_clock() / 1000000;
788 default:
789 case QEMU_TIMER_VIRTUAL:
790 return cpu_get_clock();
794 static void init_timers(void)
796 init_get_clock();
797 ticks_per_sec = QEMU_TIMER_BASE;
798 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
799 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
802 /* save a timer */
803 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
805 uint64_t expire_time;
807 if (qemu_timer_pending(ts)) {
808 expire_time = ts->expire_time;
809 } else {
810 expire_time = -1;
812 qemu_put_be64(f, expire_time);
815 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
817 uint64_t expire_time;
819 expire_time = qemu_get_be64(f);
820 if (expire_time != -1) {
821 qemu_mod_timer(ts, expire_time);
822 } else {
823 qemu_del_timer(ts);
827 static void timer_save(QEMUFile *f, void *opaque)
829 if (cpu_ticks_enabled) {
830 hw_error("cannot save state if virtual timers are running");
832 qemu_put_be64s(f, &cpu_ticks_offset);
833 qemu_put_be64s(f, &ticks_per_sec);
834 qemu_put_be64s(f, &cpu_clock_offset);
837 static int timer_load(QEMUFile *f, void *opaque, int version_id)
839 if (version_id != 1 && version_id != 2)
840 return -EINVAL;
841 if (cpu_ticks_enabled) {
842 return -EINVAL;
844 qemu_get_be64s(f, &cpu_ticks_offset);
845 qemu_get_be64s(f, &ticks_per_sec);
846 if (version_id == 2) {
847 qemu_get_be64s(f, &cpu_clock_offset);
849 return 0;
852 #ifdef _WIN32
853 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
854 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
855 #else
856 static void host_alarm_handler(int host_signum)
857 #endif
859 #if 0
860 #define DISP_FREQ 1000
862 static int64_t delta_min = INT64_MAX;
863 static int64_t delta_max, delta_cum, last_clock, delta, ti;
864 static int count;
865 ti = qemu_get_clock(vm_clock);
866 if (last_clock != 0) {
867 delta = ti - last_clock;
868 if (delta < delta_min)
869 delta_min = delta;
870 if (delta > delta_max)
871 delta_max = delta;
872 delta_cum += delta;
873 if (++count == DISP_FREQ) {
874 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
875 muldiv64(delta_min, 1000000, ticks_per_sec),
876 muldiv64(delta_max, 1000000, ticks_per_sec),
877 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
878 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
879 count = 0;
880 delta_min = INT64_MAX;
881 delta_max = 0;
882 delta_cum = 0;
885 last_clock = ti;
887 #endif
888 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
889 qemu_get_clock(vm_clock)) ||
890 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
891 qemu_get_clock(rt_clock))) {
892 #ifdef _WIN32
893 SetEvent(host_alarm);
894 #endif
895 CPUState *env = cpu_single_env;
896 if (env) {
897 /* stop the currently executing cpu because a timer occured */
898 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
899 #ifdef USE_KQEMU
900 if (env->kqemu_enabled) {
901 kqemu_cpu_interrupt(env);
903 #endif
908 #ifndef _WIN32
910 #if defined(__linux__)
912 #define RTC_FREQ 1024
914 static int rtc_fd;
916 static int start_rtc_timer(void)
918 rtc_fd = open("/dev/rtc", O_RDONLY);
919 if (rtc_fd < 0)
920 return -1;
921 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
922 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
923 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
924 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
925 goto fail;
927 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
928 fail:
929 close(rtc_fd);
930 return -1;
932 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
933 return 0;
936 #else
938 static int start_rtc_timer(void)
940 return -1;
943 #endif /* !defined(__linux__) */
945 #endif /* !defined(_WIN32) */
947 static void init_timer_alarm(void)
949 #ifdef _WIN32
951 int count=0;
952 TIMECAPS tc;
954 ZeroMemory(&tc, sizeof(TIMECAPS));
955 timeGetDevCaps(&tc, sizeof(TIMECAPS));
956 if (period < tc.wPeriodMin)
957 period = tc.wPeriodMin;
958 timeBeginPeriod(period);
959 timerID = timeSetEvent(1, // interval (ms)
960 period, // resolution
961 host_alarm_handler, // function
962 (DWORD)&count, // user parameter
963 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
964 if( !timerID ) {
965 perror("failed timer alarm");
966 exit(1);
968 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
969 if (!host_alarm) {
970 perror("failed CreateEvent");
971 exit(1);
973 qemu_add_wait_object(host_alarm, NULL, NULL);
975 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
976 #else
978 struct sigaction act;
979 struct itimerval itv;
981 /* get times() syscall frequency */
982 timer_freq = sysconf(_SC_CLK_TCK);
984 /* timer signal */
985 sigfillset(&act.sa_mask);
986 act.sa_flags = 0;
987 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
988 act.sa_flags |= SA_ONSTACK;
989 #endif
990 act.sa_handler = host_alarm_handler;
991 sigaction(SIGALRM, &act, NULL);
993 itv.it_interval.tv_sec = 0;
994 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
995 itv.it_value.tv_sec = 0;
996 itv.it_value.tv_usec = 10 * 1000;
997 setitimer(ITIMER_REAL, &itv, NULL);
998 /* we probe the tick duration of the kernel to inform the user if
999 the emulated kernel requested a too high timer frequency */
1000 getitimer(ITIMER_REAL, &itv);
1002 #if defined(__linux__)
1003 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1004 have timers with 1 ms resolution. The correct solution will
1005 be to use the POSIX real time timers available in recent
1006 2.6 kernels */
1007 if (itv.it_interval.tv_usec > 1000 || 1) {
1008 /* try to use /dev/rtc to have a faster timer */
1009 if (start_rtc_timer() < 0)
1010 goto use_itimer;
1011 /* disable itimer */
1012 itv.it_interval.tv_sec = 0;
1013 itv.it_interval.tv_usec = 0;
1014 itv.it_value.tv_sec = 0;
1015 itv.it_value.tv_usec = 0;
1016 setitimer(ITIMER_REAL, &itv, NULL);
1018 /* use the RTC */
1019 sigaction(SIGIO, &act, NULL);
1020 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1021 fcntl(rtc_fd, F_SETOWN, getpid());
1022 } else
1023 #endif /* defined(__linux__) */
1025 use_itimer:
1026 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1027 PIT_FREQ) / 1000000;
1030 #endif
1033 void quit_timers(void)
1035 #ifdef _WIN32
1036 timeKillEvent(timerID);
1037 timeEndPeriod(period);
1038 if (host_alarm) {
1039 CloseHandle(host_alarm);
1040 host_alarm = NULL;
1042 #endif
1045 /***********************************************************/
1046 /* character device */
1048 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1050 return s->chr_write(s, buf, len);
1053 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1055 if (!s->chr_ioctl)
1056 return -ENOTSUP;
1057 return s->chr_ioctl(s, cmd, arg);
1060 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1062 char buf[4096];
1063 va_list ap;
1064 va_start(ap, fmt);
1065 vsnprintf(buf, sizeof(buf), fmt, ap);
1066 qemu_chr_write(s, buf, strlen(buf));
1067 va_end(ap);
1070 void qemu_chr_send_event(CharDriverState *s, int event)
1072 if (s->chr_send_event)
1073 s->chr_send_event(s, event);
1076 void qemu_chr_add_read_handler(CharDriverState *s,
1077 IOCanRWHandler *fd_can_read,
1078 IOReadHandler *fd_read, void *opaque)
1080 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1083 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1085 s->chr_event = chr_event;
1088 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1090 return len;
1093 static void null_chr_add_read_handler(CharDriverState *chr,
1094 IOCanRWHandler *fd_can_read,
1095 IOReadHandler *fd_read, void *opaque)
1099 static CharDriverState *qemu_chr_open_null(void)
1101 CharDriverState *chr;
1103 chr = qemu_mallocz(sizeof(CharDriverState));
1104 if (!chr)
1105 return NULL;
1106 chr->chr_write = null_chr_write;
1107 chr->chr_add_read_handler = null_chr_add_read_handler;
1108 return chr;
1111 #ifdef _WIN32
1113 static void socket_cleanup(void)
1115 WSACleanup();
1118 static int socket_init(void)
1120 WSADATA Data;
1121 int ret, err;
1123 ret = WSAStartup(MAKEWORD(2,2), &Data);
1124 if (ret != 0) {
1125 err = WSAGetLastError();
1126 fprintf(stderr, "WSAStartup: %d\n", err);
1127 return -1;
1129 atexit(socket_cleanup);
1130 return 0;
1133 static int send_all(int fd, const uint8_t *buf, int len1)
1135 int ret, len;
1137 len = len1;
1138 while (len > 0) {
1139 ret = send(fd, buf, len, 0);
1140 if (ret < 0) {
1141 int errno;
1142 errno = WSAGetLastError();
1143 if (errno != WSAEWOULDBLOCK) {
1144 return -1;
1146 } else if (ret == 0) {
1147 break;
1148 } else {
1149 buf += ret;
1150 len -= ret;
1153 return len1 - len;
1156 void socket_set_nonblock(int fd)
1158 unsigned long opt = 1;
1159 ioctlsocket(fd, FIONBIO, &opt);
1162 #else
1164 static int unix_write(int fd, const uint8_t *buf, int len1)
1166 int ret, len;
1168 len = len1;
1169 while (len > 0) {
1170 ret = write(fd, buf, len);
1171 if (ret < 0) {
1172 if (errno != EINTR && errno != EAGAIN)
1173 return -1;
1174 } else if (ret == 0) {
1175 break;
1176 } else {
1177 buf += ret;
1178 len -= ret;
1181 return len1 - len;
1184 static inline int send_all(int fd, const uint8_t *buf, int len1)
1186 return unix_write(fd, buf, len1);
1189 void socket_set_nonblock(int fd)
1191 fcntl(fd, F_SETFL, O_NONBLOCK);
1193 #endif /* !_WIN32 */
1195 #ifndef _WIN32
1197 typedef struct {
1198 int fd_in, fd_out;
1199 IOCanRWHandler *fd_can_read;
1200 IOReadHandler *fd_read;
1201 void *fd_opaque;
1202 int max_size;
1203 } FDCharDriver;
1205 #define STDIO_MAX_CLIENTS 2
1207 static int stdio_nb_clients;
1208 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1210 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1212 FDCharDriver *s = chr->opaque;
1213 return unix_write(s->fd_out, buf, len);
1216 static int fd_chr_read_poll(void *opaque)
1218 CharDriverState *chr = opaque;
1219 FDCharDriver *s = chr->opaque;
1221 s->max_size = s->fd_can_read(s->fd_opaque);
1222 return s->max_size;
1225 static void fd_chr_read(void *opaque)
1227 CharDriverState *chr = opaque;
1228 FDCharDriver *s = chr->opaque;
1229 int size, len;
1230 uint8_t buf[1024];
1232 len = sizeof(buf);
1233 if (len > s->max_size)
1234 len = s->max_size;
1235 if (len == 0)
1236 return;
1237 size = read(s->fd_in, buf, len);
1238 if (size == 0) {
1239 /* FD has been closed. Remove it from the active list. */
1240 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1241 return;
1243 if (size > 0) {
1244 s->fd_read(s->fd_opaque, buf, size);
1248 static void fd_chr_add_read_handler(CharDriverState *chr,
1249 IOCanRWHandler *fd_can_read,
1250 IOReadHandler *fd_read, void *opaque)
1252 FDCharDriver *s = chr->opaque;
1254 if (s->fd_in >= 0) {
1255 s->fd_can_read = fd_can_read;
1256 s->fd_read = fd_read;
1257 s->fd_opaque = opaque;
1258 if (nographic && s->fd_in == 0) {
1259 } else {
1260 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1261 fd_chr_read, NULL, chr);
1266 /* open a character device to a unix fd */
1267 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1269 CharDriverState *chr;
1270 FDCharDriver *s;
1272 chr = qemu_mallocz(sizeof(CharDriverState));
1273 if (!chr)
1274 return NULL;
1275 s = qemu_mallocz(sizeof(FDCharDriver));
1276 if (!s) {
1277 free(chr);
1278 return NULL;
1280 s->fd_in = fd_in;
1281 s->fd_out = fd_out;
1282 chr->opaque = s;
1283 chr->chr_write = fd_chr_write;
1284 chr->chr_add_read_handler = fd_chr_add_read_handler;
1285 return chr;
1288 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1290 int fd_out;
1292 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1293 if (fd_out < 0)
1294 return NULL;
1295 return qemu_chr_open_fd(-1, fd_out);
1298 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1300 int fd_in, fd_out;
1301 char filename_in[256], filename_out[256];
1303 snprintf(filename_in, 256, "%s.in", filename);
1304 snprintf(filename_out, 256, "%s.out", filename);
1305 fd_in = open(filename_in, O_RDWR | O_BINARY);
1306 fd_out = open(filename_out, O_RDWR | O_BINARY);
1307 if (fd_in < 0 || fd_out < 0) {
1308 if (fd_in >= 0)
1309 close(fd_in);
1310 if (fd_out >= 0)
1311 close(fd_out);
1312 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1313 if (fd_in < 0)
1314 return NULL;
1316 return qemu_chr_open_fd(fd_in, fd_out);
1320 /* for STDIO, we handle the case where several clients use it
1321 (nographic mode) */
1323 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1325 #define TERM_FIFO_MAX_SIZE 1
1327 static int term_got_escape, client_index;
1328 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1329 static int term_fifo_size;
1330 static int term_timestamps;
1331 static int64_t term_timestamps_start;
1333 void term_print_help(void)
1335 printf("\n"
1336 "C-a h print this help\n"
1337 "C-a x exit emulator\n"
1338 "C-a s save disk data back to file (if -snapshot)\n"
1339 "C-a b send break (magic sysrq)\n"
1340 "C-a t toggle console timestamps\n"
1341 "C-a c switch between console and monitor\n"
1342 "C-a C-a send C-a\n"
1346 /* called when a char is received */
1347 static void stdio_received_byte(int ch)
1349 if (term_got_escape) {
1350 term_got_escape = 0;
1351 switch(ch) {
1352 case 'h':
1353 term_print_help();
1354 break;
1355 case 'x':
1356 exit(0);
1357 break;
1358 case 's':
1360 int i;
1361 for (i = 0; i < MAX_DISKS; i++) {
1362 if (bs_table[i])
1363 bdrv_commit(bs_table[i]);
1366 break;
1367 case 'b':
1368 if (client_index < stdio_nb_clients) {
1369 CharDriverState *chr;
1370 FDCharDriver *s;
1372 chr = stdio_clients[client_index];
1373 s = chr->opaque;
1374 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1376 break;
1377 case 'c':
1378 client_index++;
1379 if (client_index >= stdio_nb_clients)
1380 client_index = 0;
1381 if (client_index == 0) {
1382 /* send a new line in the monitor to get the prompt */
1383 ch = '\r';
1384 goto send_char;
1386 break;
1387 case 't':
1388 term_timestamps = !term_timestamps;
1389 term_timestamps_start = -1;
1390 break;
1391 case TERM_ESCAPE:
1392 goto send_char;
1394 } else if (ch == TERM_ESCAPE) {
1395 term_got_escape = 1;
1396 } else {
1397 send_char:
1398 if (client_index < stdio_nb_clients) {
1399 uint8_t buf[1];
1400 CharDriverState *chr;
1401 FDCharDriver *s;
1403 chr = stdio_clients[client_index];
1404 s = chr->opaque;
1405 if (s->fd_can_read(s->fd_opaque) > 0) {
1406 buf[0] = ch;
1407 s->fd_read(s->fd_opaque, buf, 1);
1408 } else if (term_fifo_size == 0) {
1409 term_fifo[term_fifo_size++] = ch;
1415 static int stdio_read_poll(void *opaque)
1417 CharDriverState *chr;
1418 FDCharDriver *s;
1420 if (client_index < stdio_nb_clients) {
1421 chr = stdio_clients[client_index];
1422 s = chr->opaque;
1423 /* try to flush the queue if needed */
1424 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1425 s->fd_read(s->fd_opaque, term_fifo, 1);
1426 term_fifo_size = 0;
1428 /* see if we can absorb more chars */
1429 if (term_fifo_size == 0)
1430 return 1;
1431 else
1432 return 0;
1433 } else {
1434 return 1;
1438 static void stdio_read(void *opaque)
1440 int size;
1441 uint8_t buf[1];
1443 size = read(0, buf, 1);
1444 if (size == 0) {
1445 /* stdin has been closed. Remove it from the active list. */
1446 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1447 return;
1449 if (size > 0)
1450 stdio_received_byte(buf[0]);
1453 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1455 FDCharDriver *s = chr->opaque;
1456 if (!term_timestamps) {
1457 return unix_write(s->fd_out, buf, len);
1458 } else {
1459 int i;
1460 char buf1[64];
1462 for(i = 0; i < len; i++) {
1463 unix_write(s->fd_out, buf + i, 1);
1464 if (buf[i] == '\n') {
1465 int64_t ti;
1466 int secs;
1468 ti = get_clock();
1469 if (term_timestamps_start == -1)
1470 term_timestamps_start = ti;
1471 ti -= term_timestamps_start;
1472 secs = ti / 1000000000;
1473 snprintf(buf1, sizeof(buf1),
1474 "[%02d:%02d:%02d.%03d] ",
1475 secs / 3600,
1476 (secs / 60) % 60,
1477 secs % 60,
1478 (int)((ti / 1000000) % 1000));
1479 unix_write(s->fd_out, buf1, strlen(buf1));
1482 return len;
1486 /* init terminal so that we can grab keys */
1487 static struct termios oldtty;
1488 static int old_fd0_flags;
1490 static void term_exit(void)
1492 tcsetattr (0, TCSANOW, &oldtty);
1493 fcntl(0, F_SETFL, old_fd0_flags);
1496 static void term_init(void)
1498 struct termios tty;
1500 tcgetattr (0, &tty);
1501 oldtty = tty;
1502 old_fd0_flags = fcntl(0, F_GETFL);
1504 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1505 |INLCR|IGNCR|ICRNL|IXON);
1506 tty.c_oflag |= OPOST;
1507 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1508 /* if graphical mode, we allow Ctrl-C handling */
1509 if (nographic)
1510 tty.c_lflag &= ~ISIG;
1511 tty.c_cflag &= ~(CSIZE|PARENB);
1512 tty.c_cflag |= CS8;
1513 tty.c_cc[VMIN] = 1;
1514 tty.c_cc[VTIME] = 0;
1516 tcsetattr (0, TCSANOW, &tty);
1518 atexit(term_exit);
1520 fcntl(0, F_SETFL, O_NONBLOCK);
1523 static CharDriverState *qemu_chr_open_stdio(void)
1525 CharDriverState *chr;
1527 if (nographic) {
1528 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1529 return NULL;
1530 chr = qemu_chr_open_fd(0, 1);
1531 chr->chr_write = stdio_write;
1532 if (stdio_nb_clients == 0)
1533 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1534 client_index = stdio_nb_clients;
1535 } else {
1536 if (stdio_nb_clients != 0)
1537 return NULL;
1538 chr = qemu_chr_open_fd(0, 1);
1540 stdio_clients[stdio_nb_clients++] = chr;
1541 if (stdio_nb_clients == 1) {
1542 /* set the terminal in raw mode */
1543 term_init();
1545 return chr;
1548 #if defined(__linux__)
1549 static CharDriverState *qemu_chr_open_pty(void)
1551 struct termios tty;
1552 char slave_name[1024];
1553 int master_fd, slave_fd;
1555 /* Not satisfying */
1556 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1557 return NULL;
1560 /* Disabling local echo and line-buffered output */
1561 tcgetattr (master_fd, &tty);
1562 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1563 tty.c_cc[VMIN] = 1;
1564 tty.c_cc[VTIME] = 0;
1565 tcsetattr (master_fd, TCSAFLUSH, &tty);
1567 fprintf(stderr, "char device redirected to %s\n", slave_name);
1568 return qemu_chr_open_fd(master_fd, master_fd);
1571 static void tty_serial_init(int fd, int speed,
1572 int parity, int data_bits, int stop_bits)
1574 struct termios tty;
1575 speed_t spd;
1577 #if 0
1578 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1579 speed, parity, data_bits, stop_bits);
1580 #endif
1581 tcgetattr (fd, &tty);
1583 switch(speed) {
1584 case 50:
1585 spd = B50;
1586 break;
1587 case 75:
1588 spd = B75;
1589 break;
1590 case 300:
1591 spd = B300;
1592 break;
1593 case 600:
1594 spd = B600;
1595 break;
1596 case 1200:
1597 spd = B1200;
1598 break;
1599 case 2400:
1600 spd = B2400;
1601 break;
1602 case 4800:
1603 spd = B4800;
1604 break;
1605 case 9600:
1606 spd = B9600;
1607 break;
1608 case 19200:
1609 spd = B19200;
1610 break;
1611 case 38400:
1612 spd = B38400;
1613 break;
1614 case 57600:
1615 spd = B57600;
1616 break;
1617 default:
1618 case 115200:
1619 spd = B115200;
1620 break;
1623 cfsetispeed(&tty, spd);
1624 cfsetospeed(&tty, spd);
1626 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1627 |INLCR|IGNCR|ICRNL|IXON);
1628 tty.c_oflag |= OPOST;
1629 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1630 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1631 switch(data_bits) {
1632 default:
1633 case 8:
1634 tty.c_cflag |= CS8;
1635 break;
1636 case 7:
1637 tty.c_cflag |= CS7;
1638 break;
1639 case 6:
1640 tty.c_cflag |= CS6;
1641 break;
1642 case 5:
1643 tty.c_cflag |= CS5;
1644 break;
1646 switch(parity) {
1647 default:
1648 case 'N':
1649 break;
1650 case 'E':
1651 tty.c_cflag |= PARENB;
1652 break;
1653 case 'O':
1654 tty.c_cflag |= PARENB | PARODD;
1655 break;
1657 if (stop_bits == 2)
1658 tty.c_cflag |= CSTOPB;
1660 tcsetattr (fd, TCSANOW, &tty);
1663 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1665 FDCharDriver *s = chr->opaque;
1667 switch(cmd) {
1668 case CHR_IOCTL_SERIAL_SET_PARAMS:
1670 QEMUSerialSetParams *ssp = arg;
1671 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1672 ssp->data_bits, ssp->stop_bits);
1674 break;
1675 case CHR_IOCTL_SERIAL_SET_BREAK:
1677 int enable = *(int *)arg;
1678 if (enable)
1679 tcsendbreak(s->fd_in, 1);
1681 break;
1682 default:
1683 return -ENOTSUP;
1685 return 0;
1688 static CharDriverState *qemu_chr_open_tty(const char *filename)
1690 CharDriverState *chr;
1691 int fd;
1693 fd = open(filename, O_RDWR | O_NONBLOCK);
1694 if (fd < 0)
1695 return NULL;
1696 fcntl(fd, F_SETFL, O_NONBLOCK);
1697 tty_serial_init(fd, 115200, 'N', 8, 1);
1698 chr = qemu_chr_open_fd(fd, fd);
1699 if (!chr)
1700 return NULL;
1701 chr->chr_ioctl = tty_serial_ioctl;
1702 return chr;
1705 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1707 int fd = (int)chr->opaque;
1708 uint8_t b;
1710 switch(cmd) {
1711 case CHR_IOCTL_PP_READ_DATA:
1712 if (ioctl(fd, PPRDATA, &b) < 0)
1713 return -ENOTSUP;
1714 *(uint8_t *)arg = b;
1715 break;
1716 case CHR_IOCTL_PP_WRITE_DATA:
1717 b = *(uint8_t *)arg;
1718 if (ioctl(fd, PPWDATA, &b) < 0)
1719 return -ENOTSUP;
1720 break;
1721 case CHR_IOCTL_PP_READ_CONTROL:
1722 if (ioctl(fd, PPRCONTROL, &b) < 0)
1723 return -ENOTSUP;
1724 *(uint8_t *)arg = b;
1725 break;
1726 case CHR_IOCTL_PP_WRITE_CONTROL:
1727 b = *(uint8_t *)arg;
1728 if (ioctl(fd, PPWCONTROL, &b) < 0)
1729 return -ENOTSUP;
1730 break;
1731 case CHR_IOCTL_PP_READ_STATUS:
1732 if (ioctl(fd, PPRSTATUS, &b) < 0)
1733 return -ENOTSUP;
1734 *(uint8_t *)arg = b;
1735 break;
1736 default:
1737 return -ENOTSUP;
1739 return 0;
1742 static CharDriverState *qemu_chr_open_pp(const char *filename)
1744 CharDriverState *chr;
1745 int fd;
1747 fd = open(filename, O_RDWR);
1748 if (fd < 0)
1749 return NULL;
1751 if (ioctl(fd, PPCLAIM) < 0) {
1752 close(fd);
1753 return NULL;
1756 chr = qemu_mallocz(sizeof(CharDriverState));
1757 if (!chr) {
1758 close(fd);
1759 return NULL;
1761 chr->opaque = (void *)fd;
1762 chr->chr_write = null_chr_write;
1763 chr->chr_add_read_handler = null_chr_add_read_handler;
1764 chr->chr_ioctl = pp_ioctl;
1765 return chr;
1768 #else
1769 static CharDriverState *qemu_chr_open_pty(void)
1771 return NULL;
1773 #endif
1775 #endif /* !defined(_WIN32) */
1777 #ifdef _WIN32
1778 typedef struct {
1779 IOCanRWHandler *fd_can_read;
1780 IOReadHandler *fd_read;
1781 void *win_opaque;
1782 int max_size;
1783 HANDLE hcom, hrecv, hsend;
1784 OVERLAPPED orecv, osend;
1785 BOOL fpipe;
1786 DWORD len;
1787 } WinCharState;
1789 #define NSENDBUF 2048
1790 #define NRECVBUF 2048
1791 #define MAXCONNECT 1
1792 #define NTIMEOUT 5000
1794 static int win_chr_poll(void *opaque);
1795 static int win_chr_pipe_poll(void *opaque);
1797 static void win_chr_close2(WinCharState *s)
1799 if (s->hsend) {
1800 CloseHandle(s->hsend);
1801 s->hsend = NULL;
1803 if (s->hrecv) {
1804 CloseHandle(s->hrecv);
1805 s->hrecv = NULL;
1807 if (s->hcom) {
1808 CloseHandle(s->hcom);
1809 s->hcom = NULL;
1811 if (s->fpipe)
1812 qemu_del_polling_cb(win_chr_pipe_poll, s);
1813 else
1814 qemu_del_polling_cb(win_chr_poll, s);
1817 static void win_chr_close(CharDriverState *chr)
1819 WinCharState *s = chr->opaque;
1820 win_chr_close2(s);
1823 static int win_chr_init(WinCharState *s, const char *filename)
1825 COMMCONFIG comcfg;
1826 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1827 COMSTAT comstat;
1828 DWORD size;
1829 DWORD err;
1831 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1832 if (!s->hsend) {
1833 fprintf(stderr, "Failed CreateEvent\n");
1834 goto fail;
1836 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1837 if (!s->hrecv) {
1838 fprintf(stderr, "Failed CreateEvent\n");
1839 goto fail;
1842 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1843 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1844 if (s->hcom == INVALID_HANDLE_VALUE) {
1845 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1846 s->hcom = NULL;
1847 goto fail;
1850 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1851 fprintf(stderr, "Failed SetupComm\n");
1852 goto fail;
1855 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1856 size = sizeof(COMMCONFIG);
1857 GetDefaultCommConfig(filename, &comcfg, &size);
1858 comcfg.dcb.DCBlength = sizeof(DCB);
1859 CommConfigDialog(filename, NULL, &comcfg);
1861 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1862 fprintf(stderr, "Failed SetCommState\n");
1863 goto fail;
1866 if (!SetCommMask(s->hcom, EV_ERR)) {
1867 fprintf(stderr, "Failed SetCommMask\n");
1868 goto fail;
1871 cto.ReadIntervalTimeout = MAXDWORD;
1872 if (!SetCommTimeouts(s->hcom, &cto)) {
1873 fprintf(stderr, "Failed SetCommTimeouts\n");
1874 goto fail;
1877 if (!ClearCommError(s->hcom, &err, &comstat)) {
1878 fprintf(stderr, "Failed ClearCommError\n");
1879 goto fail;
1881 qemu_add_polling_cb(win_chr_poll, s);
1882 return 0;
1884 fail:
1885 win_chr_close2(s);
1886 return -1;
1889 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1891 WinCharState *s = chr->opaque;
1892 DWORD len, ret, size, err;
1894 len = len1;
1895 ZeroMemory(&s->osend, sizeof(s->osend));
1896 s->osend.hEvent = s->hsend;
1897 while (len > 0) {
1898 if (s->hsend)
1899 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1900 else
1901 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1902 if (!ret) {
1903 err = GetLastError();
1904 if (err == ERROR_IO_PENDING) {
1905 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1906 if (ret) {
1907 buf += size;
1908 len -= size;
1909 } else {
1910 break;
1912 } else {
1913 break;
1915 } else {
1916 buf += size;
1917 len -= size;
1920 return len1 - len;
1923 static int win_chr_read_poll(WinCharState *s)
1925 s->max_size = s->fd_can_read(s->win_opaque);
1926 return s->max_size;
1929 static void win_chr_readfile(WinCharState *s)
1931 int ret, err;
1932 uint8_t buf[1024];
1933 DWORD size;
1935 ZeroMemory(&s->orecv, sizeof(s->orecv));
1936 s->orecv.hEvent = s->hrecv;
1937 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1938 if (!ret) {
1939 err = GetLastError();
1940 if (err == ERROR_IO_PENDING) {
1941 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1945 if (size > 0) {
1946 s->fd_read(s->win_opaque, buf, size);
1950 static void win_chr_read(WinCharState *s)
1952 if (s->len > s->max_size)
1953 s->len = s->max_size;
1954 if (s->len == 0)
1955 return;
1957 win_chr_readfile(s);
1960 static int win_chr_poll(void *opaque)
1962 WinCharState *s = opaque;
1963 COMSTAT status;
1964 DWORD comerr;
1966 ClearCommError(s->hcom, &comerr, &status);
1967 if (status.cbInQue > 0) {
1968 s->len = status.cbInQue;
1969 win_chr_read_poll(s);
1970 win_chr_read(s);
1971 return 1;
1973 return 0;
1976 static void win_chr_add_read_handler(CharDriverState *chr,
1977 IOCanRWHandler *fd_can_read,
1978 IOReadHandler *fd_read, void *opaque)
1980 WinCharState *s = chr->opaque;
1982 s->fd_can_read = fd_can_read;
1983 s->fd_read = fd_read;
1984 s->win_opaque = opaque;
1987 static CharDriverState *qemu_chr_open_win(const char *filename)
1989 CharDriverState *chr;
1990 WinCharState *s;
1992 chr = qemu_mallocz(sizeof(CharDriverState));
1993 if (!chr)
1994 return NULL;
1995 s = qemu_mallocz(sizeof(WinCharState));
1996 if (!s) {
1997 free(chr);
1998 return NULL;
2000 chr->opaque = s;
2001 chr->chr_write = win_chr_write;
2002 chr->chr_add_read_handler = win_chr_add_read_handler;
2003 chr->chr_close = win_chr_close;
2005 if (win_chr_init(s, filename) < 0) {
2006 free(s);
2007 free(chr);
2008 return NULL;
2010 return chr;
2013 static int win_chr_pipe_poll(void *opaque)
2015 WinCharState *s = opaque;
2016 DWORD size;
2018 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2019 if (size > 0) {
2020 s->len = size;
2021 win_chr_read_poll(s);
2022 win_chr_read(s);
2023 return 1;
2025 return 0;
2028 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2030 OVERLAPPED ov;
2031 int ret;
2032 DWORD size;
2033 char openname[256];
2035 s->fpipe = TRUE;
2037 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2038 if (!s->hsend) {
2039 fprintf(stderr, "Failed CreateEvent\n");
2040 goto fail;
2042 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2043 if (!s->hrecv) {
2044 fprintf(stderr, "Failed CreateEvent\n");
2045 goto fail;
2048 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2049 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2050 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2051 PIPE_WAIT,
2052 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2053 if (s->hcom == INVALID_HANDLE_VALUE) {
2054 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2055 s->hcom = NULL;
2056 goto fail;
2059 ZeroMemory(&ov, sizeof(ov));
2060 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2061 ret = ConnectNamedPipe(s->hcom, &ov);
2062 if (ret) {
2063 fprintf(stderr, "Failed ConnectNamedPipe\n");
2064 goto fail;
2067 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2068 if (!ret) {
2069 fprintf(stderr, "Failed GetOverlappedResult\n");
2070 if (ov.hEvent) {
2071 CloseHandle(ov.hEvent);
2072 ov.hEvent = NULL;
2074 goto fail;
2077 if (ov.hEvent) {
2078 CloseHandle(ov.hEvent);
2079 ov.hEvent = NULL;
2081 qemu_add_polling_cb(win_chr_pipe_poll, s);
2082 return 0;
2084 fail:
2085 win_chr_close2(s);
2086 return -1;
2090 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2092 CharDriverState *chr;
2093 WinCharState *s;
2095 chr = qemu_mallocz(sizeof(CharDriverState));
2096 if (!chr)
2097 return NULL;
2098 s = qemu_mallocz(sizeof(WinCharState));
2099 if (!s) {
2100 free(chr);
2101 return NULL;
2103 chr->opaque = s;
2104 chr->chr_write = win_chr_write;
2105 chr->chr_add_read_handler = win_chr_add_read_handler;
2106 chr->chr_close = win_chr_close;
2108 if (win_chr_pipe_init(s, filename) < 0) {
2109 free(s);
2110 free(chr);
2111 return NULL;
2113 return chr;
2116 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2118 CharDriverState *chr;
2119 WinCharState *s;
2121 chr = qemu_mallocz(sizeof(CharDriverState));
2122 if (!chr)
2123 return NULL;
2124 s = qemu_mallocz(sizeof(WinCharState));
2125 if (!s) {
2126 free(chr);
2127 return NULL;
2129 s->hcom = fd_out;
2130 chr->opaque = s;
2131 chr->chr_write = win_chr_write;
2132 chr->chr_add_read_handler = win_chr_add_read_handler;
2133 return chr;
2136 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2138 HANDLE fd_out;
2140 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2141 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2142 if (fd_out == INVALID_HANDLE_VALUE)
2143 return NULL;
2145 return qemu_chr_open_win_file(fd_out);
2147 #endif
2149 /***********************************************************/
2150 /* UDP Net console */
2152 typedef struct {
2153 IOCanRWHandler *fd_can_read;
2154 IOReadHandler *fd_read;
2155 void *fd_opaque;
2156 int fd;
2157 struct sockaddr_in daddr;
2158 char buf[1024];
2159 int bufcnt;
2160 int bufptr;
2161 int max_size;
2162 } NetCharDriver;
2164 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2166 NetCharDriver *s = chr->opaque;
2168 return sendto(s->fd, buf, len, 0,
2169 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2172 static int udp_chr_read_poll(void *opaque)
2174 CharDriverState *chr = opaque;
2175 NetCharDriver *s = chr->opaque;
2177 s->max_size = s->fd_can_read(s->fd_opaque);
2179 /* If there were any stray characters in the queue process them
2180 * first
2182 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2183 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2184 s->bufptr++;
2185 s->max_size = s->fd_can_read(s->fd_opaque);
2187 return s->max_size;
2190 static void udp_chr_read(void *opaque)
2192 CharDriverState *chr = opaque;
2193 NetCharDriver *s = chr->opaque;
2195 if (s->max_size == 0)
2196 return;
2197 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2198 s->bufptr = s->bufcnt;
2199 if (s->bufcnt <= 0)
2200 return;
2202 s->bufptr = 0;
2203 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2204 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2205 s->bufptr++;
2206 s->max_size = s->fd_can_read(s->fd_opaque);
2210 static void udp_chr_add_read_handler(CharDriverState *chr,
2211 IOCanRWHandler *fd_can_read,
2212 IOReadHandler *fd_read, void *opaque)
2214 NetCharDriver *s = chr->opaque;
2216 if (s->fd >= 0) {
2217 s->fd_can_read = fd_can_read;
2218 s->fd_read = fd_read;
2219 s->fd_opaque = opaque;
2220 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2221 udp_chr_read, NULL, chr);
2225 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2226 #ifndef _WIN32
2227 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2228 #endif
2229 int parse_host_src_port(struct sockaddr_in *haddr,
2230 struct sockaddr_in *saddr,
2231 const char *str);
2233 static CharDriverState *qemu_chr_open_udp(const char *def)
2235 CharDriverState *chr = NULL;
2236 NetCharDriver *s = NULL;
2237 int fd = -1;
2238 struct sockaddr_in saddr;
2240 chr = qemu_mallocz(sizeof(CharDriverState));
2241 if (!chr)
2242 goto return_err;
2243 s = qemu_mallocz(sizeof(NetCharDriver));
2244 if (!s)
2245 goto return_err;
2247 fd = socket(PF_INET, SOCK_DGRAM, 0);
2248 if (fd < 0) {
2249 perror("socket(PF_INET, SOCK_DGRAM)");
2250 goto return_err;
2253 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2254 printf("Could not parse: %s\n", def);
2255 goto return_err;
2258 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2260 perror("bind");
2261 goto return_err;
2264 s->fd = fd;
2265 s->bufcnt = 0;
2266 s->bufptr = 0;
2267 chr->opaque = s;
2268 chr->chr_write = udp_chr_write;
2269 chr->chr_add_read_handler = udp_chr_add_read_handler;
2270 return chr;
2272 return_err:
2273 if (chr)
2274 free(chr);
2275 if (s)
2276 free(s);
2277 if (fd >= 0)
2278 closesocket(fd);
2279 return NULL;
2282 /***********************************************************/
2283 /* TCP Net console */
2285 typedef struct {
2286 IOCanRWHandler *fd_can_read;
2287 IOReadHandler *fd_read;
2288 void *fd_opaque;
2289 int fd, listen_fd;
2290 int connected;
2291 int max_size;
2292 int do_telnetopt;
2293 int is_unix;
2294 } TCPCharDriver;
2296 static void tcp_chr_accept(void *opaque);
2298 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2300 TCPCharDriver *s = chr->opaque;
2301 if (s->connected) {
2302 return send_all(s->fd, buf, len);
2303 } else {
2304 /* XXX: indicate an error ? */
2305 return len;
2309 static int tcp_chr_read_poll(void *opaque)
2311 CharDriverState *chr = opaque;
2312 TCPCharDriver *s = chr->opaque;
2313 if (!s->connected)
2314 return 0;
2315 if (!s->fd_can_read)
2316 return 0;
2317 s->max_size = s->fd_can_read(s->fd_opaque);
2318 return s->max_size;
2321 #define IAC 255
2322 #define IAC_BREAK 243
2323 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2324 TCPCharDriver *s,
2325 char *buf, int *size)
2327 /* Handle any telnet client's basic IAC options to satisfy char by
2328 * char mode with no echo. All IAC options will be removed from
2329 * the buf and the do_telnetopt variable will be used to track the
2330 * state of the width of the IAC information.
2332 * IAC commands come in sets of 3 bytes with the exception of the
2333 * "IAC BREAK" command and the double IAC.
2336 int i;
2337 int j = 0;
2339 for (i = 0; i < *size; i++) {
2340 if (s->do_telnetopt > 1) {
2341 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2342 /* Double IAC means send an IAC */
2343 if (j != i)
2344 buf[j] = buf[i];
2345 j++;
2346 s->do_telnetopt = 1;
2347 } else {
2348 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2349 /* Handle IAC break commands by sending a serial break */
2350 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2351 s->do_telnetopt++;
2353 s->do_telnetopt++;
2355 if (s->do_telnetopt >= 4) {
2356 s->do_telnetopt = 1;
2358 } else {
2359 if ((unsigned char)buf[i] == IAC) {
2360 s->do_telnetopt = 2;
2361 } else {
2362 if (j != i)
2363 buf[j] = buf[i];
2364 j++;
2368 *size = j;
2371 static void tcp_chr_read(void *opaque)
2373 CharDriverState *chr = opaque;
2374 TCPCharDriver *s = chr->opaque;
2375 uint8_t buf[1024];
2376 int len, size;
2378 if (!s->connected || s->max_size <= 0)
2379 return;
2380 len = sizeof(buf);
2381 if (len > s->max_size)
2382 len = s->max_size;
2383 size = recv(s->fd, buf, len, 0);
2384 if (size == 0) {
2385 /* connection closed */
2386 s->connected = 0;
2387 if (s->listen_fd >= 0) {
2388 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2390 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2391 closesocket(s->fd);
2392 s->fd = -1;
2393 } else if (size > 0) {
2394 if (s->do_telnetopt)
2395 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2396 if (size > 0)
2397 s->fd_read(s->fd_opaque, buf, size);
2401 static void tcp_chr_add_read_handler(CharDriverState *chr,
2402 IOCanRWHandler *fd_can_read,
2403 IOReadHandler *fd_read, void *opaque)
2405 TCPCharDriver *s = chr->opaque;
2407 s->fd_can_read = fd_can_read;
2408 s->fd_read = fd_read;
2409 s->fd_opaque = opaque;
2412 static void tcp_chr_connect(void *opaque)
2414 CharDriverState *chr = opaque;
2415 TCPCharDriver *s = chr->opaque;
2417 s->connected = 1;
2418 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2419 tcp_chr_read, NULL, chr);
2422 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2423 static void tcp_chr_telnet_init(int fd)
2425 char buf[3];
2426 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2427 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2428 send(fd, (char *)buf, 3, 0);
2429 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2430 send(fd, (char *)buf, 3, 0);
2431 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2432 send(fd, (char *)buf, 3, 0);
2433 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2434 send(fd, (char *)buf, 3, 0);
2437 static void tcp_chr_accept(void *opaque)
2439 CharDriverState *chr = opaque;
2440 TCPCharDriver *s = chr->opaque;
2441 struct sockaddr_in saddr;
2442 #ifndef _WIN32
2443 struct sockaddr_un uaddr;
2444 #endif
2445 struct sockaddr *addr;
2446 socklen_t len;
2447 int fd;
2449 for(;;) {
2450 #ifndef _WIN32
2451 if (s->is_unix) {
2452 len = sizeof(uaddr);
2453 addr = (struct sockaddr *)&uaddr;
2454 } else
2455 #endif
2457 len = sizeof(saddr);
2458 addr = (struct sockaddr *)&saddr;
2460 fd = accept(s->listen_fd, addr, &len);
2461 if (fd < 0 && errno != EINTR) {
2462 return;
2463 } else if (fd >= 0) {
2464 if (s->do_telnetopt)
2465 tcp_chr_telnet_init(fd);
2466 break;
2469 socket_set_nonblock(fd);
2470 s->fd = fd;
2471 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2472 tcp_chr_connect(chr);
2475 static void tcp_chr_close(CharDriverState *chr)
2477 TCPCharDriver *s = chr->opaque;
2478 if (s->fd >= 0)
2479 closesocket(s->fd);
2480 if (s->listen_fd >= 0)
2481 closesocket(s->listen_fd);
2482 qemu_free(s);
2485 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2486 int is_telnet,
2487 int is_unix)
2489 CharDriverState *chr = NULL;
2490 TCPCharDriver *s = NULL;
2491 int fd = -1, ret, err, val;
2492 int is_listen = 0;
2493 int is_waitconnect = 1;
2494 const char *ptr;
2495 struct sockaddr_in saddr;
2496 #ifndef _WIN32
2497 struct sockaddr_un uaddr;
2498 #endif
2499 struct sockaddr *addr;
2500 socklen_t addrlen;
2502 #ifndef _WIN32
2503 if (is_unix) {
2504 addr = (struct sockaddr *)&uaddr;
2505 addrlen = sizeof(uaddr);
2506 if (parse_unix_path(&uaddr, host_str) < 0)
2507 goto fail;
2508 } else
2509 #endif
2511 addr = (struct sockaddr *)&saddr;
2512 addrlen = sizeof(saddr);
2513 if (parse_host_port(&saddr, host_str) < 0)
2514 goto fail;
2517 ptr = host_str;
2518 while((ptr = strchr(ptr,','))) {
2519 ptr++;
2520 if (!strncmp(ptr,"server",6)) {
2521 is_listen = 1;
2522 } else if (!strncmp(ptr,"nowait",6)) {
2523 is_waitconnect = 0;
2524 } else {
2525 printf("Unknown option: %s\n", ptr);
2526 goto fail;
2529 if (!is_listen)
2530 is_waitconnect = 0;
2532 chr = qemu_mallocz(sizeof(CharDriverState));
2533 if (!chr)
2534 goto fail;
2535 s = qemu_mallocz(sizeof(TCPCharDriver));
2536 if (!s)
2537 goto fail;
2539 #ifndef _WIN32
2540 if (is_unix)
2541 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2542 else
2543 #endif
2544 fd = socket(PF_INET, SOCK_STREAM, 0);
2546 if (fd < 0)
2547 goto fail;
2549 if (!is_waitconnect)
2550 socket_set_nonblock(fd);
2552 s->connected = 0;
2553 s->fd = -1;
2554 s->listen_fd = -1;
2555 s->is_unix = is_unix;
2557 chr->opaque = s;
2558 chr->chr_write = tcp_chr_write;
2559 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2560 chr->chr_close = tcp_chr_close;
2562 if (is_listen) {
2563 /* allow fast reuse */
2564 #ifndef _WIN32
2565 if (is_unix) {
2566 char path[109];
2567 strncpy(path, uaddr.sun_path, 108);
2568 path[108] = 0;
2569 unlink(path);
2570 } else
2571 #endif
2573 val = 1;
2574 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2577 ret = bind(fd, addr, addrlen);
2578 if (ret < 0)
2579 goto fail;
2581 ret = listen(fd, 0);
2582 if (ret < 0)
2583 goto fail;
2585 s->listen_fd = fd;
2586 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2587 if (is_telnet)
2588 s->do_telnetopt = 1;
2589 } else {
2590 for(;;) {
2591 ret = connect(fd, addr, addrlen);
2592 if (ret < 0) {
2593 err = socket_error();
2594 if (err == EINTR || err == EWOULDBLOCK) {
2595 } else if (err == EINPROGRESS) {
2596 break;
2597 } else {
2598 goto fail;
2600 } else {
2601 s->connected = 1;
2602 break;
2605 s->fd = fd;
2606 if (s->connected)
2607 tcp_chr_connect(chr);
2608 else
2609 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2612 if (is_listen && is_waitconnect) {
2613 printf("QEMU waiting for connection on: %s\n", host_str);
2614 tcp_chr_accept(chr);
2615 socket_set_nonblock(s->listen_fd);
2618 return chr;
2619 fail:
2620 if (fd >= 0)
2621 closesocket(fd);
2622 qemu_free(s);
2623 qemu_free(chr);
2624 return NULL;
2627 CharDriverState *qemu_chr_open(const char *filename)
2629 const char *p;
2631 if (!strcmp(filename, "vc")) {
2632 return text_console_init(&display_state);
2633 } else if (!strcmp(filename, "null")) {
2634 return qemu_chr_open_null();
2635 } else
2636 if (strstart(filename, "tcp:", &p)) {
2637 return qemu_chr_open_tcp(p, 0, 0);
2638 } else
2639 if (strstart(filename, "telnet:", &p)) {
2640 return qemu_chr_open_tcp(p, 1, 0);
2641 } else
2642 if (strstart(filename, "udp:", &p)) {
2643 return qemu_chr_open_udp(p);
2644 } else
2645 #ifndef _WIN32
2646 if (strstart(filename, "unix:", &p)) {
2647 return qemu_chr_open_tcp(p, 0, 1);
2648 } else if (strstart(filename, "file:", &p)) {
2649 return qemu_chr_open_file_out(p);
2650 } else if (strstart(filename, "pipe:", &p)) {
2651 return qemu_chr_open_pipe(p);
2652 } else if (!strcmp(filename, "pty")) {
2653 return qemu_chr_open_pty();
2654 } else if (!strcmp(filename, "stdio")) {
2655 return qemu_chr_open_stdio();
2656 } else
2657 #endif
2658 #if defined(__linux__)
2659 if (strstart(filename, "/dev/parport", NULL)) {
2660 return qemu_chr_open_pp(filename);
2661 } else
2662 if (strstart(filename, "/dev/", NULL)) {
2663 return qemu_chr_open_tty(filename);
2664 } else
2665 #endif
2666 #ifdef _WIN32
2667 if (strstart(filename, "COM", NULL)) {
2668 return qemu_chr_open_win(filename);
2669 } else
2670 if (strstart(filename, "pipe:", &p)) {
2671 return qemu_chr_open_win_pipe(p);
2672 } else
2673 if (strstart(filename, "file:", &p)) {
2674 return qemu_chr_open_win_file_out(p);
2676 #endif
2678 return NULL;
2682 void qemu_chr_close(CharDriverState *chr)
2684 if (chr->chr_close)
2685 chr->chr_close(chr);
2688 /***********************************************************/
2689 /* network device redirectors */
2691 void hex_dump(FILE *f, const uint8_t *buf, int size)
2693 int len, i, j, c;
2695 for(i=0;i<size;i+=16) {
2696 len = size - i;
2697 if (len > 16)
2698 len = 16;
2699 fprintf(f, "%08x ", i);
2700 for(j=0;j<16;j++) {
2701 if (j < len)
2702 fprintf(f, " %02x", buf[i+j]);
2703 else
2704 fprintf(f, " ");
2706 fprintf(f, " ");
2707 for(j=0;j<len;j++) {
2708 c = buf[i+j];
2709 if (c < ' ' || c > '~')
2710 c = '.';
2711 fprintf(f, "%c", c);
2713 fprintf(f, "\n");
2717 static int parse_macaddr(uint8_t *macaddr, const char *p)
2719 int i;
2720 for(i = 0; i < 6; i++) {
2721 macaddr[i] = strtol(p, (char **)&p, 16);
2722 if (i == 5) {
2723 if (*p != '\0')
2724 return -1;
2725 } else {
2726 if (*p != ':')
2727 return -1;
2728 p++;
2731 return 0;
2734 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2736 const char *p, *p1;
2737 int len;
2738 p = *pp;
2739 p1 = strchr(p, sep);
2740 if (!p1)
2741 return -1;
2742 len = p1 - p;
2743 p1++;
2744 if (buf_size > 0) {
2745 if (len > buf_size - 1)
2746 len = buf_size - 1;
2747 memcpy(buf, p, len);
2748 buf[len] = '\0';
2750 *pp = p1;
2751 return 0;
2754 int parse_host_src_port(struct sockaddr_in *haddr,
2755 struct sockaddr_in *saddr,
2756 const char *input_str)
2758 char *str = strdup(input_str);
2759 char *host_str = str;
2760 char *src_str;
2761 char *ptr;
2764 * Chop off any extra arguments at the end of the string which
2765 * would start with a comma, then fill in the src port information
2766 * if it was provided else use the "any address" and "any port".
2768 if ((ptr = strchr(str,',')))
2769 *ptr = '\0';
2771 if ((src_str = strchr(input_str,'@'))) {
2772 *src_str = '\0';
2773 src_str++;
2776 if (parse_host_port(haddr, host_str) < 0)
2777 goto fail;
2779 if (!src_str || *src_str == '\0')
2780 src_str = ":0";
2782 if (parse_host_port(saddr, src_str) < 0)
2783 goto fail;
2785 free(str);
2786 return(0);
2788 fail:
2789 free(str);
2790 return -1;
2793 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2795 char buf[512];
2796 struct hostent *he;
2797 const char *p, *r;
2798 int port;
2800 p = str;
2801 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2802 return -1;
2803 saddr->sin_family = AF_INET;
2804 if (buf[0] == '\0') {
2805 saddr->sin_addr.s_addr = 0;
2806 } else {
2807 if (isdigit(buf[0])) {
2808 if (!inet_aton(buf, &saddr->sin_addr))
2809 return -1;
2810 } else {
2811 if ((he = gethostbyname(buf)) == NULL)
2812 return - 1;
2813 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2816 port = strtol(p, (char **)&r, 0);
2817 if (r == p)
2818 return -1;
2819 saddr->sin_port = htons(port);
2820 return 0;
2823 #ifndef _WIN32
2824 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2826 const char *p;
2827 int len;
2829 len = MIN(108, strlen(str));
2830 p = strchr(str, ',');
2831 if (p)
2832 len = MIN(len, p - str);
2834 memset(uaddr, 0, sizeof(*uaddr));
2836 uaddr->sun_family = AF_UNIX;
2837 memcpy(uaddr->sun_path, str, len);
2839 return 0;
2841 #endif
2843 /* find or alloc a new VLAN */
2844 VLANState *qemu_find_vlan(int id)
2846 VLANState **pvlan, *vlan;
2847 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2848 if (vlan->id == id)
2849 return vlan;
2851 vlan = qemu_mallocz(sizeof(VLANState));
2852 if (!vlan)
2853 return NULL;
2854 vlan->id = id;
2855 vlan->next = NULL;
2856 pvlan = &first_vlan;
2857 while (*pvlan != NULL)
2858 pvlan = &(*pvlan)->next;
2859 *pvlan = vlan;
2860 return vlan;
2863 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2864 IOReadHandler *fd_read,
2865 IOCanRWHandler *fd_can_read,
2866 void *opaque)
2868 VLANClientState *vc, **pvc;
2869 vc = qemu_mallocz(sizeof(VLANClientState));
2870 if (!vc)
2871 return NULL;
2872 vc->fd_read = fd_read;
2873 vc->fd_can_read = fd_can_read;
2874 vc->opaque = opaque;
2875 vc->vlan = vlan;
2877 vc->next = NULL;
2878 pvc = &vlan->first_client;
2879 while (*pvc != NULL)
2880 pvc = &(*pvc)->next;
2881 *pvc = vc;
2882 return vc;
2885 int qemu_can_send_packet(VLANClientState *vc1)
2887 VLANState *vlan = vc1->vlan;
2888 VLANClientState *vc;
2890 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2891 if (vc != vc1) {
2892 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2893 return 0;
2896 return 1;
2899 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2901 VLANState *vlan = vc1->vlan;
2902 VLANClientState *vc;
2904 #if 0
2905 printf("vlan %d send:\n", vlan->id);
2906 hex_dump(stdout, buf, size);
2907 #endif
2908 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2909 if (vc != vc1) {
2910 vc->fd_read(vc->opaque, buf, size);
2915 #if defined(CONFIG_SLIRP)
2917 /* slirp network adapter */
2919 static int slirp_inited;
2920 static VLANClientState *slirp_vc;
2922 int slirp_can_output(void)
2924 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2927 void slirp_output(const uint8_t *pkt, int pkt_len)
2929 #if 0
2930 printf("slirp output:\n");
2931 hex_dump(stdout, pkt, pkt_len);
2932 #endif
2933 if (!slirp_vc)
2934 return;
2935 qemu_send_packet(slirp_vc, pkt, pkt_len);
2938 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2940 #if 0
2941 printf("slirp input:\n");
2942 hex_dump(stdout, buf, size);
2943 #endif
2944 slirp_input(buf, size);
2947 static int net_slirp_init(VLANState *vlan)
2949 if (!slirp_inited) {
2950 slirp_inited = 1;
2951 slirp_init();
2953 slirp_vc = qemu_new_vlan_client(vlan,
2954 slirp_receive, NULL, NULL);
2955 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2956 return 0;
2959 static void net_slirp_redir(const char *redir_str)
2961 int is_udp;
2962 char buf[256], *r;
2963 const char *p;
2964 struct in_addr guest_addr;
2965 int host_port, guest_port;
2967 if (!slirp_inited) {
2968 slirp_inited = 1;
2969 slirp_init();
2972 p = redir_str;
2973 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2974 goto fail;
2975 if (!strcmp(buf, "tcp")) {
2976 is_udp = 0;
2977 } else if (!strcmp(buf, "udp")) {
2978 is_udp = 1;
2979 } else {
2980 goto fail;
2983 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2984 goto fail;
2985 host_port = strtol(buf, &r, 0);
2986 if (r == buf)
2987 goto fail;
2989 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2990 goto fail;
2991 if (buf[0] == '\0') {
2992 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2994 if (!inet_aton(buf, &guest_addr))
2995 goto fail;
2997 guest_port = strtol(p, &r, 0);
2998 if (r == p)
2999 goto fail;
3001 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3002 fprintf(stderr, "qemu: could not set up redirection\n");
3003 exit(1);
3005 return;
3006 fail:
3007 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3008 exit(1);
3011 #ifndef _WIN32
3013 char smb_dir[1024];
3015 static void smb_exit(void)
3017 DIR *d;
3018 struct dirent *de;
3019 char filename[1024];
3021 /* erase all the files in the directory */
3022 d = opendir(smb_dir);
3023 for(;;) {
3024 de = readdir(d);
3025 if (!de)
3026 break;
3027 if (strcmp(de->d_name, ".") != 0 &&
3028 strcmp(de->d_name, "..") != 0) {
3029 snprintf(filename, sizeof(filename), "%s/%s",
3030 smb_dir, de->d_name);
3031 unlink(filename);
3034 closedir(d);
3035 rmdir(smb_dir);
3038 /* automatic user mode samba server configuration */
3039 void net_slirp_smb(const char *exported_dir)
3041 char smb_conf[1024];
3042 char smb_cmdline[1024];
3043 FILE *f;
3045 if (!slirp_inited) {
3046 slirp_inited = 1;
3047 slirp_init();
3050 /* XXX: better tmp dir construction */
3051 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3052 if (mkdir(smb_dir, 0700) < 0) {
3053 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3054 exit(1);
3056 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3058 f = fopen(smb_conf, "w");
3059 if (!f) {
3060 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3061 exit(1);
3063 fprintf(f,
3064 "[global]\n"
3065 "private dir=%s\n"
3066 "smb ports=0\n"
3067 "socket address=127.0.0.1\n"
3068 "pid directory=%s\n"
3069 "lock directory=%s\n"
3070 "log file=%s/log.smbd\n"
3071 "smb passwd file=%s/smbpasswd\n"
3072 "security = share\n"
3073 "[qemu]\n"
3074 "path=%s\n"
3075 "read only=no\n"
3076 "guest ok=yes\n",
3077 smb_dir,
3078 smb_dir,
3079 smb_dir,
3080 smb_dir,
3081 smb_dir,
3082 exported_dir
3084 fclose(f);
3085 atexit(smb_exit);
3087 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3088 smb_conf);
3090 slirp_add_exec(0, smb_cmdline, 4, 139);
3093 #endif /* !defined(_WIN32) */
3095 #endif /* CONFIG_SLIRP */
3097 #if !defined(_WIN32)
3099 typedef struct TAPState {
3100 VLANClientState *vc;
3101 int fd;
3102 } TAPState;
3104 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3106 TAPState *s = opaque;
3107 int ret;
3108 for(;;) {
3109 ret = write(s->fd, buf, size);
3110 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3111 } else {
3112 break;
3117 static void tap_send(void *opaque)
3119 TAPState *s = opaque;
3120 uint8_t buf[4096];
3121 int size;
3123 size = read(s->fd, buf, sizeof(buf));
3124 if (size > 0) {
3125 qemu_send_packet(s->vc, buf, size);
3129 /* fd support */
3131 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3133 TAPState *s;
3135 s = qemu_mallocz(sizeof(TAPState));
3136 if (!s)
3137 return NULL;
3138 s->fd = fd;
3139 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3140 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3141 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3142 return s;
3145 #ifdef _BSD
3146 static int tap_open(char *ifname, int ifname_size)
3148 int fd;
3149 char *dev;
3150 struct stat s;
3152 fd = open("/dev/tap", O_RDWR);
3153 if (fd < 0) {
3154 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3155 return -1;
3158 fstat(fd, &s);
3159 dev = devname(s.st_rdev, S_IFCHR);
3160 pstrcpy(ifname, ifname_size, dev);
3162 fcntl(fd, F_SETFL, O_NONBLOCK);
3163 return fd;
3165 #elif defined(__sun__)
3166 static int tap_open(char *ifname, int ifname_size)
3168 fprintf(stderr, "warning: tap_open not yet implemented\n");
3169 return -1;
3171 #else
3172 static int tap_open(char *ifname, int ifname_size)
3174 struct ifreq ifr;
3175 int fd, ret;
3177 fd = open("/dev/net/tun", O_RDWR);
3178 if (fd < 0) {
3179 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3180 return -1;
3182 memset(&ifr, 0, sizeof(ifr));
3183 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3184 if (ifname[0] != '\0')
3185 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3186 else
3187 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3188 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3189 if (ret != 0) {
3190 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3191 close(fd);
3192 return -1;
3194 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3195 fcntl(fd, F_SETFL, O_NONBLOCK);
3196 return fd;
3198 #endif
3200 static int net_tap_init(VLANState *vlan, const char *ifname1,
3201 const char *setup_script)
3203 TAPState *s;
3204 int pid, status, fd;
3205 char *args[3];
3206 char **parg;
3207 char ifname[128];
3209 if (ifname1 != NULL)
3210 pstrcpy(ifname, sizeof(ifname), ifname1);
3211 else
3212 ifname[0] = '\0';
3213 fd = tap_open(ifname, sizeof(ifname));
3214 if (fd < 0)
3215 return -1;
3217 if (!setup_script)
3218 setup_script = "";
3219 if (setup_script[0] != '\0') {
3220 /* try to launch network init script */
3221 pid = fork();
3222 if (pid >= 0) {
3223 if (pid == 0) {
3224 parg = args;
3225 *parg++ = (char *)setup_script;
3226 *parg++ = ifname;
3227 *parg++ = NULL;
3228 execv(setup_script, args);
3229 _exit(1);
3231 while (waitpid(pid, &status, 0) != pid);
3232 if (!WIFEXITED(status) ||
3233 WEXITSTATUS(status) != 0) {
3234 fprintf(stderr, "%s: could not launch network script\n",
3235 setup_script);
3236 return -1;
3240 s = net_tap_fd_init(vlan, fd);
3241 if (!s)
3242 return -1;
3243 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3244 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3245 return 0;
3248 #endif /* !_WIN32 */
3250 /* network connection */
3251 typedef struct NetSocketState {
3252 VLANClientState *vc;
3253 int fd;
3254 int state; /* 0 = getting length, 1 = getting data */
3255 int index;
3256 int packet_len;
3257 uint8_t buf[4096];
3258 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3259 } NetSocketState;
3261 typedef struct NetSocketListenState {
3262 VLANState *vlan;
3263 int fd;
3264 } NetSocketListenState;
3266 /* XXX: we consider we can send the whole packet without blocking */
3267 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3269 NetSocketState *s = opaque;
3270 uint32_t len;
3271 len = htonl(size);
3273 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3274 send_all(s->fd, buf, size);
3277 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3279 NetSocketState *s = opaque;
3280 sendto(s->fd, buf, size, 0,
3281 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3284 static void net_socket_send(void *opaque)
3286 NetSocketState *s = opaque;
3287 int l, size, err;
3288 uint8_t buf1[4096];
3289 const uint8_t *buf;
3291 size = recv(s->fd, buf1, sizeof(buf1), 0);
3292 if (size < 0) {
3293 err = socket_error();
3294 if (err != EWOULDBLOCK)
3295 goto eoc;
3296 } else if (size == 0) {
3297 /* end of connection */
3298 eoc:
3299 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3300 closesocket(s->fd);
3301 return;
3303 buf = buf1;
3304 while (size > 0) {
3305 /* reassemble a packet from the network */
3306 switch(s->state) {
3307 case 0:
3308 l = 4 - s->index;
3309 if (l > size)
3310 l = size;
3311 memcpy(s->buf + s->index, buf, l);
3312 buf += l;
3313 size -= l;
3314 s->index += l;
3315 if (s->index == 4) {
3316 /* got length */
3317 s->packet_len = ntohl(*(uint32_t *)s->buf);
3318 s->index = 0;
3319 s->state = 1;
3321 break;
3322 case 1:
3323 l = s->packet_len - s->index;
3324 if (l > size)
3325 l = size;
3326 memcpy(s->buf + s->index, buf, l);
3327 s->index += l;
3328 buf += l;
3329 size -= l;
3330 if (s->index >= s->packet_len) {
3331 qemu_send_packet(s->vc, s->buf, s->packet_len);
3332 s->index = 0;
3333 s->state = 0;
3335 break;
3340 static void net_socket_send_dgram(void *opaque)
3342 NetSocketState *s = opaque;
3343 int size;
3345 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3346 if (size < 0)
3347 return;
3348 if (size == 0) {
3349 /* end of connection */
3350 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3351 return;
3353 qemu_send_packet(s->vc, s->buf, size);
3356 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3358 struct ip_mreq imr;
3359 int fd;
3360 int val, ret;
3361 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3362 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3363 inet_ntoa(mcastaddr->sin_addr),
3364 (int)ntohl(mcastaddr->sin_addr.s_addr));
3365 return -1;
3368 fd = socket(PF_INET, SOCK_DGRAM, 0);
3369 if (fd < 0) {
3370 perror("socket(PF_INET, SOCK_DGRAM)");
3371 return -1;
3374 val = 1;
3375 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3376 (const char *)&val, sizeof(val));
3377 if (ret < 0) {
3378 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3379 goto fail;
3382 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3383 if (ret < 0) {
3384 perror("bind");
3385 goto fail;
3388 /* Add host to multicast group */
3389 imr.imr_multiaddr = mcastaddr->sin_addr;
3390 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3392 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3393 (const char *)&imr, sizeof(struct ip_mreq));
3394 if (ret < 0) {
3395 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3396 goto fail;
3399 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3400 val = 1;
3401 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3402 (const char *)&val, sizeof(val));
3403 if (ret < 0) {
3404 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3405 goto fail;
3408 socket_set_nonblock(fd);
3409 return fd;
3410 fail:
3411 if (fd >= 0)
3412 closesocket(fd);
3413 return -1;
3416 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3417 int is_connected)
3419 struct sockaddr_in saddr;
3420 int newfd;
3421 socklen_t saddr_len;
3422 NetSocketState *s;
3424 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3425 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3426 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3429 if (is_connected) {
3430 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3431 /* must be bound */
3432 if (saddr.sin_addr.s_addr==0) {
3433 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3434 fd);
3435 return NULL;
3437 /* clone dgram socket */
3438 newfd = net_socket_mcast_create(&saddr);
3439 if (newfd < 0) {
3440 /* error already reported by net_socket_mcast_create() */
3441 close(fd);
3442 return NULL;
3444 /* clone newfd to fd, close newfd */
3445 dup2(newfd, fd);
3446 close(newfd);
3448 } else {
3449 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3450 fd, strerror(errno));
3451 return NULL;
3455 s = qemu_mallocz(sizeof(NetSocketState));
3456 if (!s)
3457 return NULL;
3458 s->fd = fd;
3460 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3461 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3463 /* mcast: save bound address as dst */
3464 if (is_connected) s->dgram_dst=saddr;
3466 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3467 "socket: fd=%d (%s mcast=%s:%d)",
3468 fd, is_connected? "cloned" : "",
3469 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3470 return s;
3473 static void net_socket_connect(void *opaque)
3475 NetSocketState *s = opaque;
3476 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3479 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3480 int is_connected)
3482 NetSocketState *s;
3483 s = qemu_mallocz(sizeof(NetSocketState));
3484 if (!s)
3485 return NULL;
3486 s->fd = fd;
3487 s->vc = qemu_new_vlan_client(vlan,
3488 net_socket_receive, NULL, s);
3489 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3490 "socket: fd=%d", fd);
3491 if (is_connected) {
3492 net_socket_connect(s);
3493 } else {
3494 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3496 return s;
3499 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3500 int is_connected)
3502 int so_type=-1, optlen=sizeof(so_type);
3504 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3505 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3506 return NULL;
3508 switch(so_type) {
3509 case SOCK_DGRAM:
3510 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3511 case SOCK_STREAM:
3512 return net_socket_fd_init_stream(vlan, fd, is_connected);
3513 default:
3514 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3515 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3516 return net_socket_fd_init_stream(vlan, fd, is_connected);
3518 return NULL;
3521 static void net_socket_accept(void *opaque)
3523 NetSocketListenState *s = opaque;
3524 NetSocketState *s1;
3525 struct sockaddr_in saddr;
3526 socklen_t len;
3527 int fd;
3529 for(;;) {
3530 len = sizeof(saddr);
3531 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3532 if (fd < 0 && errno != EINTR) {
3533 return;
3534 } else if (fd >= 0) {
3535 break;
3538 s1 = net_socket_fd_init(s->vlan, fd, 1);
3539 if (!s1) {
3540 closesocket(fd);
3541 } else {
3542 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3543 "socket: connection from %s:%d",
3544 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3548 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3550 NetSocketListenState *s;
3551 int fd, val, ret;
3552 struct sockaddr_in saddr;
3554 if (parse_host_port(&saddr, host_str) < 0)
3555 return -1;
3557 s = qemu_mallocz(sizeof(NetSocketListenState));
3558 if (!s)
3559 return -1;
3561 fd = socket(PF_INET, SOCK_STREAM, 0);
3562 if (fd < 0) {
3563 perror("socket");
3564 return -1;
3566 socket_set_nonblock(fd);
3568 /* allow fast reuse */
3569 val = 1;
3570 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3572 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3573 if (ret < 0) {
3574 perror("bind");
3575 return -1;
3577 ret = listen(fd, 0);
3578 if (ret < 0) {
3579 perror("listen");
3580 return -1;
3582 s->vlan = vlan;
3583 s->fd = fd;
3584 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3585 return 0;
3588 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3590 NetSocketState *s;
3591 int fd, connected, ret, err;
3592 struct sockaddr_in saddr;
3594 if (parse_host_port(&saddr, host_str) < 0)
3595 return -1;
3597 fd = socket(PF_INET, SOCK_STREAM, 0);
3598 if (fd < 0) {
3599 perror("socket");
3600 return -1;
3602 socket_set_nonblock(fd);
3604 connected = 0;
3605 for(;;) {
3606 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3607 if (ret < 0) {
3608 err = socket_error();
3609 if (err == EINTR || err == EWOULDBLOCK) {
3610 } else if (err == EINPROGRESS) {
3611 break;
3612 } else {
3613 perror("connect");
3614 closesocket(fd);
3615 return -1;
3617 } else {
3618 connected = 1;
3619 break;
3622 s = net_socket_fd_init(vlan, fd, connected);
3623 if (!s)
3624 return -1;
3625 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3626 "socket: connect to %s:%d",
3627 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3628 return 0;
3631 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3633 NetSocketState *s;
3634 int fd;
3635 struct sockaddr_in saddr;
3637 if (parse_host_port(&saddr, host_str) < 0)
3638 return -1;
3641 fd = net_socket_mcast_create(&saddr);
3642 if (fd < 0)
3643 return -1;
3645 s = net_socket_fd_init(vlan, fd, 0);
3646 if (!s)
3647 return -1;
3649 s->dgram_dst = saddr;
3651 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3652 "socket: mcast=%s:%d",
3653 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3654 return 0;
3658 static int get_param_value(char *buf, int buf_size,
3659 const char *tag, const char *str)
3661 const char *p;
3662 char *q;
3663 char option[128];
3665 p = str;
3666 for(;;) {
3667 q = option;
3668 while (*p != '\0' && *p != '=') {
3669 if ((q - option) < sizeof(option) - 1)
3670 *q++ = *p;
3671 p++;
3673 *q = '\0';
3674 if (*p != '=')
3675 break;
3676 p++;
3677 if (!strcmp(tag, option)) {
3678 q = buf;
3679 while (*p != '\0' && *p != ',') {
3680 if ((q - buf) < buf_size - 1)
3681 *q++ = *p;
3682 p++;
3684 *q = '\0';
3685 return q - buf;
3686 } else {
3687 while (*p != '\0' && *p != ',') {
3688 p++;
3691 if (*p != ',')
3692 break;
3693 p++;
3695 return 0;
3698 static int net_client_init(const char *str)
3700 const char *p;
3701 char *q;
3702 char device[64];
3703 char buf[1024];
3704 int vlan_id, ret;
3705 VLANState *vlan;
3707 p = str;
3708 q = device;
3709 while (*p != '\0' && *p != ',') {
3710 if ((q - device) < sizeof(device) - 1)
3711 *q++ = *p;
3712 p++;
3714 *q = '\0';
3715 if (*p == ',')
3716 p++;
3717 vlan_id = 0;
3718 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3719 vlan_id = strtol(buf, NULL, 0);
3721 vlan = qemu_find_vlan(vlan_id);
3722 if (!vlan) {
3723 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3724 return -1;
3726 if (!strcmp(device, "nic")) {
3727 NICInfo *nd;
3728 uint8_t *macaddr;
3730 if (nb_nics >= MAX_NICS) {
3731 fprintf(stderr, "Too Many NICs\n");
3732 return -1;
3734 nd = &nd_table[nb_nics];
3735 macaddr = nd->macaddr;
3736 macaddr[0] = 0x52;
3737 macaddr[1] = 0x54;
3738 macaddr[2] = 0x00;
3739 macaddr[3] = 0x12;
3740 macaddr[4] = 0x34;
3741 macaddr[5] = 0x56 + nb_nics;
3743 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3744 if (parse_macaddr(macaddr, buf) < 0) {
3745 fprintf(stderr, "invalid syntax for ethernet address\n");
3746 return -1;
3749 if (get_param_value(buf, sizeof(buf), "model", p)) {
3750 nd->model = strdup(buf);
3752 nd->vlan = vlan;
3753 nb_nics++;
3754 ret = 0;
3755 } else
3756 if (!strcmp(device, "none")) {
3757 /* does nothing. It is needed to signal that no network cards
3758 are wanted */
3759 ret = 0;
3760 } else
3761 #ifdef CONFIG_SLIRP
3762 if (!strcmp(device, "user")) {
3763 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3764 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3766 ret = net_slirp_init(vlan);
3767 } else
3768 #endif
3769 #ifdef _WIN32
3770 if (!strcmp(device, "tap")) {
3771 char ifname[64];
3772 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3773 fprintf(stderr, "tap: no interface name\n");
3774 return -1;
3776 ret = tap_win32_init(vlan, ifname);
3777 } else
3778 #else
3779 if (!strcmp(device, "tap")) {
3780 char ifname[64];
3781 char setup_script[1024];
3782 int fd;
3783 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3784 fd = strtol(buf, NULL, 0);
3785 ret = -1;
3786 if (net_tap_fd_init(vlan, fd))
3787 ret = 0;
3788 } else {
3789 get_param_value(ifname, sizeof(ifname), "ifname", p);
3790 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3791 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3793 ret = net_tap_init(vlan, ifname, setup_script);
3795 } else
3796 #endif
3797 if (!strcmp(device, "socket")) {
3798 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3799 int fd;
3800 fd = strtol(buf, NULL, 0);
3801 ret = -1;
3802 if (net_socket_fd_init(vlan, fd, 1))
3803 ret = 0;
3804 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3805 ret = net_socket_listen_init(vlan, buf);
3806 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3807 ret = net_socket_connect_init(vlan, buf);
3808 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3809 ret = net_socket_mcast_init(vlan, buf);
3810 } else {
3811 fprintf(stderr, "Unknown socket options: %s\n", p);
3812 return -1;
3814 } else
3816 fprintf(stderr, "Unknown network device: %s\n", device);
3817 return -1;
3819 if (ret < 0) {
3820 fprintf(stderr, "Could not initialize device '%s'\n", device);
3823 return ret;
3826 void do_info_network(void)
3828 VLANState *vlan;
3829 VLANClientState *vc;
3831 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3832 term_printf("VLAN %d devices:\n", vlan->id);
3833 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3834 term_printf(" %s\n", vc->info_str);
3838 /* Parse IDE and SCSI disk options */
3839 static int disk_options_init(int num_ide_disks,
3840 char ide_disk_options[][DISK_OPTIONS_SIZE],
3841 int snapshot,
3842 int num_scsi_disks,
3843 char scsi_disk_options[][DISK_OPTIONS_SIZE],
3844 int cdrom_index,
3845 int cyls,
3846 int heads,
3847 int secs,
3848 int translation)
3850 char buf[256];
3851 char dev_name[64];
3852 int id, i, j;
3853 int cdrom_device;
3854 int ide_cdrom_created = 0;
3855 int scsi_index;
3856 scsi_host_adapters temp_adapter;
3858 /* Process any IDE disks/cdroms */
3859 for (i=0; i< num_ide_disks; i++) {
3860 for (j=0; j<MAX_DISKS; j++) {
3861 if (ide_disk_options[j][0] == '\0')
3862 continue;
3864 if (get_param_value(buf, sizeof(buf),"type",ide_disk_options[j])) {
3865 if (!strcmp(buf, "disk")) {
3866 cdrom_device = 0;
3867 } else if (!strcmp(buf, "cdrom")) {
3868 cdrom_device = 1;
3869 ide_cdrom_created = 1;
3870 } else {
3871 fprintf(stderr, "qemu: invalid IDE disk type= value: %s\n", buf);
3872 return -1;
3874 } else {
3875 cdrom_device = 0;
3878 if (cdrom_device) {
3879 snprintf(dev_name, sizeof(dev_name), "cdrom%c", i);
3880 } else {
3881 snprintf(dev_name, sizeof(dev_name), "hd%c", i + 'a');
3884 if (!(get_param_value(buf, sizeof(buf),"img",ide_disk_options[j]))) {
3885 fprintf(stderr, "qemu: missing IDE disk img= value.\n");
3886 return -1;
3889 if (!(bs_table[i] = bdrv_new(dev_name))) {
3890 fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
3891 return -1;
3894 if (cdrom_device) {
3895 bdrv_set_type_hint(bs_table[i], BDRV_TYPE_CDROM);
3898 if (bdrv_open(bs_table[i], buf, snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
3899 fprintf(stderr, "qemu: could not open hard disk image: '%s'\n",
3900 buf);
3901 return -1;
3903 if (i == 0 && cyls != 0) {
3904 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3905 bdrv_set_translation_hint(bs_table[i], translation);
3907 ide_disk_options[j][0] = '\0';
3909 if (i == cdrom_index) {
3910 cdrom_index = -1;
3912 break; /* finished with this IDE device*/
3916 if (cdrom_index >= 0 && (!ide_cdrom_created)) {
3917 bs_table[cdrom_index] = bdrv_new("cdrom");
3918 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
3921 for(i = 0; i < num_scsi_disks; i++) {
3923 temp_adapter = SCSI_LSI_53C895A;
3924 scsi_hba_lsi++;
3926 /*Check for sdx= parameter */
3927 if (get_param_value(buf, sizeof(buf), "sdx", scsi_disk_options[i])) {
3928 if (buf[0] >= 'a' && buf[0] <= 'g') {
3929 scsi_index = buf[0] - 'a';
3930 } else{
3931 fprintf(stderr, "qemu: sdx= option for SCSI must be one letter from a-g. %s \n",buf);
3932 exit(1);
3934 } else {
3935 scsi_index = 0;
3938 /* Check for SCSI id specified. */
3939 if (get_param_value(buf, sizeof(buf),"id",scsi_disk_options[i])) {
3940 id = strtol(buf, NULL, 0);
3941 if (id < 0 || id > 6) {
3942 fprintf(stderr, "qemu: SCSI id must be from 0-6: %d\n", id);
3943 return -1;
3945 /* Check if id already used */
3946 for(j = 0; j < MAX_SCSI_DISKS; j++) {
3947 if (scsi_disks_info[j].device_type != SCSI_NONE &&
3948 j != i &&
3949 scsi_disks_info[j].adapter == temp_adapter &&
3950 scsi_disks_info[j].id == id ) {
3951 fprintf(stderr, "qemu: SCSI id already used: %u\n", id);
3952 return -1;
3955 } else {
3956 id = -1;
3958 scsi_disks_info[i].adapter = temp_adapter;
3959 scsi_disks_info[i].id = id;
3961 if (get_param_value(buf, sizeof(buf),"type",scsi_disk_options[i])) {
3962 if (!strcmp(buf, "disk")) {
3963 cdrom_device = 0;
3964 } else if (!strcmp(buf, "cdrom")) {
3965 cdrom_device = 1;
3966 } else {
3967 fprintf(stderr, "qemu: invalid SCSI disk type= value: %s\n", buf);
3968 return -1;
3970 } else {
3971 cdrom_device = 0;
3974 if (cdrom_device) {
3975 snprintf(dev_name, sizeof(buf), "cdrom%c", scsi_index);
3976 scsi_disks_info[scsi_index].device_type = SCSI_CDROM;
3977 } else {
3978 snprintf(dev_name, sizeof(buf), "sd%c", scsi_index + 'a');
3979 scsi_disks_info[scsi_index].device_type = SCSI_DISK;
3982 if (!(bs_scsi_table[scsi_index] = bdrv_new(dev_name))) {
3983 fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
3984 return -1;
3987 /* Get image filename from options and then try to open it */
3988 if (get_param_value(buf, sizeof(buf),"img",scsi_disk_options[i])) {
3989 if (bdrv_open(bs_scsi_table[scsi_index], buf, 0) < 0) {
3990 fprintf(stderr, "qemu: could not open SCSI disk image img='%s'\n",buf);
3991 return -1;
3993 } else {
3994 fprintf(stderr, "qemu: SCSI disk image not specified for sd%c \n", i + 'a');
3995 return -1;
3999 return 0;
4003 /***********************************************************/
4004 /* USB devices */
4006 static USBPort *used_usb_ports;
4007 static USBPort *free_usb_ports;
4009 /* ??? Maybe change this to register a hub to keep track of the topology. */
4010 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4011 usb_attachfn attach)
4013 port->opaque = opaque;
4014 port->index = index;
4015 port->attach = attach;
4016 port->next = free_usb_ports;
4017 free_usb_ports = port;
4020 static int usb_device_add(const char *devname)
4022 const char *p;
4023 USBDevice *dev;
4024 USBPort *port;
4026 if (!free_usb_ports)
4027 return -1;
4029 if (strstart(devname, "host:", &p)) {
4030 dev = usb_host_device_open(p);
4031 } else if (!strcmp(devname, "mouse")) {
4032 dev = usb_mouse_init();
4033 } else if (!strcmp(devname, "tablet")) {
4034 dev = usb_tablet_init();
4035 } else if (strstart(devname, "disk:", &p)) {
4036 dev = usb_msd_init(p);
4037 } else {
4038 return -1;
4040 if (!dev)
4041 return -1;
4043 /* Find a USB port to add the device to. */
4044 port = free_usb_ports;
4045 if (!port->next) {
4046 USBDevice *hub;
4048 /* Create a new hub and chain it on. */
4049 free_usb_ports = NULL;
4050 port->next = used_usb_ports;
4051 used_usb_ports = port;
4053 hub = usb_hub_init(VM_USB_HUB_SIZE);
4054 usb_attach(port, hub);
4055 port = free_usb_ports;
4058 free_usb_ports = port->next;
4059 port->next = used_usb_ports;
4060 used_usb_ports = port;
4061 usb_attach(port, dev);
4062 return 0;
4065 static int usb_device_del(const char *devname)
4067 USBPort *port;
4068 USBPort **lastp;
4069 USBDevice *dev;
4070 int bus_num, addr;
4071 const char *p;
4073 if (!used_usb_ports)
4074 return -1;
4076 p = strchr(devname, '.');
4077 if (!p)
4078 return -1;
4079 bus_num = strtoul(devname, NULL, 0);
4080 addr = strtoul(p + 1, NULL, 0);
4081 if (bus_num != 0)
4082 return -1;
4084 lastp = &used_usb_ports;
4085 port = used_usb_ports;
4086 while (port && port->dev->addr != addr) {
4087 lastp = &port->next;
4088 port = port->next;
4091 if (!port)
4092 return -1;
4094 dev = port->dev;
4095 *lastp = port->next;
4096 usb_attach(port, NULL);
4097 dev->handle_destroy(dev);
4098 port->next = free_usb_ports;
4099 free_usb_ports = port;
4100 return 0;
4103 void do_usb_add(const char *devname)
4105 int ret;
4106 ret = usb_device_add(devname);
4107 if (ret < 0)
4108 term_printf("Could not add USB device '%s'\n", devname);
4111 void do_usb_del(const char *devname)
4113 int ret;
4114 ret = usb_device_del(devname);
4115 if (ret < 0)
4116 term_printf("Could not remove USB device '%s'\n", devname);
4119 void usb_info(void)
4121 USBDevice *dev;
4122 USBPort *port;
4123 const char *speed_str;
4125 if (!usb_enabled) {
4126 term_printf("USB support not enabled\n");
4127 return;
4130 for (port = used_usb_ports; port; port = port->next) {
4131 dev = port->dev;
4132 if (!dev)
4133 continue;
4134 switch(dev->speed) {
4135 case USB_SPEED_LOW:
4136 speed_str = "1.5";
4137 break;
4138 case USB_SPEED_FULL:
4139 speed_str = "12";
4140 break;
4141 case USB_SPEED_HIGH:
4142 speed_str = "480";
4143 break;
4144 default:
4145 speed_str = "?";
4146 break;
4148 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4149 0, dev->addr, speed_str, dev->devname);
4153 /***********************************************************/
4154 /* pid file */
4156 static char *pid_filename;
4158 /* Remove PID file. Called on normal exit */
4160 static void remove_pidfile(void)
4162 unlink (pid_filename);
4165 static void create_pidfile(const char *filename)
4167 struct stat pidstat;
4168 FILE *f;
4170 /* Try to write our PID to the named file */
4171 if (stat(filename, &pidstat) < 0) {
4172 if (errno == ENOENT) {
4173 if ((f = fopen (filename, "w")) == NULL) {
4174 perror("Opening pidfile");
4175 exit(1);
4177 fprintf(f, "%d\n", getpid());
4178 fclose(f);
4179 pid_filename = qemu_strdup(filename);
4180 if (!pid_filename) {
4181 fprintf(stderr, "Could not save PID filename");
4182 exit(1);
4184 atexit(remove_pidfile);
4186 } else {
4187 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4188 filename);
4189 exit(1);
4193 /***********************************************************/
4194 /* dumb display */
4196 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4200 static void dumb_resize(DisplayState *ds, int w, int h)
4204 static void dumb_refresh(DisplayState *ds)
4206 vga_hw_update();
4209 void dumb_display_init(DisplayState *ds)
4211 ds->data = NULL;
4212 ds->linesize = 0;
4213 ds->depth = 0;
4214 ds->dpy_update = dumb_update;
4215 ds->dpy_resize = dumb_resize;
4216 ds->dpy_refresh = dumb_refresh;
4219 /***********************************************************/
4220 /* I/O handling */
4222 #define MAX_IO_HANDLERS 64
4224 typedef struct IOHandlerRecord {
4225 int fd;
4226 IOCanRWHandler *fd_read_poll;
4227 IOHandler *fd_read;
4228 IOHandler *fd_write;
4229 void *opaque;
4230 /* temporary data */
4231 struct pollfd *ufd;
4232 struct IOHandlerRecord *next;
4233 } IOHandlerRecord;
4235 static IOHandlerRecord *first_io_handler;
4237 /* XXX: fd_read_poll should be suppressed, but an API change is
4238 necessary in the character devices to suppress fd_can_read(). */
4239 int qemu_set_fd_handler2(int fd,
4240 IOCanRWHandler *fd_read_poll,
4241 IOHandler *fd_read,
4242 IOHandler *fd_write,
4243 void *opaque)
4245 IOHandlerRecord **pioh, *ioh;
4247 if (!fd_read && !fd_write) {
4248 pioh = &first_io_handler;
4249 for(;;) {
4250 ioh = *pioh;
4251 if (ioh == NULL)
4252 break;
4253 if (ioh->fd == fd) {
4254 *pioh = ioh->next;
4255 qemu_free(ioh);
4256 break;
4258 pioh = &ioh->next;
4260 } else {
4261 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4262 if (ioh->fd == fd)
4263 goto found;
4265 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4266 if (!ioh)
4267 return -1;
4268 ioh->next = first_io_handler;
4269 first_io_handler = ioh;
4270 found:
4271 ioh->fd = fd;
4272 ioh->fd_read_poll = fd_read_poll;
4273 ioh->fd_read = fd_read;
4274 ioh->fd_write = fd_write;
4275 ioh->opaque = opaque;
4277 return 0;
4280 int qemu_set_fd_handler(int fd,
4281 IOHandler *fd_read,
4282 IOHandler *fd_write,
4283 void *opaque)
4285 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4288 /***********************************************************/
4289 /* Polling handling */
4291 typedef struct PollingEntry {
4292 PollingFunc *func;
4293 void *opaque;
4294 struct PollingEntry *next;
4295 } PollingEntry;
4297 static PollingEntry *first_polling_entry;
4299 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4301 PollingEntry **ppe, *pe;
4302 pe = qemu_mallocz(sizeof(PollingEntry));
4303 if (!pe)
4304 return -1;
4305 pe->func = func;
4306 pe->opaque = opaque;
4307 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4308 *ppe = pe;
4309 return 0;
4312 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4314 PollingEntry **ppe, *pe;
4315 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4316 pe = *ppe;
4317 if (pe->func == func && pe->opaque == opaque) {
4318 *ppe = pe->next;
4319 qemu_free(pe);
4320 break;
4325 #ifdef _WIN32
4326 /***********************************************************/
4327 /* Wait objects support */
4328 typedef struct WaitObjects {
4329 int num;
4330 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4331 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4332 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4333 } WaitObjects;
4335 static WaitObjects wait_objects = {0};
4337 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4339 WaitObjects *w = &wait_objects;
4341 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4342 return -1;
4343 w->events[w->num] = handle;
4344 w->func[w->num] = func;
4345 w->opaque[w->num] = opaque;
4346 w->num++;
4347 return 0;
4350 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4352 int i, found;
4353 WaitObjects *w = &wait_objects;
4355 found = 0;
4356 for (i = 0; i < w->num; i++) {
4357 if (w->events[i] == handle)
4358 found = 1;
4359 if (found) {
4360 w->events[i] = w->events[i + 1];
4361 w->func[i] = w->func[i + 1];
4362 w->opaque[i] = w->opaque[i + 1];
4365 if (found)
4366 w->num--;
4368 #endif
4370 /***********************************************************/
4371 /* savevm/loadvm support */
4373 #define IO_BUF_SIZE 32768
4375 struct QEMUFile {
4376 FILE *outfile;
4377 BlockDriverState *bs;
4378 int is_file;
4379 int is_writable;
4380 int64_t base_offset;
4381 int64_t buf_offset; /* start of buffer when writing, end of buffer
4382 when reading */
4383 int buf_index;
4384 int buf_size; /* 0 when writing */
4385 uint8_t buf[IO_BUF_SIZE];
4388 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4390 QEMUFile *f;
4392 f = qemu_mallocz(sizeof(QEMUFile));
4393 if (!f)
4394 return NULL;
4395 if (!strcmp(mode, "wb")) {
4396 f->is_writable = 1;
4397 } else if (!strcmp(mode, "rb")) {
4398 f->is_writable = 0;
4399 } else {
4400 goto fail;
4402 f->outfile = fopen(filename, mode);
4403 if (!f->outfile)
4404 goto fail;
4405 f->is_file = 1;
4406 return f;
4407 fail:
4408 if (f->outfile)
4409 fclose(f->outfile);
4410 qemu_free(f);
4411 return NULL;
4414 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4416 QEMUFile *f;
4418 f = qemu_mallocz(sizeof(QEMUFile));
4419 if (!f)
4420 return NULL;
4421 f->is_file = 0;
4422 f->bs = bs;
4423 f->is_writable = is_writable;
4424 f->base_offset = offset;
4425 return f;
4428 void qemu_fflush(QEMUFile *f)
4430 if (!f->is_writable)
4431 return;
4432 if (f->buf_index > 0) {
4433 if (f->is_file) {
4434 fseek(f->outfile, f->buf_offset, SEEK_SET);
4435 fwrite(f->buf, 1, f->buf_index, f->outfile);
4436 } else {
4437 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4438 f->buf, f->buf_index);
4440 f->buf_offset += f->buf_index;
4441 f->buf_index = 0;
4445 static void qemu_fill_buffer(QEMUFile *f)
4447 int len;
4449 if (f->is_writable)
4450 return;
4451 if (f->is_file) {
4452 fseek(f->outfile, f->buf_offset, SEEK_SET);
4453 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4454 if (len < 0)
4455 len = 0;
4456 } else {
4457 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4458 f->buf, IO_BUF_SIZE);
4459 if (len < 0)
4460 len = 0;
4462 f->buf_index = 0;
4463 f->buf_size = len;
4464 f->buf_offset += len;
4467 void qemu_fclose(QEMUFile *f)
4469 if (f->is_writable)
4470 qemu_fflush(f);
4471 if (f->is_file) {
4472 fclose(f->outfile);
4474 qemu_free(f);
4477 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4479 int l;
4480 while (size > 0) {
4481 l = IO_BUF_SIZE - f->buf_index;
4482 if (l > size)
4483 l = size;
4484 memcpy(f->buf + f->buf_index, buf, l);
4485 f->buf_index += l;
4486 buf += l;
4487 size -= l;
4488 if (f->buf_index >= IO_BUF_SIZE)
4489 qemu_fflush(f);
4493 void qemu_put_byte(QEMUFile *f, int v)
4495 f->buf[f->buf_index++] = v;
4496 if (f->buf_index >= IO_BUF_SIZE)
4497 qemu_fflush(f);
4500 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4502 int size, l;
4504 size = size1;
4505 while (size > 0) {
4506 l = f->buf_size - f->buf_index;
4507 if (l == 0) {
4508 qemu_fill_buffer(f);
4509 l = f->buf_size - f->buf_index;
4510 if (l == 0)
4511 break;
4513 if (l > size)
4514 l = size;
4515 memcpy(buf, f->buf + f->buf_index, l);
4516 f->buf_index += l;
4517 buf += l;
4518 size -= l;
4520 return size1 - size;
4523 int qemu_get_byte(QEMUFile *f)
4525 if (f->buf_index >= f->buf_size) {
4526 qemu_fill_buffer(f);
4527 if (f->buf_index >= f->buf_size)
4528 return 0;
4530 return f->buf[f->buf_index++];
4533 int64_t qemu_ftell(QEMUFile *f)
4535 return f->buf_offset - f->buf_size + f->buf_index;
4538 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4540 if (whence == SEEK_SET) {
4541 /* nothing to do */
4542 } else if (whence == SEEK_CUR) {
4543 pos += qemu_ftell(f);
4544 } else {
4545 /* SEEK_END not supported */
4546 return -1;
4548 if (f->is_writable) {
4549 qemu_fflush(f);
4550 f->buf_offset = pos;
4551 } else {
4552 f->buf_offset = pos;
4553 f->buf_index = 0;
4554 f->buf_size = 0;
4556 return pos;
4559 void qemu_put_be16(QEMUFile *f, unsigned int v)
4561 qemu_put_byte(f, v >> 8);
4562 qemu_put_byte(f, v);
4565 void qemu_put_be32(QEMUFile *f, unsigned int v)
4567 qemu_put_byte(f, v >> 24);
4568 qemu_put_byte(f, v >> 16);
4569 qemu_put_byte(f, v >> 8);
4570 qemu_put_byte(f, v);
4573 void qemu_put_be64(QEMUFile *f, uint64_t v)
4575 qemu_put_be32(f, v >> 32);
4576 qemu_put_be32(f, v);
4579 unsigned int qemu_get_be16(QEMUFile *f)
4581 unsigned int v;
4582 v = qemu_get_byte(f) << 8;
4583 v |= qemu_get_byte(f);
4584 return v;
4587 unsigned int qemu_get_be32(QEMUFile *f)
4589 unsigned int v;
4590 v = qemu_get_byte(f) << 24;
4591 v |= qemu_get_byte(f) << 16;
4592 v |= qemu_get_byte(f) << 8;
4593 v |= qemu_get_byte(f);
4594 return v;
4597 uint64_t qemu_get_be64(QEMUFile *f)
4599 uint64_t v;
4600 v = (uint64_t)qemu_get_be32(f) << 32;
4601 v |= qemu_get_be32(f);
4602 return v;
4605 typedef struct SaveStateEntry {
4606 char idstr[256];
4607 int instance_id;
4608 int version_id;
4609 SaveStateHandler *save_state;
4610 LoadStateHandler *load_state;
4611 void *opaque;
4612 struct SaveStateEntry *next;
4613 } SaveStateEntry;
4615 static SaveStateEntry *first_se;
4617 int register_savevm(const char *idstr,
4618 int instance_id,
4619 int version_id,
4620 SaveStateHandler *save_state,
4621 LoadStateHandler *load_state,
4622 void *opaque)
4624 SaveStateEntry *se, **pse;
4626 se = qemu_malloc(sizeof(SaveStateEntry));
4627 if (!se)
4628 return -1;
4629 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4630 se->instance_id = instance_id;
4631 se->version_id = version_id;
4632 se->save_state = save_state;
4633 se->load_state = load_state;
4634 se->opaque = opaque;
4635 se->next = NULL;
4637 /* add at the end of list */
4638 pse = &first_se;
4639 while (*pse != NULL)
4640 pse = &(*pse)->next;
4641 *pse = se;
4642 return 0;
4645 #define QEMU_VM_FILE_MAGIC 0x5145564d
4646 #define QEMU_VM_FILE_VERSION 0x00000002
4648 int qemu_savevm_state(QEMUFile *f)
4650 SaveStateEntry *se;
4651 int len, ret;
4652 int64_t cur_pos, len_pos, total_len_pos;
4654 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4655 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4656 total_len_pos = qemu_ftell(f);
4657 qemu_put_be64(f, 0); /* total size */
4659 for(se = first_se; se != NULL; se = se->next) {
4660 /* ID string */
4661 len = strlen(se->idstr);
4662 qemu_put_byte(f, len);
4663 qemu_put_buffer(f, se->idstr, len);
4665 qemu_put_be32(f, se->instance_id);
4666 qemu_put_be32(f, se->version_id);
4668 /* record size: filled later */
4669 len_pos = qemu_ftell(f);
4670 qemu_put_be32(f, 0);
4672 se->save_state(f, se->opaque);
4674 /* fill record size */
4675 cur_pos = qemu_ftell(f);
4676 len = cur_pos - len_pos - 4;
4677 qemu_fseek(f, len_pos, SEEK_SET);
4678 qemu_put_be32(f, len);
4679 qemu_fseek(f, cur_pos, SEEK_SET);
4681 cur_pos = qemu_ftell(f);
4682 qemu_fseek(f, total_len_pos, SEEK_SET);
4683 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4684 qemu_fseek(f, cur_pos, SEEK_SET);
4686 ret = 0;
4687 return ret;
4690 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4692 SaveStateEntry *se;
4694 for(se = first_se; se != NULL; se = se->next) {
4695 if (!strcmp(se->idstr, idstr) &&
4696 instance_id == se->instance_id)
4697 return se;
4699 return NULL;
4702 int qemu_loadvm_state(QEMUFile *f)
4704 SaveStateEntry *se;
4705 int len, ret, instance_id, record_len, version_id;
4706 int64_t total_len, end_pos, cur_pos;
4707 unsigned int v;
4708 char idstr[256];
4710 v = qemu_get_be32(f);
4711 if (v != QEMU_VM_FILE_MAGIC)
4712 goto fail;
4713 v = qemu_get_be32(f);
4714 if (v != QEMU_VM_FILE_VERSION) {
4715 fail:
4716 ret = -1;
4717 goto the_end;
4719 total_len = qemu_get_be64(f);
4720 end_pos = total_len + qemu_ftell(f);
4721 for(;;) {
4722 if (qemu_ftell(f) >= end_pos)
4723 break;
4724 len = qemu_get_byte(f);
4725 qemu_get_buffer(f, idstr, len);
4726 idstr[len] = '\0';
4727 instance_id = qemu_get_be32(f);
4728 version_id = qemu_get_be32(f);
4729 record_len = qemu_get_be32(f);
4730 #if 0
4731 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4732 idstr, instance_id, version_id, record_len);
4733 #endif
4734 cur_pos = qemu_ftell(f);
4735 se = find_se(idstr, instance_id);
4736 if (!se) {
4737 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4738 instance_id, idstr);
4739 } else {
4740 ret = se->load_state(f, se->opaque, version_id);
4741 if (ret < 0) {
4742 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4743 instance_id, idstr);
4746 /* always seek to exact end of record */
4747 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4749 ret = 0;
4750 the_end:
4751 return ret;
4754 /* device can contain snapshots */
4755 static int bdrv_can_snapshot(BlockDriverState *bs)
4757 return (bs &&
4758 !bdrv_is_removable(bs) &&
4759 !bdrv_is_read_only(bs));
4762 /* device must be snapshots in order to have a reliable snapshot */
4763 static int bdrv_has_snapshot(BlockDriverState *bs)
4765 return (bs &&
4766 !bdrv_is_removable(bs) &&
4767 !bdrv_is_read_only(bs));
4770 static BlockDriverState *get_bs_snapshots(void)
4772 BlockDriverState *bs;
4773 int i;
4775 if (bs_snapshots)
4776 return bs_snapshots;
4777 for(i = 0; i <= MAX_DISKS; i++) {
4778 bs = bs_table[i];
4779 if (bdrv_can_snapshot(bs))
4780 goto ok;
4782 return NULL;
4784 bs_snapshots = bs;
4785 return bs;
4788 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4789 const char *name)
4791 QEMUSnapshotInfo *sn_tab, *sn;
4792 int nb_sns, i, ret;
4794 ret = -ENOENT;
4795 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4796 if (nb_sns < 0)
4797 return ret;
4798 for(i = 0; i < nb_sns; i++) {
4799 sn = &sn_tab[i];
4800 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4801 *sn_info = *sn;
4802 ret = 0;
4803 break;
4806 qemu_free(sn_tab);
4807 return ret;
4810 void do_savevm(const char *name)
4812 BlockDriverState *bs, *bs1;
4813 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4814 int must_delete, ret, i;
4815 BlockDriverInfo bdi1, *bdi = &bdi1;
4816 QEMUFile *f;
4817 int saved_vm_running;
4818 #ifdef _WIN32
4819 struct _timeb tb;
4820 #else
4821 struct timeval tv;
4822 #endif
4824 bs = get_bs_snapshots();
4825 if (!bs) {
4826 term_printf("No block device can accept snapshots\n");
4827 return;
4830 /* ??? Should this occur after vm_stop? */
4831 qemu_aio_flush();
4833 saved_vm_running = vm_running;
4834 vm_stop(0);
4836 must_delete = 0;
4837 if (name) {
4838 ret = bdrv_snapshot_find(bs, old_sn, name);
4839 if (ret >= 0) {
4840 must_delete = 1;
4843 memset(sn, 0, sizeof(*sn));
4844 if (must_delete) {
4845 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4846 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4847 } else {
4848 if (name)
4849 pstrcpy(sn->name, sizeof(sn->name), name);
4852 /* fill auxiliary fields */
4853 #ifdef _WIN32
4854 _ftime(&tb);
4855 sn->date_sec = tb.time;
4856 sn->date_nsec = tb.millitm * 1000000;
4857 #else
4858 gettimeofday(&tv, NULL);
4859 sn->date_sec = tv.tv_sec;
4860 sn->date_nsec = tv.tv_usec * 1000;
4861 #endif
4862 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4864 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4865 term_printf("Device %s does not support VM state snapshots\n",
4866 bdrv_get_device_name(bs));
4867 goto the_end;
4870 /* save the VM state */
4871 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4872 if (!f) {
4873 term_printf("Could not open VM state file\n");
4874 goto the_end;
4876 ret = qemu_savevm_state(f);
4877 sn->vm_state_size = qemu_ftell(f);
4878 qemu_fclose(f);
4879 if (ret < 0) {
4880 term_printf("Error %d while writing VM\n", ret);
4881 goto the_end;
4884 /* create the snapshots */
4886 for(i = 0; i < MAX_DISKS; i++) {
4887 bs1 = bs_table[i];
4888 if (bdrv_has_snapshot(bs1)) {
4889 if (must_delete) {
4890 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4891 if (ret < 0) {
4892 term_printf("Error while deleting snapshot on '%s'\n",
4893 bdrv_get_device_name(bs1));
4896 ret = bdrv_snapshot_create(bs1, sn);
4897 if (ret < 0) {
4898 term_printf("Error while creating snapshot on '%s'\n",
4899 bdrv_get_device_name(bs1));
4904 the_end:
4905 if (saved_vm_running)
4906 vm_start();
4909 void do_loadvm(const char *name)
4911 BlockDriverState *bs, *bs1;
4912 BlockDriverInfo bdi1, *bdi = &bdi1;
4913 QEMUFile *f;
4914 int i, ret;
4915 int saved_vm_running;
4917 bs = get_bs_snapshots();
4918 if (!bs) {
4919 term_printf("No block device supports snapshots\n");
4920 return;
4923 /* Flush all IO requests so they don't interfere with the new state. */
4924 qemu_aio_flush();
4926 saved_vm_running = vm_running;
4927 vm_stop(0);
4929 for(i = 0; i <= MAX_DISKS; i++) {
4930 bs1 = bs_table[i];
4931 if (bdrv_has_snapshot(bs1)) {
4932 ret = bdrv_snapshot_goto(bs1, name);
4933 if (ret < 0) {
4934 if (bs != bs1)
4935 term_printf("Warning: ");
4936 switch(ret) {
4937 case -ENOTSUP:
4938 term_printf("Snapshots not supported on device '%s'\n",
4939 bdrv_get_device_name(bs1));
4940 break;
4941 case -ENOENT:
4942 term_printf("Could not find snapshot '%s' on device '%s'\n",
4943 name, bdrv_get_device_name(bs1));
4944 break;
4945 default:
4946 term_printf("Error %d while activating snapshot on '%s'\n",
4947 ret, bdrv_get_device_name(bs1));
4948 break;
4950 /* fatal on snapshot block device */
4951 if (bs == bs1)
4952 goto the_end;
4957 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4958 term_printf("Device %s does not support VM state snapshots\n",
4959 bdrv_get_device_name(bs));
4960 return;
4963 /* restore the VM state */
4964 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4965 if (!f) {
4966 term_printf("Could not open VM state file\n");
4967 goto the_end;
4969 ret = qemu_loadvm_state(f);
4970 qemu_fclose(f);
4971 if (ret < 0) {
4972 term_printf("Error %d while loading VM state\n", ret);
4974 the_end:
4975 if (saved_vm_running)
4976 vm_start();
4979 void do_delvm(const char *name)
4981 BlockDriverState *bs, *bs1;
4982 int i, ret;
4984 bs = get_bs_snapshots();
4985 if (!bs) {
4986 term_printf("No block device supports snapshots\n");
4987 return;
4990 for(i = 0; i <= MAX_DISKS; i++) {
4991 bs1 = bs_table[i];
4992 if (bdrv_has_snapshot(bs1)) {
4993 ret = bdrv_snapshot_delete(bs1, name);
4994 if (ret < 0) {
4995 if (ret == -ENOTSUP)
4996 term_printf("Snapshots not supported on device '%s'\n",
4997 bdrv_get_device_name(bs1));
4998 else
4999 term_printf("Error %d while deleting snapshot on '%s'\n",
5000 ret, bdrv_get_device_name(bs1));
5006 void do_info_snapshots(void)
5008 BlockDriverState *bs, *bs1;
5009 QEMUSnapshotInfo *sn_tab, *sn;
5010 int nb_sns, i;
5011 char buf[256];
5013 bs = get_bs_snapshots();
5014 if (!bs) {
5015 term_printf("No available block device supports snapshots\n");
5016 return;
5018 term_printf("Snapshot devices:");
5019 for(i = 0; i <= MAX_DISKS; i++) {
5020 bs1 = bs_table[i];
5021 if (bdrv_has_snapshot(bs1)) {
5022 if (bs == bs1)
5023 term_printf(" %s", bdrv_get_device_name(bs1));
5026 term_printf("\n");
5028 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5029 if (nb_sns < 0) {
5030 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5031 return;
5033 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5034 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5035 for(i = 0; i < nb_sns; i++) {
5036 sn = &sn_tab[i];
5037 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5039 qemu_free(sn_tab);
5042 /***********************************************************/
5043 /* cpu save/restore */
5045 #if defined(TARGET_I386)
5047 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5049 qemu_put_be32(f, dt->selector);
5050 qemu_put_betl(f, dt->base);
5051 qemu_put_be32(f, dt->limit);
5052 qemu_put_be32(f, dt->flags);
5055 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5057 dt->selector = qemu_get_be32(f);
5058 dt->base = qemu_get_betl(f);
5059 dt->limit = qemu_get_be32(f);
5060 dt->flags = qemu_get_be32(f);
5063 void cpu_save(QEMUFile *f, void *opaque)
5065 CPUState *env = opaque;
5066 uint16_t fptag, fpus, fpuc, fpregs_format;
5067 uint32_t hflags;
5068 int i;
5070 for(i = 0; i < CPU_NB_REGS; i++)
5071 qemu_put_betls(f, &env->regs[i]);
5072 qemu_put_betls(f, &env->eip);
5073 qemu_put_betls(f, &env->eflags);
5074 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5075 qemu_put_be32s(f, &hflags);
5077 /* FPU */
5078 fpuc = env->fpuc;
5079 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5080 fptag = 0;
5081 for(i = 0; i < 8; i++) {
5082 fptag |= ((!env->fptags[i]) << i);
5085 qemu_put_be16s(f, &fpuc);
5086 qemu_put_be16s(f, &fpus);
5087 qemu_put_be16s(f, &fptag);
5089 #ifdef USE_X86LDOUBLE
5090 fpregs_format = 0;
5091 #else
5092 fpregs_format = 1;
5093 #endif
5094 qemu_put_be16s(f, &fpregs_format);
5096 for(i = 0; i < 8; i++) {
5097 #ifdef USE_X86LDOUBLE
5099 uint64_t mant;
5100 uint16_t exp;
5101 /* we save the real CPU data (in case of MMX usage only 'mant'
5102 contains the MMX register */
5103 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5104 qemu_put_be64(f, mant);
5105 qemu_put_be16(f, exp);
5107 #else
5108 /* if we use doubles for float emulation, we save the doubles to
5109 avoid losing information in case of MMX usage. It can give
5110 problems if the image is restored on a CPU where long
5111 doubles are used instead. */
5112 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5113 #endif
5116 for(i = 0; i < 6; i++)
5117 cpu_put_seg(f, &env->segs[i]);
5118 cpu_put_seg(f, &env->ldt);
5119 cpu_put_seg(f, &env->tr);
5120 cpu_put_seg(f, &env->gdt);
5121 cpu_put_seg(f, &env->idt);
5123 qemu_put_be32s(f, &env->sysenter_cs);
5124 qemu_put_be32s(f, &env->sysenter_esp);
5125 qemu_put_be32s(f, &env->sysenter_eip);
5127 qemu_put_betls(f, &env->cr[0]);
5128 qemu_put_betls(f, &env->cr[2]);
5129 qemu_put_betls(f, &env->cr[3]);
5130 qemu_put_betls(f, &env->cr[4]);
5132 for(i = 0; i < 8; i++)
5133 qemu_put_betls(f, &env->dr[i]);
5135 /* MMU */
5136 qemu_put_be32s(f, &env->a20_mask);
5138 /* XMM */
5139 qemu_put_be32s(f, &env->mxcsr);
5140 for(i = 0; i < CPU_NB_REGS; i++) {
5141 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5142 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5145 #ifdef TARGET_X86_64
5146 qemu_put_be64s(f, &env->efer);
5147 qemu_put_be64s(f, &env->star);
5148 qemu_put_be64s(f, &env->lstar);
5149 qemu_put_be64s(f, &env->cstar);
5150 qemu_put_be64s(f, &env->fmask);
5151 qemu_put_be64s(f, &env->kernelgsbase);
5152 #endif
5153 qemu_put_be32s(f, &env->smbase);
5156 #ifdef USE_X86LDOUBLE
5157 /* XXX: add that in a FPU generic layer */
5158 union x86_longdouble {
5159 uint64_t mant;
5160 uint16_t exp;
5163 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5164 #define EXPBIAS1 1023
5165 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5166 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5168 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5170 int e;
5171 /* mantissa */
5172 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5173 /* exponent + sign */
5174 e = EXPD1(temp) - EXPBIAS1 + 16383;
5175 e |= SIGND1(temp) >> 16;
5176 p->exp = e;
5178 #endif
5180 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5182 CPUState *env = opaque;
5183 int i, guess_mmx;
5184 uint32_t hflags;
5185 uint16_t fpus, fpuc, fptag, fpregs_format;
5187 if (version_id != 3 && version_id != 4)
5188 return -EINVAL;
5189 for(i = 0; i < CPU_NB_REGS; i++)
5190 qemu_get_betls(f, &env->regs[i]);
5191 qemu_get_betls(f, &env->eip);
5192 qemu_get_betls(f, &env->eflags);
5193 qemu_get_be32s(f, &hflags);
5195 qemu_get_be16s(f, &fpuc);
5196 qemu_get_be16s(f, &fpus);
5197 qemu_get_be16s(f, &fptag);
5198 qemu_get_be16s(f, &fpregs_format);
5200 /* NOTE: we cannot always restore the FPU state if the image come
5201 from a host with a different 'USE_X86LDOUBLE' define. We guess
5202 if we are in an MMX state to restore correctly in that case. */
5203 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5204 for(i = 0; i < 8; i++) {
5205 uint64_t mant;
5206 uint16_t exp;
5208 switch(fpregs_format) {
5209 case 0:
5210 mant = qemu_get_be64(f);
5211 exp = qemu_get_be16(f);
5212 #ifdef USE_X86LDOUBLE
5213 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5214 #else
5215 /* difficult case */
5216 if (guess_mmx)
5217 env->fpregs[i].mmx.MMX_Q(0) = mant;
5218 else
5219 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5220 #endif
5221 break;
5222 case 1:
5223 mant = qemu_get_be64(f);
5224 #ifdef USE_X86LDOUBLE
5226 union x86_longdouble *p;
5227 /* difficult case */
5228 p = (void *)&env->fpregs[i];
5229 if (guess_mmx) {
5230 p->mant = mant;
5231 p->exp = 0xffff;
5232 } else {
5233 fp64_to_fp80(p, mant);
5236 #else
5237 env->fpregs[i].mmx.MMX_Q(0) = mant;
5238 #endif
5239 break;
5240 default:
5241 return -EINVAL;
5245 env->fpuc = fpuc;
5246 /* XXX: restore FPU round state */
5247 env->fpstt = (fpus >> 11) & 7;
5248 env->fpus = fpus & ~0x3800;
5249 fptag ^= 0xff;
5250 for(i = 0; i < 8; i++) {
5251 env->fptags[i] = (fptag >> i) & 1;
5254 for(i = 0; i < 6; i++)
5255 cpu_get_seg(f, &env->segs[i]);
5256 cpu_get_seg(f, &env->ldt);
5257 cpu_get_seg(f, &env->tr);
5258 cpu_get_seg(f, &env->gdt);
5259 cpu_get_seg(f, &env->idt);
5261 qemu_get_be32s(f, &env->sysenter_cs);
5262 qemu_get_be32s(f, &env->sysenter_esp);
5263 qemu_get_be32s(f, &env->sysenter_eip);
5265 qemu_get_betls(f, &env->cr[0]);
5266 qemu_get_betls(f, &env->cr[2]);
5267 qemu_get_betls(f, &env->cr[3]);
5268 qemu_get_betls(f, &env->cr[4]);
5270 for(i = 0; i < 8; i++)
5271 qemu_get_betls(f, &env->dr[i]);
5273 /* MMU */
5274 qemu_get_be32s(f, &env->a20_mask);
5276 qemu_get_be32s(f, &env->mxcsr);
5277 for(i = 0; i < CPU_NB_REGS; i++) {
5278 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5279 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5282 #ifdef TARGET_X86_64
5283 qemu_get_be64s(f, &env->efer);
5284 qemu_get_be64s(f, &env->star);
5285 qemu_get_be64s(f, &env->lstar);
5286 qemu_get_be64s(f, &env->cstar);
5287 qemu_get_be64s(f, &env->fmask);
5288 qemu_get_be64s(f, &env->kernelgsbase);
5289 #endif
5290 if (version_id >= 4)
5291 qemu_get_be32s(f, &env->smbase);
5293 /* XXX: compute hflags from scratch, except for CPL and IIF */
5294 env->hflags = hflags;
5295 tlb_flush(env, 1);
5296 return 0;
5299 #elif defined(TARGET_PPC)
5300 void cpu_save(QEMUFile *f, void *opaque)
5304 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5306 return 0;
5309 #elif defined(TARGET_MIPS)
5310 void cpu_save(QEMUFile *f, void *opaque)
5314 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5316 return 0;
5319 #elif defined(TARGET_SPARC)
5320 void cpu_save(QEMUFile *f, void *opaque)
5322 CPUState *env = opaque;
5323 int i;
5324 uint32_t tmp;
5326 for(i = 0; i < 8; i++)
5327 qemu_put_betls(f, &env->gregs[i]);
5328 for(i = 0; i < NWINDOWS * 16; i++)
5329 qemu_put_betls(f, &env->regbase[i]);
5331 /* FPU */
5332 for(i = 0; i < TARGET_FPREGS; i++) {
5333 union {
5334 float32 f;
5335 uint32_t i;
5336 } u;
5337 u.f = env->fpr[i];
5338 qemu_put_be32(f, u.i);
5341 qemu_put_betls(f, &env->pc);
5342 qemu_put_betls(f, &env->npc);
5343 qemu_put_betls(f, &env->y);
5344 tmp = GET_PSR(env);
5345 qemu_put_be32(f, tmp);
5346 qemu_put_betls(f, &env->fsr);
5347 qemu_put_betls(f, &env->tbr);
5348 #ifndef TARGET_SPARC64
5349 qemu_put_be32s(f, &env->wim);
5350 /* MMU */
5351 for(i = 0; i < 16; i++)
5352 qemu_put_be32s(f, &env->mmuregs[i]);
5353 #endif
5356 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5358 CPUState *env = opaque;
5359 int i;
5360 uint32_t tmp;
5362 for(i = 0; i < 8; i++)
5363 qemu_get_betls(f, &env->gregs[i]);
5364 for(i = 0; i < NWINDOWS * 16; i++)
5365 qemu_get_betls(f, &env->regbase[i]);
5367 /* FPU */
5368 for(i = 0; i < TARGET_FPREGS; i++) {
5369 union {
5370 float32 f;
5371 uint32_t i;
5372 } u;
5373 u.i = qemu_get_be32(f);
5374 env->fpr[i] = u.f;
5377 qemu_get_betls(f, &env->pc);
5378 qemu_get_betls(f, &env->npc);
5379 qemu_get_betls(f, &env->y);
5380 tmp = qemu_get_be32(f);
5381 env->cwp = 0; /* needed to ensure that the wrapping registers are
5382 correctly updated */
5383 PUT_PSR(env, tmp);
5384 qemu_get_betls(f, &env->fsr);
5385 qemu_get_betls(f, &env->tbr);
5386 #ifndef TARGET_SPARC64
5387 qemu_get_be32s(f, &env->wim);
5388 /* MMU */
5389 for(i = 0; i < 16; i++)
5390 qemu_get_be32s(f, &env->mmuregs[i]);
5391 #endif
5392 tlb_flush(env, 1);
5393 return 0;
5396 #elif defined(TARGET_ARM)
5398 /* ??? Need to implement these. */
5399 void cpu_save(QEMUFile *f, void *opaque)
5403 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5405 return 0;
5408 #else
5410 #warning No CPU save/restore functions
5412 #endif
5414 /***********************************************************/
5415 /* ram save/restore */
5417 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5419 int v;
5421 v = qemu_get_byte(f);
5422 switch(v) {
5423 case 0:
5424 if (qemu_get_buffer(f, buf, len) != len)
5425 return -EIO;
5426 break;
5427 case 1:
5428 v = qemu_get_byte(f);
5429 memset(buf, v, len);
5430 break;
5431 default:
5432 return -EINVAL;
5434 return 0;
5437 static int ram_load_v1(QEMUFile *f, void *opaque)
5439 int i, ret;
5441 if (qemu_get_be32(f) != phys_ram_size)
5442 return -EINVAL;
5443 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5444 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5445 if (ret)
5446 return ret;
5448 return 0;
5451 #define BDRV_HASH_BLOCK_SIZE 1024
5452 #define IOBUF_SIZE 4096
5453 #define RAM_CBLOCK_MAGIC 0xfabe
5455 typedef struct RamCompressState {
5456 z_stream zstream;
5457 QEMUFile *f;
5458 uint8_t buf[IOBUF_SIZE];
5459 } RamCompressState;
5461 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5463 int ret;
5464 memset(s, 0, sizeof(*s));
5465 s->f = f;
5466 ret = deflateInit2(&s->zstream, 1,
5467 Z_DEFLATED, 15,
5468 9, Z_DEFAULT_STRATEGY);
5469 if (ret != Z_OK)
5470 return -1;
5471 s->zstream.avail_out = IOBUF_SIZE;
5472 s->zstream.next_out = s->buf;
5473 return 0;
5476 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5478 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5479 qemu_put_be16(s->f, len);
5480 qemu_put_buffer(s->f, buf, len);
5483 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5485 int ret;
5487 s->zstream.avail_in = len;
5488 s->zstream.next_in = (uint8_t *)buf;
5489 while (s->zstream.avail_in > 0) {
5490 ret = deflate(&s->zstream, Z_NO_FLUSH);
5491 if (ret != Z_OK)
5492 return -1;
5493 if (s->zstream.avail_out == 0) {
5494 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5495 s->zstream.avail_out = IOBUF_SIZE;
5496 s->zstream.next_out = s->buf;
5499 return 0;
5502 static void ram_compress_close(RamCompressState *s)
5504 int len, ret;
5506 /* compress last bytes */
5507 for(;;) {
5508 ret = deflate(&s->zstream, Z_FINISH);
5509 if (ret == Z_OK || ret == Z_STREAM_END) {
5510 len = IOBUF_SIZE - s->zstream.avail_out;
5511 if (len > 0) {
5512 ram_put_cblock(s, s->buf, len);
5514 s->zstream.avail_out = IOBUF_SIZE;
5515 s->zstream.next_out = s->buf;
5516 if (ret == Z_STREAM_END)
5517 break;
5518 } else {
5519 goto fail;
5522 fail:
5523 deflateEnd(&s->zstream);
5526 typedef struct RamDecompressState {
5527 z_stream zstream;
5528 QEMUFile *f;
5529 uint8_t buf[IOBUF_SIZE];
5530 } RamDecompressState;
5532 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5534 int ret;
5535 memset(s, 0, sizeof(*s));
5536 s->f = f;
5537 ret = inflateInit(&s->zstream);
5538 if (ret != Z_OK)
5539 return -1;
5540 return 0;
5543 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5545 int ret, clen;
5547 s->zstream.avail_out = len;
5548 s->zstream.next_out = buf;
5549 while (s->zstream.avail_out > 0) {
5550 if (s->zstream.avail_in == 0) {
5551 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5552 return -1;
5553 clen = qemu_get_be16(s->f);
5554 if (clen > IOBUF_SIZE)
5555 return -1;
5556 qemu_get_buffer(s->f, s->buf, clen);
5557 s->zstream.avail_in = clen;
5558 s->zstream.next_in = s->buf;
5560 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5561 if (ret != Z_OK && ret != Z_STREAM_END) {
5562 return -1;
5565 return 0;
5568 static void ram_decompress_close(RamDecompressState *s)
5570 inflateEnd(&s->zstream);
5573 static void ram_save(QEMUFile *f, void *opaque)
5575 int i;
5576 RamCompressState s1, *s = &s1;
5577 uint8_t buf[10];
5579 qemu_put_be32(f, phys_ram_size);
5580 if (ram_compress_open(s, f) < 0)
5581 return;
5582 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5583 #if 0
5584 if (tight_savevm_enabled) {
5585 int64_t sector_num;
5586 int j;
5588 /* find if the memory block is available on a virtual
5589 block device */
5590 sector_num = -1;
5591 for(j = 0; j < MAX_DISKS; j++) {
5592 if (bs_table[j]) {
5593 sector_num = bdrv_hash_find(bs_table[j],
5594 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5595 if (sector_num >= 0)
5596 break;
5599 if (j == MAX_DISKS)
5600 goto normal_compress;
5601 buf[0] = 1;
5602 buf[1] = j;
5603 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5604 ram_compress_buf(s, buf, 10);
5605 } else
5606 #endif
5608 // normal_compress:
5609 buf[0] = 0;
5610 ram_compress_buf(s, buf, 1);
5611 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5614 ram_compress_close(s);
5617 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5619 RamDecompressState s1, *s = &s1;
5620 uint8_t buf[10];
5621 int i;
5623 if (version_id == 1)
5624 return ram_load_v1(f, opaque);
5625 if (version_id != 2)
5626 return -EINVAL;
5627 if (qemu_get_be32(f) != phys_ram_size)
5628 return -EINVAL;
5629 if (ram_decompress_open(s, f) < 0)
5630 return -EINVAL;
5631 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5632 if (ram_decompress_buf(s, buf, 1) < 0) {
5633 fprintf(stderr, "Error while reading ram block header\n");
5634 goto error;
5636 if (buf[0] == 0) {
5637 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5638 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5639 goto error;
5641 } else
5642 #if 0
5643 if (buf[0] == 1) {
5644 int bs_index;
5645 int64_t sector_num;
5647 ram_decompress_buf(s, buf + 1, 9);
5648 bs_index = buf[1];
5649 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5650 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5651 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5652 goto error;
5654 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5655 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5656 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5657 bs_index, sector_num);
5658 goto error;
5660 } else
5661 #endif
5663 error:
5664 printf("Error block header\n");
5665 return -EINVAL;
5668 ram_decompress_close(s);
5669 return 0;
5672 /***********************************************************/
5673 /* bottom halves (can be seen as timers which expire ASAP) */
5675 struct QEMUBH {
5676 QEMUBHFunc *cb;
5677 void *opaque;
5678 int scheduled;
5679 QEMUBH *next;
5682 static QEMUBH *first_bh = NULL;
5684 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5686 QEMUBH *bh;
5687 bh = qemu_mallocz(sizeof(QEMUBH));
5688 if (!bh)
5689 return NULL;
5690 bh->cb = cb;
5691 bh->opaque = opaque;
5692 return bh;
5695 int qemu_bh_poll(void)
5697 QEMUBH *bh, **pbh;
5698 int ret;
5700 ret = 0;
5701 for(;;) {
5702 pbh = &first_bh;
5703 bh = *pbh;
5704 if (!bh)
5705 break;
5706 ret = 1;
5707 *pbh = bh->next;
5708 bh->scheduled = 0;
5709 bh->cb(bh->opaque);
5711 return ret;
5714 void qemu_bh_schedule(QEMUBH *bh)
5716 CPUState *env = cpu_single_env;
5717 if (bh->scheduled)
5718 return;
5719 bh->scheduled = 1;
5720 bh->next = first_bh;
5721 first_bh = bh;
5723 /* stop the currently executing CPU to execute the BH ASAP */
5724 if (env) {
5725 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5729 void qemu_bh_cancel(QEMUBH *bh)
5731 QEMUBH **pbh;
5732 if (bh->scheduled) {
5733 pbh = &first_bh;
5734 while (*pbh != bh)
5735 pbh = &(*pbh)->next;
5736 *pbh = bh->next;
5737 bh->scheduled = 0;
5741 void qemu_bh_delete(QEMUBH *bh)
5743 qemu_bh_cancel(bh);
5744 qemu_free(bh);
5747 /***********************************************************/
5748 /* machine registration */
5750 QEMUMachine *first_machine = NULL;
5752 int qemu_register_machine(QEMUMachine *m)
5754 QEMUMachine **pm;
5755 pm = &first_machine;
5756 while (*pm != NULL)
5757 pm = &(*pm)->next;
5758 m->next = NULL;
5759 *pm = m;
5760 return 0;
5763 QEMUMachine *find_machine(const char *name)
5765 QEMUMachine *m;
5767 for(m = first_machine; m != NULL; m = m->next) {
5768 if (!strcmp(m->name, name))
5769 return m;
5771 return NULL;
5774 /***********************************************************/
5775 /* main execution loop */
5777 void gui_update(void *opaque)
5779 display_state.dpy_refresh(&display_state);
5780 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5783 struct vm_change_state_entry {
5784 VMChangeStateHandler *cb;
5785 void *opaque;
5786 LIST_ENTRY (vm_change_state_entry) entries;
5789 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5791 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5792 void *opaque)
5794 VMChangeStateEntry *e;
5796 e = qemu_mallocz(sizeof (*e));
5797 if (!e)
5798 return NULL;
5800 e->cb = cb;
5801 e->opaque = opaque;
5802 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5803 return e;
5806 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5808 LIST_REMOVE (e, entries);
5809 qemu_free (e);
5812 static void vm_state_notify(int running)
5814 VMChangeStateEntry *e;
5816 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5817 e->cb(e->opaque, running);
5821 /* XXX: support several handlers */
5822 static VMStopHandler *vm_stop_cb;
5823 static void *vm_stop_opaque;
5825 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5827 vm_stop_cb = cb;
5828 vm_stop_opaque = opaque;
5829 return 0;
5832 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5834 vm_stop_cb = NULL;
5837 void vm_start(void)
5839 if (!vm_running) {
5840 cpu_enable_ticks();
5841 vm_running = 1;
5842 vm_state_notify(1);
5846 void vm_stop(int reason)
5848 if (vm_running) {
5849 cpu_disable_ticks();
5850 vm_running = 0;
5851 if (reason != 0) {
5852 if (vm_stop_cb) {
5853 vm_stop_cb(vm_stop_opaque, reason);
5856 vm_state_notify(0);
5860 /* reset/shutdown handler */
5862 typedef struct QEMUResetEntry {
5863 QEMUResetHandler *func;
5864 void *opaque;
5865 struct QEMUResetEntry *next;
5866 } QEMUResetEntry;
5868 static QEMUResetEntry *first_reset_entry;
5869 static int reset_requested;
5870 static int shutdown_requested;
5871 static int powerdown_requested;
5873 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5875 QEMUResetEntry **pre, *re;
5877 pre = &first_reset_entry;
5878 while (*pre != NULL)
5879 pre = &(*pre)->next;
5880 re = qemu_mallocz(sizeof(QEMUResetEntry));
5881 re->func = func;
5882 re->opaque = opaque;
5883 re->next = NULL;
5884 *pre = re;
5887 static void qemu_system_reset(void)
5889 QEMUResetEntry *re;
5891 /* reset all devices */
5892 for(re = first_reset_entry; re != NULL; re = re->next) {
5893 re->func(re->opaque);
5897 void qemu_system_reset_request(void)
5899 if (no_reboot) {
5900 shutdown_requested = 1;
5901 } else {
5902 reset_requested = 1;
5904 if (cpu_single_env)
5905 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5908 void qemu_system_shutdown_request(void)
5910 shutdown_requested = 1;
5911 if (cpu_single_env)
5912 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5915 void qemu_system_powerdown_request(void)
5917 powerdown_requested = 1;
5918 if (cpu_single_env)
5919 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5922 void main_loop_wait(int timeout)
5924 IOHandlerRecord *ioh, *ioh_next;
5925 fd_set rfds, wfds, xfds;
5926 int ret, nfds;
5927 struct timeval tv;
5928 PollingEntry *pe;
5931 /* XXX: need to suppress polling by better using win32 events */
5932 ret = 0;
5933 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5934 ret |= pe->func(pe->opaque);
5936 #ifdef _WIN32
5937 if (ret == 0 && timeout > 0) {
5938 int err;
5939 WaitObjects *w = &wait_objects;
5941 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5942 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5943 if (w->func[ret - WAIT_OBJECT_0])
5944 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5945 } else if (ret == WAIT_TIMEOUT) {
5946 } else {
5947 err = GetLastError();
5948 fprintf(stderr, "Wait error %d %d\n", ret, err);
5951 #endif
5952 /* poll any events */
5953 /* XXX: separate device handlers from system ones */
5954 nfds = -1;
5955 FD_ZERO(&rfds);
5956 FD_ZERO(&wfds);
5957 FD_ZERO(&xfds);
5958 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5959 if (ioh->fd_read &&
5960 (!ioh->fd_read_poll ||
5961 ioh->fd_read_poll(ioh->opaque) != 0)) {
5962 FD_SET(ioh->fd, &rfds);
5963 if (ioh->fd > nfds)
5964 nfds = ioh->fd;
5966 if (ioh->fd_write) {
5967 FD_SET(ioh->fd, &wfds);
5968 if (ioh->fd > nfds)
5969 nfds = ioh->fd;
5973 tv.tv_sec = 0;
5974 #ifdef _WIN32
5975 tv.tv_usec = 0;
5976 #else
5977 tv.tv_usec = timeout * 1000;
5978 #endif
5979 #if defined(CONFIG_SLIRP)
5980 if (slirp_inited) {
5981 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5983 #endif
5984 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5985 if (ret > 0) {
5986 /* XXX: better handling of removal */
5987 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5988 ioh_next = ioh->next;
5989 if (FD_ISSET(ioh->fd, &rfds)) {
5990 ioh->fd_read(ioh->opaque);
5992 if (FD_ISSET(ioh->fd, &wfds)) {
5993 ioh->fd_write(ioh->opaque);
5997 #if defined(CONFIG_SLIRP)
5998 if (slirp_inited) {
5999 if (ret < 0) {
6000 FD_ZERO(&rfds);
6001 FD_ZERO(&wfds);
6002 FD_ZERO(&xfds);
6004 slirp_select_poll(&rfds, &wfds, &xfds);
6006 #endif
6007 qemu_aio_poll();
6008 qemu_bh_poll();
6010 if (vm_running) {
6011 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6012 qemu_get_clock(vm_clock));
6013 /* run dma transfers, if any */
6014 DMA_run();
6017 /* real time timers */
6018 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6019 qemu_get_clock(rt_clock));
6022 static CPUState *cur_cpu;
6024 int main_loop(void)
6026 int ret, timeout;
6027 #ifdef CONFIG_PROFILER
6028 int64_t ti;
6029 #endif
6030 CPUState *env;
6032 cur_cpu = first_cpu;
6033 for(;;) {
6034 if (vm_running) {
6036 env = cur_cpu;
6037 for(;;) {
6038 /* get next cpu */
6039 env = env->next_cpu;
6040 if (!env)
6041 env = first_cpu;
6042 #ifdef CONFIG_PROFILER
6043 ti = profile_getclock();
6044 #endif
6045 ret = cpu_exec(env);
6046 #ifdef CONFIG_PROFILER
6047 qemu_time += profile_getclock() - ti;
6048 #endif
6049 if (ret != EXCP_HALTED)
6050 break;
6051 /* all CPUs are halted ? */
6052 if (env == cur_cpu) {
6053 ret = EXCP_HLT;
6054 break;
6057 cur_cpu = env;
6059 if (shutdown_requested) {
6060 ret = EXCP_INTERRUPT;
6061 break;
6063 if (reset_requested) {
6064 reset_requested = 0;
6065 qemu_system_reset();
6066 ret = EXCP_INTERRUPT;
6068 if (powerdown_requested) {
6069 powerdown_requested = 0;
6070 qemu_system_powerdown();
6071 ret = EXCP_INTERRUPT;
6073 if (ret == EXCP_DEBUG) {
6074 vm_stop(EXCP_DEBUG);
6076 /* if hlt instruction, we wait until the next IRQ */
6077 /* XXX: use timeout computed from timers */
6078 if (ret == EXCP_HLT)
6079 timeout = 10;
6080 else
6081 timeout = 0;
6082 } else {
6083 timeout = 10;
6085 #ifdef CONFIG_PROFILER
6086 ti = profile_getclock();
6087 #endif
6088 main_loop_wait(timeout);
6089 #ifdef CONFIG_PROFILER
6090 dev_time += profile_getclock() - ti;
6091 #endif
6093 cpu_disable_ticks();
6094 return ret;
6097 void help(void)
6099 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6100 "usage: %s [options] [disk_image]\n"
6101 "\n"
6102 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6103 "\n"
6104 "Standard options:\n"
6105 "-M machine select emulated machine (-M ? for list)\n"
6106 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6107 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6108 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6109 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6110 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
6111 "-disk ide,img=file[,hdx=a..dd][,type=disk|cdrom] \n"
6112 " defaults are: hdx=a,type=disk \n"
6113 "-disk scsi,img=file[,sdx=a..g][,type=disk|cdrom][,id=n] \n"
6114 " defaults are: sdx=a,type=disk,id='auto assign' \n"
6115 "-snapshot write to temporary files instead of disk image files\n"
6116 #ifdef CONFIG_SDL
6117 "-no-quit disable SDL window close capability\n"
6118 #endif
6119 #ifdef TARGET_I386
6120 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6121 #endif
6122 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6123 "-smp n set the number of CPUs to 'n' [default=1]\n"
6124 "-nographic disable graphical output and redirect serial I/Os to console\n"
6125 #ifndef _WIN32
6126 "-k language use keyboard layout (for example \"fr\" for French)\n"
6127 #endif
6128 #ifdef HAS_AUDIO
6129 "-audio-help print list of audio drivers and their options\n"
6130 "-soundhw c1,... enable audio support\n"
6131 " and only specified sound cards (comma separated list)\n"
6132 " use -soundhw ? to get the list of supported cards\n"
6133 " use -soundhw all to enable all of them\n"
6134 #endif
6135 "-localtime set the real time clock to local time [default=utc]\n"
6136 "-full-screen start in full screen\n"
6137 #ifdef TARGET_I386
6138 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6139 #endif
6140 "-usb enable the USB driver (will be the default soon)\n"
6141 "-usbdevice name add the host or guest USB device 'name'\n"
6142 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6143 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6144 #endif
6145 "\n"
6146 "Network options:\n"
6147 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6148 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6149 #ifdef CONFIG_SLIRP
6150 "-net user[,vlan=n][,hostname=host]\n"
6151 " connect the user mode network stack to VLAN 'n' and send\n"
6152 " hostname 'host' to DHCP clients\n"
6153 #endif
6154 #ifdef _WIN32
6155 "-net tap[,vlan=n],ifname=name\n"
6156 " connect the host TAP network interface to VLAN 'n'\n"
6157 #else
6158 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6159 " connect the host TAP network interface to VLAN 'n' and use\n"
6160 " the network script 'file' (default=%s);\n"
6161 " use 'fd=h' to connect to an already opened TAP interface\n"
6162 #endif
6163 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6164 " connect the vlan 'n' to another VLAN using a socket connection\n"
6165 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6166 " connect the vlan 'n' to multicast maddr and port\n"
6167 "-net none use it alone to have zero network devices; if no -net option\n"
6168 " is provided, the default is '-net nic -net user'\n"
6169 "\n"
6170 #ifdef CONFIG_SLIRP
6171 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6172 #ifndef _WIN32
6173 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6174 #endif
6175 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6176 " redirect TCP or UDP connections from host to guest [-net user]\n"
6177 #endif
6178 "\n"
6179 "Linux boot specific:\n"
6180 "-kernel bzImage use 'bzImage' as kernel image\n"
6181 "-append cmdline use 'cmdline' as kernel command line\n"
6182 "-initrd file use 'file' as initial ram disk\n"
6183 "\n"
6184 "Debug/Expert options:\n"
6185 "-monitor dev redirect the monitor to char device 'dev'\n"
6186 "-serial dev redirect the serial port to char device 'dev'\n"
6187 "-parallel dev redirect the parallel port to char device 'dev'\n"
6188 "-pidfile file Write PID to 'file'\n"
6189 "-S freeze CPU at startup (use 'c' to start execution)\n"
6190 "-s wait gdb connection to port %d\n"
6191 "-p port change gdb connection port\n"
6192 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6193 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6194 " translation (t=none or lba) (usually qemu can guess them)\n"
6195 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6196 #ifdef USE_KQEMU
6197 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6198 "-no-kqemu disable KQEMU kernel module usage\n"
6199 #endif
6200 #ifdef USE_CODE_COPY
6201 "-no-code-copy disable code copy acceleration\n"
6202 #endif
6203 #ifdef TARGET_I386
6204 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6205 " (default is CL-GD5446 PCI VGA)\n"
6206 "-no-acpi disable ACPI\n"
6207 #endif
6208 "-no-reboot exit instead of rebooting\n"
6209 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6210 "-vnc display start a VNC server on display\n"
6211 #ifndef _WIN32
6212 "-daemonize daemonize QEMU after initializing\n"
6213 #endif
6214 "\n"
6215 "During emulation, the following keys are useful:\n"
6216 "ctrl-alt-f toggle full screen\n"
6217 "ctrl-alt-n switch to virtual console 'n'\n"
6218 "ctrl-alt toggle mouse and keyboard grab\n"
6219 "\n"
6220 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6222 "qemu",
6223 DEFAULT_RAM_SIZE,
6224 #ifndef _WIN32
6225 DEFAULT_NETWORK_SCRIPT,
6226 #endif
6227 DEFAULT_GDBSTUB_PORT,
6228 "/tmp/qemu.log");
6229 exit(1);
6232 #define HAS_ARG 0x0001
6234 enum {
6235 QEMU_OPTION_h,
6237 QEMU_OPTION_M,
6238 QEMU_OPTION_fda,
6239 QEMU_OPTION_fdb,
6240 QEMU_OPTION_hda,
6241 QEMU_OPTION_hdb,
6242 QEMU_OPTION_hdc,
6243 QEMU_OPTION_hdd,
6244 QEMU_OPTION_cdrom,
6245 QEMU_OPTION_boot,
6246 QEMU_OPTION_snapshot,
6247 #ifdef TARGET_I386
6248 QEMU_OPTION_no_fd_bootchk,
6249 #endif
6250 QEMU_OPTION_m,
6251 QEMU_OPTION_nographic,
6252 #ifdef HAS_AUDIO
6253 QEMU_OPTION_audio_help,
6254 QEMU_OPTION_soundhw,
6255 #endif
6257 QEMU_OPTION_net,
6258 QEMU_OPTION_tftp,
6259 QEMU_OPTION_smb,
6260 QEMU_OPTION_redir,
6262 QEMU_OPTION_kernel,
6263 QEMU_OPTION_append,
6264 QEMU_OPTION_initrd,
6266 QEMU_OPTION_S,
6267 QEMU_OPTION_s,
6268 QEMU_OPTION_p,
6269 QEMU_OPTION_d,
6270 QEMU_OPTION_hdachs,
6271 QEMU_OPTION_L,
6272 QEMU_OPTION_no_code_copy,
6273 QEMU_OPTION_k,
6274 QEMU_OPTION_localtime,
6275 QEMU_OPTION_cirrusvga,
6276 QEMU_OPTION_g,
6277 QEMU_OPTION_std_vga,
6278 QEMU_OPTION_monitor,
6279 QEMU_OPTION_serial,
6280 QEMU_OPTION_parallel,
6281 QEMU_OPTION_loadvm,
6282 QEMU_OPTION_full_screen,
6283 QEMU_OPTION_no_quit,
6284 QEMU_OPTION_pidfile,
6285 QEMU_OPTION_no_kqemu,
6286 QEMU_OPTION_kernel_kqemu,
6287 QEMU_OPTION_win2k_hack,
6288 QEMU_OPTION_usb,
6289 QEMU_OPTION_usbdevice,
6290 QEMU_OPTION_smp,
6291 QEMU_OPTION_vnc,
6292 QEMU_OPTION_no_acpi,
6293 QEMU_OPTION_no_reboot,
6294 QEMU_OPTION_daemonize,
6295 QEMU_OPTION_disk,
6298 typedef struct QEMUOption {
6299 const char *name;
6300 int flags;
6301 int index;
6302 } QEMUOption;
6304 const QEMUOption qemu_options[] = {
6305 { "h", 0, QEMU_OPTION_h },
6307 { "M", HAS_ARG, QEMU_OPTION_M },
6308 { "fda", HAS_ARG, QEMU_OPTION_fda },
6309 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6310 { "hda", HAS_ARG, QEMU_OPTION_hda },
6311 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6312 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6313 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6314 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6315 { "boot", HAS_ARG, QEMU_OPTION_boot },
6316 { "snapshot", 0, QEMU_OPTION_snapshot },
6317 #ifdef TARGET_I386
6318 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6319 #endif
6320 { "m", HAS_ARG, QEMU_OPTION_m },
6321 { "nographic", 0, QEMU_OPTION_nographic },
6322 { "k", HAS_ARG, QEMU_OPTION_k },
6323 #ifdef HAS_AUDIO
6324 { "audio-help", 0, QEMU_OPTION_audio_help },
6325 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6326 #endif
6328 { "net", HAS_ARG, QEMU_OPTION_net},
6329 #ifdef CONFIG_SLIRP
6330 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6331 #ifndef _WIN32
6332 { "smb", HAS_ARG, QEMU_OPTION_smb },
6333 #endif
6334 { "redir", HAS_ARG, QEMU_OPTION_redir },
6335 #endif
6337 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6338 { "append", HAS_ARG, QEMU_OPTION_append },
6339 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6341 { "S", 0, QEMU_OPTION_S },
6342 { "s", 0, QEMU_OPTION_s },
6343 { "p", HAS_ARG, QEMU_OPTION_p },
6344 { "d", HAS_ARG, QEMU_OPTION_d },
6345 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6346 { "L", HAS_ARG, QEMU_OPTION_L },
6347 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6348 #ifdef USE_KQEMU
6349 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6350 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6351 #endif
6352 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6353 { "g", 1, QEMU_OPTION_g },
6354 #endif
6355 { "localtime", 0, QEMU_OPTION_localtime },
6356 { "std-vga", 0, QEMU_OPTION_std_vga },
6357 { "monitor", 1, QEMU_OPTION_monitor },
6358 { "serial", 1, QEMU_OPTION_serial },
6359 { "parallel", 1, QEMU_OPTION_parallel },
6360 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6361 { "full-screen", 0, QEMU_OPTION_full_screen },
6362 #ifdef CONFIG_SDL
6363 { "no-quit", 0, QEMU_OPTION_no_quit },
6364 #endif
6365 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6366 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6367 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6368 { "smp", HAS_ARG, QEMU_OPTION_smp },
6369 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6370 { "disk", HAS_ARG, QEMU_OPTION_disk },
6372 /* temporary options */
6373 { "usb", 0, QEMU_OPTION_usb },
6374 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6375 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6376 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6377 { "daemonize", 0, QEMU_OPTION_daemonize },
6378 { NULL },
6381 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6383 /* this stack is only used during signal handling */
6384 #define SIGNAL_STACK_SIZE 32768
6386 static uint8_t *signal_stack;
6388 #endif
6390 /* password input */
6392 static BlockDriverState *get_bdrv(int index)
6394 BlockDriverState *bs;
6396 if (index < 4) {
6397 bs = bs_table[index];
6398 } else if (index < 6) {
6399 bs = fd_table[index - 4];
6400 } else {
6401 bs = NULL;
6403 return bs;
6406 static void read_passwords(void)
6408 BlockDriverState *bs;
6409 int i, j;
6410 char password[256];
6412 for(i = 0; i < 6; i++) {
6413 bs = get_bdrv(i);
6414 if (bs && bdrv_is_encrypted(bs)) {
6415 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6416 for(j = 0; j < 3; j++) {
6417 monitor_readline("Password: ",
6418 1, password, sizeof(password));
6419 if (bdrv_set_key(bs, password) == 0)
6420 break;
6421 term_printf("invalid password\n");
6427 /* XXX: currently we cannot use simultaneously different CPUs */
6428 void register_machines(void)
6430 #if defined(TARGET_I386)
6431 qemu_register_machine(&pc_machine);
6432 qemu_register_machine(&isapc_machine);
6433 #elif defined(TARGET_PPC)
6434 qemu_register_machine(&heathrow_machine);
6435 qemu_register_machine(&core99_machine);
6436 qemu_register_machine(&prep_machine);
6437 #elif defined(TARGET_MIPS)
6438 qemu_register_machine(&mips_machine);
6439 #elif defined(TARGET_SPARC)
6440 #ifdef TARGET_SPARC64
6441 qemu_register_machine(&sun4u_machine);
6442 #else
6443 qemu_register_machine(&sun4m_machine);
6444 #endif
6445 #elif defined(TARGET_ARM)
6446 qemu_register_machine(&integratorcp926_machine);
6447 qemu_register_machine(&integratorcp1026_machine);
6448 qemu_register_machine(&versatilepb_machine);
6449 qemu_register_machine(&versatileab_machine);
6450 qemu_register_machine(&realview_machine);
6451 #elif defined(TARGET_SH4)
6452 qemu_register_machine(&shix_machine);
6453 #else
6454 #error unsupported CPU
6455 #endif
6458 #ifdef HAS_AUDIO
6459 struct soundhw soundhw[] = {
6460 #ifdef TARGET_I386
6462 "pcspk",
6463 "PC speaker",
6466 { .init_isa = pcspk_audio_init }
6468 #endif
6470 "sb16",
6471 "Creative Sound Blaster 16",
6474 { .init_isa = SB16_init }
6477 #ifdef CONFIG_ADLIB
6479 "adlib",
6480 #ifdef HAS_YMF262
6481 "Yamaha YMF262 (OPL3)",
6482 #else
6483 "Yamaha YM3812 (OPL2)",
6484 #endif
6487 { .init_isa = Adlib_init }
6489 #endif
6491 #ifdef CONFIG_GUS
6493 "gus",
6494 "Gravis Ultrasound GF1",
6497 { .init_isa = GUS_init }
6499 #endif
6502 "es1370",
6503 "ENSONIQ AudioPCI ES1370",
6506 { .init_pci = es1370_init }
6509 { NULL, NULL, 0, 0, { NULL } }
6512 static void select_soundhw (const char *optarg)
6514 struct soundhw *c;
6516 if (*optarg == '?') {
6517 show_valid_cards:
6519 printf ("Valid sound card names (comma separated):\n");
6520 for (c = soundhw; c->name; ++c) {
6521 printf ("%-11s %s\n", c->name, c->descr);
6523 printf ("\n-soundhw all will enable all of the above\n");
6524 exit (*optarg != '?');
6526 else {
6527 size_t l;
6528 const char *p;
6529 char *e;
6530 int bad_card = 0;
6532 if (!strcmp (optarg, "all")) {
6533 for (c = soundhw; c->name; ++c) {
6534 c->enabled = 1;
6536 return;
6539 p = optarg;
6540 while (*p) {
6541 e = strchr (p, ',');
6542 l = !e ? strlen (p) : (size_t) (e - p);
6544 for (c = soundhw; c->name; ++c) {
6545 if (!strncmp (c->name, p, l)) {
6546 c->enabled = 1;
6547 break;
6551 if (!c->name) {
6552 if (l > 80) {
6553 fprintf (stderr,
6554 "Unknown sound card name (too big to show)\n");
6556 else {
6557 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6558 (int) l, p);
6560 bad_card = 1;
6562 p += l + (e != NULL);
6565 if (bad_card)
6566 goto show_valid_cards;
6569 #endif
6571 #ifdef _WIN32
6572 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6574 exit(STATUS_CONTROL_C_EXIT);
6575 return TRUE;
6577 #endif
6579 #define MAX_NET_CLIENTS 32
6581 int main(int argc, char **argv)
6583 #ifdef CONFIG_GDBSTUB
6584 int use_gdbstub, gdbstub_port;
6585 #endif
6586 int i, cdrom_index;
6587 int snapshot, linux_boot;
6588 const char *initrd_filename;
6589 const char *fd_filename[MAX_FD];
6590 char scsi_options[MAX_SCSI_DISKS] [DISK_OPTIONS_SIZE];
6591 char ide_options[MAX_DISKS] [DISK_OPTIONS_SIZE];
6592 int num_ide_disks;
6593 int num_scsi_disks;
6594 const char *kernel_filename, *kernel_cmdline;
6595 DisplayState *ds = &display_state;
6596 int cyls, heads, secs, translation;
6597 int start_emulation = 1;
6598 char net_clients[MAX_NET_CLIENTS][256];
6599 int nb_net_clients;
6600 int optind;
6601 const char *r, *optarg;
6602 CharDriverState *monitor_hd;
6603 char monitor_device[128];
6604 char serial_devices[MAX_SERIAL_PORTS][128];
6605 int serial_device_index;
6606 char parallel_devices[MAX_PARALLEL_PORTS][128];
6607 int parallel_device_index;
6608 const char *loadvm = NULL;
6609 QEMUMachine *machine;
6610 char usb_devices[MAX_USB_CMDLINE][128];
6611 int usb_devices_index;
6612 int fds[2];
6614 LIST_INIT (&vm_change_state_head);
6615 #ifndef _WIN32
6617 struct sigaction act;
6618 sigfillset(&act.sa_mask);
6619 act.sa_flags = 0;
6620 act.sa_handler = SIG_IGN;
6621 sigaction(SIGPIPE, &act, NULL);
6623 #else
6624 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6625 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6626 QEMU to run on a single CPU */
6628 HANDLE h;
6629 DWORD mask, smask;
6630 int i;
6631 h = GetCurrentProcess();
6632 if (GetProcessAffinityMask(h, &mask, &smask)) {
6633 for(i = 0; i < 32; i++) {
6634 if (mask & (1 << i))
6635 break;
6637 if (i != 32) {
6638 mask = 1 << i;
6639 SetProcessAffinityMask(h, mask);
6643 #endif
6645 register_machines();
6646 machine = first_machine;
6647 initrd_filename = NULL;
6648 for(i = 0; i < MAX_SCSI_DISKS; i++) {
6649 scsi_disks_info[i].device_type = SCSI_NONE;
6650 bs_scsi_table[i] = NULL;
6653 num_ide_disks = 0;
6654 num_scsi_disks = 0;
6656 for(i = 0; i < MAX_FD; i++)
6657 fd_filename[i] = NULL;
6658 for(i = 0; i < MAX_DISKS; i++) {
6659 ide_options[i][0] = '\0';
6661 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6662 vga_ram_size = VGA_RAM_SIZE;
6663 bios_size = BIOS_SIZE;
6664 #ifdef CONFIG_GDBSTUB
6665 use_gdbstub = 0;
6666 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6667 #endif
6668 snapshot = 0;
6669 nographic = 0;
6670 kernel_filename = NULL;
6671 kernel_cmdline = "";
6672 #ifdef TARGET_PPC
6673 cdrom_index = 1;
6674 #else
6675 cdrom_index = 2;
6676 #endif
6677 cyls = heads = secs = 0;
6678 translation = BIOS_ATA_TRANSLATION_AUTO;
6679 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6681 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6682 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6683 serial_devices[i][0] = '\0';
6684 serial_device_index = 0;
6686 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6687 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6688 parallel_devices[i][0] = '\0';
6689 parallel_device_index = 0;
6691 usb_devices_index = 0;
6693 nb_net_clients = 0;
6695 nb_nics = 0;
6696 /* default mac address of the first network interface */
6698 optind = 1;
6699 for(;;) {
6700 if (optind >= argc)
6701 break;
6702 r = argv[optind];
6703 if (r[0] != '-') {
6705 /* Build new disk IDE syntax string */
6706 pstrcpy(ide_options[0],
6708 "hdx=a,img=");
6709 /*Add on image filename */
6710 pstrcpy(&(ide_options[0][13]),
6711 sizeof(ide_options[0])-13,
6712 argv[optind++]);
6713 num_ide_disks++;
6714 } else {
6715 const QEMUOption *popt;
6717 optind++;
6718 popt = qemu_options;
6719 for(;;) {
6720 if (!popt->name) {
6721 fprintf(stderr, "%s: invalid option -- '%s'\n",
6722 argv[0], r);
6723 exit(1);
6725 if (!strcmp(popt->name, r + 1))
6726 break;
6727 popt++;
6729 if (popt->flags & HAS_ARG) {
6730 if (optind >= argc) {
6731 fprintf(stderr, "%s: option '%s' requires an argument\n",
6732 argv[0], r);
6733 exit(1);
6735 optarg = argv[optind++];
6736 } else {
6737 optarg = NULL;
6740 switch(popt->index) {
6741 case QEMU_OPTION_M:
6742 machine = find_machine(optarg);
6743 if (!machine) {
6744 QEMUMachine *m;
6745 printf("Supported machines are:\n");
6746 for(m = first_machine; m != NULL; m = m->next) {
6747 printf("%-10s %s%s\n",
6748 m->name, m->desc,
6749 m == first_machine ? " (default)" : "");
6751 exit(1);
6753 break;
6754 case QEMU_OPTION_initrd:
6755 initrd_filename = optarg;
6756 break;
6757 case QEMU_OPTION_hda:
6758 case QEMU_OPTION_hdb:
6759 case QEMU_OPTION_hdc:
6760 case QEMU_OPTION_hdd:
6762 int hd_index;
6763 const char newIDE_DiskSyntax [][10] = {
6764 "hdx=a,img=", "hdx=b,img=", "hdx=c,img=", "hdx=d,img=" };
6766 hd_index = popt->index - QEMU_OPTION_hda;
6767 if (num_ide_disks >= MAX_DISKS) {
6768 fprintf(stderr, "qemu: too many IDE disks defined.\n");
6769 exit(1);
6771 /* Build new disk IDE syntax string */
6772 pstrcpy(ide_options[hd_index],
6774 newIDE_DiskSyntax[hd_index]);
6775 /* Add on image filename */
6776 pstrcpy(&(ide_options[hd_index][10]),
6777 sizeof(ide_options[0])-10,
6778 optarg);
6779 num_ide_disks++;
6781 break;
6782 case QEMU_OPTION_disk: /*Combined IDE and SCSI, for disk and CDROM */
6784 const char *p_input_char;
6785 char *p_output_string;
6786 char device[64];
6787 int disk_index;
6789 p_input_char = optarg;
6790 p_output_string = device;
6791 while (*p_input_char != '\0' && *p_input_char != ',') {
6792 if ((p_output_string - device) < sizeof(device) - 1)
6793 *p_output_string++ = *p_input_char;
6794 p_input_char++;
6796 *p_output_string = '\0';
6797 if (*p_input_char == ',')
6798 p_input_char++;
6800 if (!strcmp(device, "scsi")) {
6801 if (num_scsi_disks >= MAX_SCSI_DISKS) {
6802 fprintf(stderr, "qemu: too many SCSI disks defined.\n");
6803 exit(1);
6805 pstrcpy(scsi_options[num_scsi_disks],
6806 sizeof(scsi_options[0]),
6807 p_input_char);
6808 num_scsi_disks++;
6809 } else if (!strcmp(device,"ide")) {
6810 if (num_ide_disks >= MAX_DISKS) {
6811 fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6812 exit(1);
6814 disk_index = 0; /* default is hda */
6815 if (get_param_value(device, sizeof(device),"hdx",p_input_char)) {
6816 if (device[0] >= 'a' && device[0] <= 'd') {
6817 disk_index = device[0] - 'a';
6818 } else {
6819 fprintf(stderr, "qemu: invalid IDE disk hdx= value: %s\n", device);
6820 return -1;
6823 else disk_index=0;
6824 pstrcpy(ide_options[disk_index],
6825 sizeof(ide_options[0]),
6826 p_input_char);
6827 num_ide_disks++;
6828 } else {
6829 fprintf(stderr, "qemu: -disk option must specify IDE or SCSI: %s \n",device);
6830 exit(1);
6833 break;
6834 case QEMU_OPTION_snapshot:
6835 snapshot = 1;
6836 break;
6837 case QEMU_OPTION_hdachs:
6839 const char *p;
6840 p = optarg;
6841 cyls = strtol(p, (char **)&p, 0);
6842 if (cyls < 1 || cyls > 16383)
6843 goto chs_fail;
6844 if (*p != ',')
6845 goto chs_fail;
6846 p++;
6847 heads = strtol(p, (char **)&p, 0);
6848 if (heads < 1 || heads > 16)
6849 goto chs_fail;
6850 if (*p != ',')
6851 goto chs_fail;
6852 p++;
6853 secs = strtol(p, (char **)&p, 0);
6854 if (secs < 1 || secs > 63)
6855 goto chs_fail;
6856 if (*p == ',') {
6857 p++;
6858 if (!strcmp(p, "none"))
6859 translation = BIOS_ATA_TRANSLATION_NONE;
6860 else if (!strcmp(p, "lba"))
6861 translation = BIOS_ATA_TRANSLATION_LBA;
6862 else if (!strcmp(p, "auto"))
6863 translation = BIOS_ATA_TRANSLATION_AUTO;
6864 else
6865 goto chs_fail;
6866 } else if (*p != '\0') {
6867 chs_fail:
6868 fprintf(stderr, "qemu: invalid physical CHS format\n");
6869 exit(1);
6872 break;
6873 case QEMU_OPTION_nographic:
6874 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6875 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6876 nographic = 1;
6877 break;
6878 case QEMU_OPTION_kernel:
6879 kernel_filename = optarg;
6880 break;
6881 case QEMU_OPTION_append:
6882 kernel_cmdline = optarg;
6883 break;
6884 case QEMU_OPTION_cdrom:
6886 char buf[22];
6887 if (num_ide_disks >= MAX_DISKS) {
6888 fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6889 exit(1);
6891 snprintf(buf, sizeof(buf), "type=cdrom,hdx=%c,img=", cdrom_index + 'a');
6892 /* Build new disk IDE syntax string */
6893 pstrcpy(ide_options[cdrom_index],
6895 buf);
6896 /* Add on image filename */
6897 pstrcpy(&(ide_options[cdrom_index][21]),
6898 sizeof(ide_options[0])-21,
6899 optarg);
6900 num_ide_disks++;
6902 break;
6903 case QEMU_OPTION_boot:
6904 boot_device = optarg[0];
6905 if (boot_device != 'a' &&
6906 #ifdef TARGET_SPARC
6907 // Network boot
6908 boot_device != 'n' &&
6909 #endif
6910 boot_device != 'c' && boot_device != 'd') {
6911 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6912 exit(1);
6914 break;
6915 case QEMU_OPTION_fda:
6916 fd_filename[0] = optarg;
6917 break;
6918 case QEMU_OPTION_fdb:
6919 fd_filename[1] = optarg;
6920 break;
6921 #ifdef TARGET_I386
6922 case QEMU_OPTION_no_fd_bootchk:
6923 fd_bootchk = 0;
6924 break;
6925 #endif
6926 case QEMU_OPTION_no_code_copy:
6927 code_copy_enabled = 0;
6928 break;
6929 case QEMU_OPTION_net:
6930 if (nb_net_clients >= MAX_NET_CLIENTS) {
6931 fprintf(stderr, "qemu: too many network clients\n");
6932 exit(1);
6934 pstrcpy(net_clients[nb_net_clients],
6935 sizeof(net_clients[0]),
6936 optarg);
6937 nb_net_clients++;
6938 break;
6939 #ifdef CONFIG_SLIRP
6940 case QEMU_OPTION_tftp:
6941 tftp_prefix = optarg;
6942 break;
6943 #ifndef _WIN32
6944 case QEMU_OPTION_smb:
6945 net_slirp_smb(optarg);
6946 break;
6947 #endif
6948 case QEMU_OPTION_redir:
6949 net_slirp_redir(optarg);
6950 break;
6951 #endif
6952 #ifdef HAS_AUDIO
6953 case QEMU_OPTION_audio_help:
6954 AUD_help ();
6955 exit (0);
6956 break;
6957 case QEMU_OPTION_soundhw:
6958 select_soundhw (optarg);
6959 break;
6960 #endif
6961 case QEMU_OPTION_h:
6962 help();
6963 break;
6964 case QEMU_OPTION_m:
6965 ram_size = atoi(optarg) * 1024 * 1024;
6966 if (ram_size <= 0)
6967 help();
6968 if (ram_size > PHYS_RAM_MAX_SIZE) {
6969 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6970 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6971 exit(1);
6973 break;
6974 case QEMU_OPTION_d:
6976 int mask;
6977 CPULogItem *item;
6979 mask = cpu_str_to_log_mask(optarg);
6980 if (!mask) {
6981 printf("Log items (comma separated):\n");
6982 for(item = cpu_log_items; item->mask != 0; item++) {
6983 printf("%-10s %s\n", item->name, item->help);
6985 exit(1);
6987 cpu_set_log(mask);
6989 break;
6990 #ifdef CONFIG_GDBSTUB
6991 case QEMU_OPTION_s:
6992 use_gdbstub = 1;
6993 break;
6994 case QEMU_OPTION_p:
6995 gdbstub_port = atoi(optarg);
6996 break;
6997 #endif
6998 case QEMU_OPTION_L:
6999 bios_dir = optarg;
7000 break;
7001 case QEMU_OPTION_S:
7002 start_emulation = 0;
7003 break;
7004 case QEMU_OPTION_k:
7005 keyboard_layout = optarg;
7006 break;
7007 case QEMU_OPTION_localtime:
7008 rtc_utc = 0;
7009 break;
7010 case QEMU_OPTION_cirrusvga:
7011 cirrus_vga_enabled = 1;
7012 break;
7013 case QEMU_OPTION_std_vga:
7014 cirrus_vga_enabled = 0;
7015 break;
7016 case QEMU_OPTION_g:
7018 const char *p;
7019 int w, h, depth;
7020 p = optarg;
7021 w = strtol(p, (char **)&p, 10);
7022 if (w <= 0) {
7023 graphic_error:
7024 fprintf(stderr, "qemu: invalid resolution or depth\n");
7025 exit(1);
7027 if (*p != 'x')
7028 goto graphic_error;
7029 p++;
7030 h = strtol(p, (char **)&p, 10);
7031 if (h <= 0)
7032 goto graphic_error;
7033 if (*p == 'x') {
7034 p++;
7035 depth = strtol(p, (char **)&p, 10);
7036 if (depth != 8 && depth != 15 && depth != 16 &&
7037 depth != 24 && depth != 32)
7038 goto graphic_error;
7039 } else if (*p == '\0') {
7040 depth = graphic_depth;
7041 } else {
7042 goto graphic_error;
7045 graphic_width = w;
7046 graphic_height = h;
7047 graphic_depth = depth;
7049 break;
7050 case QEMU_OPTION_monitor:
7051 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7052 break;
7053 case QEMU_OPTION_serial:
7054 if (serial_device_index >= MAX_SERIAL_PORTS) {
7055 fprintf(stderr, "qemu: too many serial ports\n");
7056 exit(1);
7058 pstrcpy(serial_devices[serial_device_index],
7059 sizeof(serial_devices[0]), optarg);
7060 serial_device_index++;
7061 break;
7062 case QEMU_OPTION_parallel:
7063 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7064 fprintf(stderr, "qemu: too many parallel ports\n");
7065 exit(1);
7067 pstrcpy(parallel_devices[parallel_device_index],
7068 sizeof(parallel_devices[0]), optarg);
7069 parallel_device_index++;
7070 break;
7071 case QEMU_OPTION_loadvm:
7072 loadvm = optarg;
7073 break;
7074 case QEMU_OPTION_full_screen:
7075 full_screen = 1;
7076 break;
7077 #ifdef CONFIG_SDL
7078 case QEMU_OPTION_no_quit:
7079 no_quit = 1;
7080 break;
7081 #endif
7082 case QEMU_OPTION_pidfile:
7083 create_pidfile(optarg);
7084 break;
7085 #ifdef TARGET_I386
7086 case QEMU_OPTION_win2k_hack:
7087 win2k_install_hack = 1;
7088 break;
7089 #endif
7090 #ifdef USE_KQEMU
7091 case QEMU_OPTION_no_kqemu:
7092 kqemu_allowed = 0;
7093 break;
7094 case QEMU_OPTION_kernel_kqemu:
7095 kqemu_allowed = 2;
7096 break;
7097 #endif
7098 case QEMU_OPTION_usb:
7099 usb_enabled = 1;
7100 break;
7101 case QEMU_OPTION_usbdevice:
7102 usb_enabled = 1;
7103 if (usb_devices_index >= MAX_USB_CMDLINE) {
7104 fprintf(stderr, "Too many USB devices\n");
7105 exit(1);
7107 pstrcpy(usb_devices[usb_devices_index],
7108 sizeof(usb_devices[usb_devices_index]),
7109 optarg);
7110 usb_devices_index++;
7111 break;
7112 case QEMU_OPTION_smp:
7113 smp_cpus = atoi(optarg);
7114 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7115 fprintf(stderr, "Invalid number of CPUs\n");
7116 exit(1);
7118 break;
7119 case QEMU_OPTION_vnc:
7120 vnc_display = optarg;
7121 break;
7122 case QEMU_OPTION_no_acpi:
7123 acpi_enabled = 0;
7124 break;
7125 case QEMU_OPTION_no_reboot:
7126 no_reboot = 1;
7127 break;
7128 case QEMU_OPTION_daemonize:
7129 daemonize = 1;
7130 break;
7135 #ifndef _WIN32
7136 if (daemonize && !nographic && vnc_display == NULL) {
7137 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7138 daemonize = 0;
7141 if (daemonize) {
7142 pid_t pid;
7144 if (pipe(fds) == -1)
7145 exit(1);
7147 pid = fork();
7148 if (pid > 0) {
7149 uint8_t status;
7150 ssize_t len;
7152 close(fds[1]);
7154 again:
7155 len = read(fds[0], &status, 1);
7156 if (len == -1 && (errno == EINTR))
7157 goto again;
7159 if (len != 1 || status != 0)
7160 exit(1);
7161 else
7162 exit(0);
7163 } else if (pid < 0)
7164 exit(1);
7166 setsid();
7168 pid = fork();
7169 if (pid > 0)
7170 exit(0);
7171 else if (pid < 0)
7172 exit(1);
7174 umask(027);
7175 chdir("/");
7177 signal(SIGTSTP, SIG_IGN);
7178 signal(SIGTTOU, SIG_IGN);
7179 signal(SIGTTIN, SIG_IGN);
7181 #endif
7183 #ifdef USE_KQEMU
7184 if (smp_cpus > 1)
7185 kqemu_allowed = 0;
7186 #endif
7187 linux_boot = (kernel_filename != NULL);
7189 if (!linux_boot &&
7190 num_ide_disks == 0 &&
7191 fd_filename[0] == '\0')
7192 help();
7194 setvbuf(stdout, NULL, _IOLBF, 0);
7196 init_timers();
7197 init_timer_alarm();
7198 qemu_aio_init();
7200 #ifdef _WIN32
7201 socket_init();
7202 #endif
7204 /* init network clients */
7205 if (nb_net_clients == 0) {
7206 /* if no clients, we use a default config */
7207 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7208 "nic");
7209 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7210 "user");
7211 nb_net_clients = 2;
7214 for(i = 0;i < nb_net_clients; i++) {
7215 if (net_client_init(net_clients[i]) < 0)
7216 exit(1);
7219 /* init the memory */
7220 phys_ram_size = ram_size + vga_ram_size + bios_size;
7222 phys_ram_base = qemu_vmalloc(phys_ram_size);
7223 if (!phys_ram_base) {
7224 fprintf(stderr, "Could not allocate physical memory\n");
7225 exit(1);
7228 bdrv_init();
7230 /* open the virtual block devices, disks or CDRoms */
7231 if (disk_options_init(num_ide_disks,ide_options,snapshot,
7232 num_scsi_disks,scsi_options,
7233 cdrom_index,
7234 cyls, heads, secs, translation)){
7235 exit(1);
7238 /* boot to floppy or default cd if no hard disk */
7239 if (num_ide_disks == 0 && boot_device == 'c') {
7240 if (fd_filename[0] != '\0')
7241 boot_device = 'a';
7242 else
7243 boot_device = 'd';
7246 /* we always create at least one floppy disk */
7247 fd_table[0] = bdrv_new("fda");
7248 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7250 for(i = 0; i < MAX_FD; i++) {
7251 if (fd_filename[i]) {
7252 if (!fd_table[i]) {
7253 char buf[64];
7254 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7255 fd_table[i] = bdrv_new(buf);
7256 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7258 if (fd_filename[i] != '\0') {
7259 if (bdrv_open(fd_table[i], fd_filename[i],
7260 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7261 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7262 fd_filename[i]);
7263 exit(1);
7269 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7270 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7272 init_ioports();
7274 /* terminal init */
7275 if (nographic) {
7276 dumb_display_init(ds);
7277 } else if (vnc_display != NULL) {
7278 vnc_display_init(ds, vnc_display);
7279 } else {
7280 #if defined(CONFIG_SDL)
7281 sdl_display_init(ds, full_screen);
7282 #elif defined(CONFIG_COCOA)
7283 cocoa_display_init(ds, full_screen);
7284 #else
7285 dumb_display_init(ds);
7286 #endif
7289 monitor_hd = qemu_chr_open(monitor_device);
7290 if (!monitor_hd) {
7291 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7292 exit(1);
7294 monitor_init(monitor_hd, !nographic);
7296 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7297 const char *devname = serial_devices[i];
7298 if (devname[0] != '\0' && strcmp(devname, "none")) {
7299 serial_hds[i] = qemu_chr_open(devname);
7300 if (!serial_hds[i]) {
7301 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7302 devname);
7303 exit(1);
7305 if (!strcmp(devname, "vc"))
7306 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7310 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7311 const char *devname = parallel_devices[i];
7312 if (devname[0] != '\0' && strcmp(devname, "none")) {
7313 parallel_hds[i] = qemu_chr_open(devname);
7314 if (!parallel_hds[i]) {
7315 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7316 devname);
7317 exit(1);
7319 if (!strcmp(devname, "vc"))
7320 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7324 machine->init(ram_size, vga_ram_size, boot_device,
7325 ds, fd_filename, snapshot,
7326 kernel_filename, kernel_cmdline, initrd_filename);
7328 /* init USB devices */
7329 if (usb_enabled) {
7330 for(i = 0; i < usb_devices_index; i++) {
7331 if (usb_device_add(usb_devices[i]) < 0) {
7332 fprintf(stderr, "Warning: could not add USB device %s\n",
7333 usb_devices[i]);
7338 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7339 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7341 #ifdef CONFIG_GDBSTUB
7342 if (use_gdbstub) {
7343 if (gdbserver_start(gdbstub_port) < 0) {
7344 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
7345 gdbstub_port);
7346 exit(1);
7347 } else {
7348 printf("Waiting gdb connection on port %d\n", gdbstub_port);
7350 } else
7351 #endif
7352 if (loadvm)
7353 do_loadvm(loadvm);
7356 /* XXX: simplify init */
7357 read_passwords();
7358 if (start_emulation) {
7359 vm_start();
7363 if (daemonize) {
7364 uint8_t status = 0;
7365 ssize_t len;
7366 int fd;
7368 again1:
7369 len = write(fds[1], &status, 1);
7370 if (len == -1 && (errno == EINTR))
7371 goto again1;
7373 if (len != 1)
7374 exit(1);
7376 fd = open("/dev/null", O_RDWR);
7377 if (fd == -1)
7378 exit(1);
7380 dup2(fd, 0);
7381 dup2(fd, 1);
7382 dup2(fd, 2);
7384 close(fd);
7387 main_loop();
7388 quit_timers();
7389 return 0;