ia64/xen-unstable

view tools/ioemu/vl.c @ 12594:2ae4e4e89d6d

[XEN] Cleanups to phys/mach address handling.

1. Balloon driver does not need to set M2P entry.
This is done by the populate_physmap hypercall.

2. Xen now translates foreign mappings from GMFN->MFN.
Tools are simplified because of this.

Signed-off-by: Keir Fraser <keir@xensource.com>
author kfraser@localhost.localdomain
date Mon Nov 27 14:20:44 2006 +0000 (2006-11-27)
parents b8cc9ffda0a3
children d901f2fe8c25 67a06a9b7b1d
line source
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
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>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.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/xen/qemu-ifup"
92 #define DEFAULT_BRIDGE "xenbr0"
94 //#define DEBUG_UNUSED_IOPORT
95 //#define DEBUG_IOPORT
97 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99 #ifdef TARGET_PPC
100 #define DEFAULT_RAM_SIZE 144
101 #else
102 #define DEFAULT_RAM_SIZE 128
103 #endif
104 /* in ms */
105 #define GUI_REFRESH_INTERVAL 30
107 /* Max number of USB devices that can be specified on the commandline. */
108 #define MAX_USB_CMDLINE 8
110 /* XXX: use a two level table to limit memory usage */
111 #define MAX_IOPORTS 65536
113 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
114 char phys_ram_file[1024];
115 void *ioport_opaque[MAX_IOPORTS];
116 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
117 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
118 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
119 int vga_ram_size;
120 int bios_size;
121 static DisplayState display_state;
122 int nographic;
123 int vncviewer;
124 int vncunused;
125 struct sockaddr_in vnclisten_addr;
126 const char* keyboard_layout = NULL;
127 int64_t ticks_per_sec;
128 char *boot_device = NULL;
129 uint64_t ram_size;
130 int pit_min_timer_count = 0;
131 int nb_nics;
132 NICInfo nd_table[MAX_NICS];
133 QEMUTimer *gui_timer;
134 int vm_running;
135 int rtc_utc = 1;
136 int cirrus_vga_enabled = 1;
137 #ifdef TARGET_SPARC
138 int graphic_width = 1024;
139 int graphic_height = 768;
140 #else
141 int graphic_width = 800;
142 int graphic_height = 600;
143 #endif
144 int graphic_depth = 15;
145 int full_screen = 0;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 #ifdef TARGET_I386
149 int win2k_install_hack = 0;
150 #endif
151 int usb_enabled = 0;
152 static VLANState *first_vlan;
153 int smp_cpus = 1;
154 int vnc_display = -1;
155 #if defined(TARGET_SPARC)
156 #define MAX_CPUS 16
157 #elif defined(TARGET_I386)
158 #define MAX_CPUS 255
159 #else
160 #define MAX_CPUS 1
161 #endif
162 int acpi_enabled = 0;
163 int fd_bootchk = 1;
165 extern int vcpus;
167 int xc_handle;
169 time_t timeoffset = 0;
171 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
172 extern int domid;
174 char vncpasswd[64];
175 unsigned char challenge[AUTHCHALLENGESIZE];
177 /***********************************************************/
178 /* x86 ISA bus support */
180 target_phys_addr_t isa_mem_base = 0;
181 PicState2 *isa_pic;
183 uint32_t default_ioport_readb(void *opaque, uint32_t address)
184 {
185 #ifdef DEBUG_UNUSED_IOPORT
186 fprintf(stderr, "inb: port=0x%04x\n", address);
187 #endif
188 return 0xff;
189 }
191 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
192 {
193 #ifdef DEBUG_UNUSED_IOPORT
194 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
195 #endif
196 }
198 /* default is to make two byte accesses */
199 uint32_t default_ioport_readw(void *opaque, uint32_t address)
200 {
201 uint32_t data;
202 data = ioport_read_table[0][address](ioport_opaque[address], address);
203 address = (address + 1) & (MAX_IOPORTS - 1);
204 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
205 return data;
206 }
208 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
209 {
210 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
211 address = (address + 1) & (MAX_IOPORTS - 1);
212 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
213 }
215 uint32_t default_ioport_readl(void *opaque, uint32_t address)
216 {
217 #ifdef DEBUG_UNUSED_IOPORT
218 fprintf(stderr, "inl: port=0x%04x\n", address);
219 #endif
220 return 0xffffffff;
221 }
223 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
224 {
225 #ifdef DEBUG_UNUSED_IOPORT
226 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
227 #endif
228 }
230 void init_ioports(void)
231 {
232 int i;
234 for(i = 0; i < MAX_IOPORTS; i++) {
235 ioport_read_table[0][i] = default_ioport_readb;
236 ioport_write_table[0][i] = default_ioport_writeb;
237 ioport_read_table[1][i] = default_ioport_readw;
238 ioport_write_table[1][i] = default_ioport_writew;
239 ioport_read_table[2][i] = default_ioport_readl;
240 ioport_write_table[2][i] = default_ioport_writel;
241 }
242 }
244 /* size is the word size in byte */
245 int register_ioport_read(int start, int length, int size,
246 IOPortReadFunc *func, void *opaque)
247 {
248 int i, bsize;
250 if (size == 1) {
251 bsize = 0;
252 } else if (size == 2) {
253 bsize = 1;
254 } else if (size == 4) {
255 bsize = 2;
256 } else {
257 hw_error("register_ioport_read: invalid size");
258 return -1;
259 }
260 for(i = start; i < start + length; i += size) {
261 ioport_read_table[bsize][i] = func;
262 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
263 hw_error("register_ioport_read: invalid opaque");
264 ioport_opaque[i] = opaque;
265 }
266 return 0;
267 }
269 /* size is the word size in byte */
270 int register_ioport_write(int start, int length, int size,
271 IOPortWriteFunc *func, void *opaque)
272 {
273 int i, bsize;
275 if (size == 1) {
276 bsize = 0;
277 } else if (size == 2) {
278 bsize = 1;
279 } else if (size == 4) {
280 bsize = 2;
281 } else {
282 hw_error("register_ioport_write: invalid size");
283 return -1;
284 }
285 for(i = start; i < start + length; i += size) {
286 ioport_write_table[bsize][i] = func;
287 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
288 hw_error("register_ioport_read: invalid opaque");
289 ioport_opaque[i] = opaque;
290 }
291 return 0;
292 }
294 void isa_unassign_ioport(int start, int length)
295 {
296 int i;
298 for(i = start; i < start + length; i++) {
299 ioport_read_table[0][i] = default_ioport_readb;
300 ioport_read_table[1][i] = default_ioport_readw;
301 ioport_read_table[2][i] = default_ioport_readl;
303 ioport_write_table[0][i] = default_ioport_writeb;
304 ioport_write_table[1][i] = default_ioport_writew;
305 ioport_write_table[2][i] = default_ioport_writel;
306 }
307 }
309 /***********************************************************/
311 void pstrcpy(char *buf, int buf_size, const char *str)
312 {
313 int c;
314 char *q = buf;
316 if (buf_size <= 0)
317 return;
319 for(;;) {
320 c = *str++;
321 if (c == 0 || q >= buf + buf_size - 1)
322 break;
323 *q++ = c;
324 }
325 *q = '\0';
326 }
328 /* strcat and truncate. */
329 char *pstrcat(char *buf, int buf_size, const char *s)
330 {
331 int len;
332 len = strlen(buf);
333 if (len < buf_size)
334 pstrcpy(buf + len, buf_size - len, s);
335 return buf;
336 }
338 int strstart(const char *str, const char *val, const char **ptr)
339 {
340 const char *p, *q;
341 p = str;
342 q = val;
343 while (*q != '\0') {
344 if (*p != *q)
345 return 0;
346 p++;
347 q++;
348 }
349 if (ptr)
350 *ptr = p;
351 return 1;
352 }
354 void cpu_outb(CPUState *env, int addr, int val)
355 {
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outb: %04x %02x\n", addr, val);
359 #endif
360 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
365 }
367 void cpu_outw(CPUState *env, int addr, int val)
368 {
369 #ifdef DEBUG_IOPORT
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outw: %04x %04x\n", addr, val);
372 #endif
373 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
374 #ifdef USE_KQEMU
375 if (env)
376 env->last_io_time = cpu_get_time_fast();
377 #endif
378 }
380 void cpu_outl(CPUState *env, int addr, int val)
381 {
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "outl: %04x %08x\n", addr, val);
385 #endif
386 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
387 #ifdef USE_KQEMU
388 if (env)
389 env->last_io_time = cpu_get_time_fast();
390 #endif
391 }
393 int cpu_inb(CPUState *env, int addr)
394 {
395 int val;
396 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
397 #ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inb : %04x %02x\n", addr, val);
400 #endif
401 #ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
404 #endif
405 return val;
406 }
408 int cpu_inw(CPUState *env, int addr)
409 {
410 int val;
411 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inw : %04x %04x\n", addr, val);
415 #endif
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
420 return val;
421 }
423 int cpu_inl(CPUState *env, int addr)
424 {
425 int val;
426 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
427 #ifdef DEBUG_IOPORT
428 if (loglevel & CPU_LOG_IOPORT)
429 fprintf(logfile, "inl : %04x %08x\n", addr, val);
430 #endif
431 #ifdef USE_KQEMU
432 if (env)
433 env->last_io_time = cpu_get_time_fast();
434 #endif
435 return val;
436 }
438 /***********************************************************/
439 void hw_error(const char *fmt, ...)
440 {
441 va_list ap;
442 #ifndef CONFIG_DM
443 CPUState *env;
444 #endif /* !CONFIG_DM */
446 va_start(ap, fmt);
447 fprintf(stderr, "qemu: hardware error: ");
448 vfprintf(stderr, fmt, ap);
449 fprintf(stderr, "\n");
450 #ifndef CONFIG_DM
451 for(env = first_cpu; env != NULL; env = env->next_cpu) {
452 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
453 #ifdef TARGET_I386
454 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
455 #else
456 cpu_dump_state(env, stderr, fprintf, 0);
457 #endif
458 }
459 #endif /* !CONFIG_DM */
460 va_end(ap);
461 abort();
462 }
464 /***********************************************************/
465 /* keyboard/mouse */
467 static QEMUPutKBDEvent *qemu_put_kbd_event;
468 static void *qemu_put_kbd_event_opaque;
469 static QEMUPutMouseEvent *qemu_put_mouse_event;
470 static void *qemu_put_mouse_event_opaque;
471 static int qemu_put_mouse_event_absolute;
473 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
474 {
475 qemu_put_kbd_event_opaque = opaque;
476 qemu_put_kbd_event = func;
477 }
479 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
480 {
481 qemu_put_mouse_event_opaque = opaque;
482 qemu_put_mouse_event = func;
483 qemu_put_mouse_event_absolute = absolute;
484 }
486 void kbd_put_keycode(int keycode)
487 {
488 if (qemu_put_kbd_event) {
489 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
490 }
491 }
493 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
494 {
495 if (qemu_put_mouse_event) {
496 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
497 dx, dy, dz, buttons_state);
498 }
499 }
501 int kbd_mouse_is_absolute(void)
502 {
503 return qemu_put_mouse_event_absolute;
504 }
506 /* compute with 96 bit intermediate result: (a*b)/c */
507 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
508 {
509 union {
510 uint64_t ll;
511 struct {
512 #ifdef WORDS_BIGENDIAN
513 uint32_t high, low;
514 #else
515 uint32_t low, high;
516 #endif
517 } l;
518 } u, res;
519 uint64_t rl, rh;
521 u.ll = a;
522 rl = (uint64_t)u.l.low * (uint64_t)b;
523 rh = (uint64_t)u.l.high * (uint64_t)b;
524 rh += (rl >> 32);
525 res.l.high = rh / c;
526 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
527 return res.ll;
528 }
530 /***********************************************************/
531 /* real time host monotonic timer */
533 #define QEMU_TIMER_BASE 1000000000LL
535 #ifdef WIN32
537 static int64_t clock_freq;
539 static void init_get_clock(void)
540 {
541 LARGE_INTEGER freq;
542 int ret;
543 ret = QueryPerformanceFrequency(&freq);
544 if (ret == 0) {
545 fprintf(stderr, "Could not calibrate ticks\n");
546 exit(1);
547 }
548 clock_freq = freq.QuadPart;
549 }
551 static int64_t get_clock(void)
552 {
553 LARGE_INTEGER ti;
554 QueryPerformanceCounter(&ti);
555 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 }
558 #else
560 static int use_rt_clock;
562 static void init_get_clock(void)
563 {
564 use_rt_clock = 0;
565 #if defined(__linux__)
566 {
567 struct timespec ts;
568 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
569 use_rt_clock = 1;
570 }
571 }
572 #endif
573 }
575 static int64_t get_clock(void)
576 {
577 #if defined(__linux__)
578 if (use_rt_clock) {
579 struct timespec ts;
580 clock_gettime(CLOCK_MONOTONIC, &ts);
581 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
582 } else
583 #endif
584 {
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
587 struct timeval tv;
588 gettimeofday(&tv, NULL);
589 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
590 }
591 }
593 #endif
595 /***********************************************************/
596 /* guest cycle counter */
598 static int64_t cpu_ticks_prev;
599 static int64_t cpu_ticks_offset;
600 static int64_t cpu_clock_offset;
601 static int cpu_ticks_enabled;
603 /* return the host CPU cycle counter and handle stop/restart */
604 int64_t cpu_get_ticks(void)
605 {
606 if (!cpu_ticks_enabled) {
607 return cpu_ticks_offset;
608 } else {
609 int64_t ticks;
610 ticks = cpu_get_real_ticks();
611 if (cpu_ticks_prev > ticks) {
612 /* Note: non increasing ticks may happen if the host uses
613 software suspend */
614 cpu_ticks_offset += cpu_ticks_prev - ticks;
615 }
616 cpu_ticks_prev = ticks;
617 return ticks + cpu_ticks_offset;
618 }
619 }
621 /* return the host CPU monotonic timer and handle stop/restart */
622 static int64_t cpu_get_clock(void)
623 {
624 int64_t ti;
625 if (!cpu_ticks_enabled) {
626 return cpu_clock_offset;
627 } else {
628 ti = get_clock();
629 return ti + cpu_clock_offset;
630 }
631 }
633 /* enable cpu_get_ticks() */
634 void cpu_enable_ticks(void)
635 {
636 if (!cpu_ticks_enabled) {
637 cpu_ticks_offset -= cpu_get_real_ticks();
638 cpu_clock_offset -= get_clock();
639 cpu_ticks_enabled = 1;
640 }
641 }
643 /* disable cpu_get_ticks() : the clock is stopped. You must not call
644 cpu_get_ticks() after that. */
645 void cpu_disable_ticks(void)
646 {
647 if (cpu_ticks_enabled) {
648 cpu_ticks_offset = cpu_get_ticks();
649 cpu_clock_offset = cpu_get_clock();
650 cpu_ticks_enabled = 0;
651 }
652 }
654 /***********************************************************/
655 /* timers */
657 #define QEMU_TIMER_REALTIME 0
658 #define QEMU_TIMER_VIRTUAL 1
660 struct QEMUClock {
661 int type;
662 /* XXX: add frequency */
663 };
665 struct QEMUTimer {
666 QEMUClock *clock;
667 int64_t expire_time;
668 QEMUTimerCB *cb;
669 void *opaque;
670 struct QEMUTimer *next;
671 };
673 QEMUClock *rt_clock;
674 QEMUClock *vm_clock;
676 static QEMUTimer *active_timers[2];
677 #ifdef _WIN32
678 static MMRESULT timerID;
679 static HANDLE host_alarm = NULL;
680 static unsigned int period = 1;
681 #else
682 /* frequency of the times() clock tick */
683 static int timer_freq;
684 #endif
686 QEMUClock *qemu_new_clock(int type)
687 {
688 QEMUClock *clock;
689 clock = qemu_mallocz(sizeof(QEMUClock));
690 if (!clock)
691 return NULL;
692 clock->type = type;
693 return clock;
694 }
696 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
697 {
698 QEMUTimer *ts;
700 ts = qemu_mallocz(sizeof(QEMUTimer));
701 ts->clock = clock;
702 ts->cb = cb;
703 ts->opaque = opaque;
704 return ts;
705 }
707 void qemu_free_timer(QEMUTimer *ts)
708 {
709 qemu_free(ts);
710 }
712 /* stop a timer, but do not dealloc it */
713 void qemu_del_timer(QEMUTimer *ts)
714 {
715 QEMUTimer **pt, *t;
717 /* NOTE: this code must be signal safe because
718 qemu_timer_expired() can be called from a signal. */
719 pt = &active_timers[ts->clock->type];
720 for(;;) {
721 t = *pt;
722 if (!t)
723 break;
724 if (t == ts) {
725 *pt = t->next;
726 break;
727 }
728 pt = &t->next;
729 }
730 }
732 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
733 {
734 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
735 qemu_mod_timer(ts, expire_time);
736 }
738 /* modify the current timer so that it will be fired when current_time
739 >= expire_time. The corresponding callback will be called. */
740 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
741 {
742 QEMUTimer **pt, *t;
744 qemu_del_timer(ts);
746 /* add the timer in the sorted list */
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
750 for(;;) {
751 t = *pt;
752 if (!t)
753 break;
754 if (t->expire_time > expire_time)
755 break;
756 pt = &t->next;
757 }
758 ts->expire_time = expire_time;
759 ts->next = *pt;
760 *pt = ts;
761 }
763 int qemu_timer_pending(QEMUTimer *ts)
764 {
765 QEMUTimer *t;
766 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
767 if (t == ts)
768 return 1;
769 }
770 return 0;
771 }
773 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
774 {
775 if (!timer_head)
776 return 0;
777 return (timer_head->expire_time <= current_time);
778 }
780 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
781 {
782 QEMUTimer *ts;
784 for(;;) {
785 ts = *ptimer_head;
786 if (!ts || ts->expire_time > current_time)
787 break;
788 /* remove timer from the list before calling the callback */
789 *ptimer_head = ts->next;
790 ts->next = NULL;
792 /* run the callback (the timer list can be modified) */
793 ts->cb(ts->opaque);
794 }
795 }
797 int64_t qemu_get_clock(QEMUClock *clock)
798 {
799 switch(clock->type) {
800 case QEMU_TIMER_REALTIME:
801 return get_clock() / 1000000;
802 default:
803 case QEMU_TIMER_VIRTUAL:
804 return cpu_get_clock();
805 }
806 }
808 static void init_timers(void)
809 {
810 init_get_clock();
811 ticks_per_sec = QEMU_TIMER_BASE;
812 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
813 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
814 }
816 /* save a timer */
817 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
818 {
819 uint64_t expire_time;
821 if (qemu_timer_pending(ts)) {
822 expire_time = ts->expire_time;
823 } else {
824 expire_time = -1;
825 }
826 qemu_put_be64(f, expire_time);
827 }
829 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
830 {
831 uint64_t expire_time;
833 expire_time = qemu_get_be64(f);
834 if (expire_time != -1) {
835 qemu_mod_timer(ts, expire_time);
836 } else {
837 qemu_del_timer(ts);
838 }
839 }
841 #ifdef CONFIG_DM
842 static void timer_save(QEMUFile *f, void *opaque)
843 {
844 }
846 static int timer_load(QEMUFile *f, void *opaque, int version_id)
847 {
848 return 0;
849 }
850 #else /* !CONFIG_DM */
851 static void timer_save(QEMUFile *f, void *opaque)
852 {
853 if (cpu_ticks_enabled) {
854 hw_error("cannot save state if virtual timers are running");
855 }
856 qemu_put_be64s(f, &cpu_ticks_offset);
857 qemu_put_be64s(f, &ticks_per_sec);
858 }
860 static int timer_load(QEMUFile *f, void *opaque, int version_id)
861 {
862 if (version_id != 1)
863 return -EINVAL;
864 if (cpu_ticks_enabled) {
865 return -EINVAL;
866 }
867 qemu_get_be64s(f, &cpu_ticks_offset);
868 qemu_get_be64s(f, &ticks_per_sec);
869 return 0;
870 }
872 #ifdef _WIN32
873 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
874 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
875 #else
876 static void host_alarm_handler(int host_signum)
877 #endif
878 {
879 #if 0
880 #define DISP_FREQ 1000
881 {
882 static int64_t delta_min = INT64_MAX;
883 static int64_t delta_max, delta_cum, last_clock, delta, ti;
884 static int count;
885 ti = qemu_get_clock(vm_clock);
886 if (last_clock != 0) {
887 delta = ti - last_clock;
888 if (delta < delta_min)
889 delta_min = delta;
890 if (delta > delta_max)
891 delta_max = delta;
892 delta_cum += delta;
893 if (++count == DISP_FREQ) {
894 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
895 muldiv64(delta_min, 1000000, ticks_per_sec),
896 muldiv64(delta_max, 1000000, ticks_per_sec),
897 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
898 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
899 count = 0;
900 delta_min = INT64_MAX;
901 delta_max = 0;
902 delta_cum = 0;
903 }
904 }
905 last_clock = ti;
906 }
907 #endif
908 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
909 qemu_get_clock(vm_clock)) ||
910 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
911 qemu_get_clock(rt_clock))) {
912 #ifdef _WIN32
913 SetEvent(host_alarm);
914 #endif
915 CPUState *env = cpu_single_env;
916 if (env) {
917 /* stop the currently executing cpu because a timer occured */
918 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
919 #ifdef USE_KQEMU
920 if (env->kqemu_enabled) {
921 kqemu_cpu_interrupt(env);
922 }
923 #endif
924 }
925 }
926 }
928 #ifndef _WIN32
930 #if defined(__linux__)
932 #define RTC_FREQ 1024
934 static int rtc_fd;
936 static int start_rtc_timer(void)
937 {
938 rtc_fd = open("/dev/rtc", O_RDONLY);
939 if (rtc_fd < 0)
940 return -1;
941 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
942 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
943 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
944 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
945 goto fail;
946 }
947 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
948 fail:
949 close(rtc_fd);
950 return -1;
951 }
952 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
953 return 0;
954 }
956 #else
958 static int start_rtc_timer(void)
959 {
960 return -1;
961 }
963 #endif /* !defined(__linux__) */
965 #endif /* !defined(_WIN32) */
967 #endif /* !CONFIG_DM */
969 static void init_timer_alarm(void)
970 {
971 #ifdef _WIN32
972 {
973 int count=0;
974 TIMECAPS tc;
976 ZeroMemory(&tc, sizeof(TIMECAPS));
977 timeGetDevCaps(&tc, sizeof(TIMECAPS));
978 if (period < tc.wPeriodMin)
979 period = tc.wPeriodMin;
980 timeBeginPeriod(period);
981 timerID = timeSetEvent(1, // interval (ms)
982 period, // resolution
983 host_alarm_handler, // function
984 (DWORD)&count, // user parameter
985 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
986 if( !timerID ) {
987 perror("failed timer alarm");
988 exit(1);
989 }
990 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
991 if (!host_alarm) {
992 perror("failed CreateEvent");
993 exit(1);
994 }
995 qemu_add_wait_object(host_alarm, NULL, NULL);
996 }
997 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
998 #else
999 {
1000 #ifndef CONFIG_DM
1001 struct sigaction act;
1002 struct itimerval itv;
1003 #endif
1005 /* get times() syscall frequency */
1006 timer_freq = sysconf(_SC_CLK_TCK);
1008 #ifndef CONFIG_DM
1009 /* timer signal */
1010 sigfillset(&act.sa_mask);
1011 act.sa_flags = 0;
1012 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1013 act.sa_flags |= SA_ONSTACK;
1014 #endif
1015 act.sa_handler = host_alarm_handler;
1016 sigaction(SIGALRM, &act, NULL);
1018 itv.it_interval.tv_sec = 0;
1019 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1020 itv.it_value.tv_sec = 0;
1021 itv.it_value.tv_usec = 10 * 1000;
1022 setitimer(ITIMER_REAL, &itv, NULL);
1023 /* we probe the tick duration of the kernel to inform the user if
1024 the emulated kernel requested a too high timer frequency */
1025 getitimer(ITIMER_REAL, &itv);
1027 #if defined(__linux__)
1028 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1029 have timers with 1 ms resolution. The correct solution will
1030 be to use the POSIX real time timers available in recent
1031 2.6 kernels */
1032 if (itv.it_interval.tv_usec > 1000 || 1) {
1033 /* try to use /dev/rtc to have a faster timer */
1034 if (start_rtc_timer() < 0)
1035 goto use_itimer;
1036 /* disable itimer */
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 0;
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 0;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1043 /* use the RTC */
1044 sigaction(SIGIO, &act, NULL);
1045 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1046 fcntl(rtc_fd, F_SETOWN, getpid());
1047 } else
1048 #endif /* defined(__linux__) */
1050 use_itimer:
1051 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1052 PIT_FREQ) / 1000000;
1054 #endif /* CONFIG_DM */
1056 #endif
1059 void quit_timers(void)
1061 #ifdef _WIN32
1062 timeKillEvent(timerID);
1063 timeEndPeriod(period);
1064 if (host_alarm) {
1065 CloseHandle(host_alarm);
1066 host_alarm = NULL;
1068 #endif
1071 /***********************************************************/
1072 /* character device */
1074 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1076 return s->chr_write(s, buf, len);
1079 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1081 if (!s->chr_ioctl)
1082 return -ENOTSUP;
1083 return s->chr_ioctl(s, cmd, arg);
1086 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1088 char buf[4096];
1089 va_list ap;
1090 va_start(ap, fmt);
1091 vsnprintf(buf, sizeof(buf), fmt, ap);
1092 qemu_chr_write(s, buf, strlen(buf));
1093 va_end(ap);
1096 void qemu_chr_send_event(CharDriverState *s, int event)
1098 if (s->chr_send_event)
1099 s->chr_send_event(s, event);
1102 void qemu_chr_add_read_handler(CharDriverState *s,
1103 IOCanRWHandler *fd_can_read,
1104 IOReadHandler *fd_read, void *opaque)
1106 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1109 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1111 s->chr_event = chr_event;
1114 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1116 return len;
1119 static void null_chr_add_read_handler(CharDriverState *chr,
1120 IOCanRWHandler *fd_can_read,
1121 IOReadHandler *fd_read, void *opaque)
1125 CharDriverState *qemu_chr_open_null(void)
1127 CharDriverState *chr;
1129 chr = qemu_mallocz(sizeof(CharDriverState));
1130 if (!chr)
1131 return NULL;
1132 chr->chr_write = null_chr_write;
1133 chr->chr_add_read_handler = null_chr_add_read_handler;
1134 return chr;
1137 #ifdef _WIN32
1139 static void socket_cleanup(void)
1141 WSACleanup();
1144 static int socket_init(void)
1146 WSADATA Data;
1147 int ret, err;
1149 ret = WSAStartup(MAKEWORD(2,2), &Data);
1150 if (ret != 0) {
1151 err = WSAGetLastError();
1152 fprintf(stderr, "WSAStartup: %d\n", err);
1153 return -1;
1155 atexit(socket_cleanup);
1156 return 0;
1159 static int send_all(int fd, const uint8_t *buf, int len1)
1161 int ret, len;
1163 len = len1;
1164 while (len > 0) {
1165 ret = send(fd, buf, len, 0);
1166 if (ret < 0) {
1167 int errno;
1168 errno = WSAGetLastError();
1169 if (errno != WSAEWOULDBLOCK) {
1170 return -1;
1172 } else if (ret == 0) {
1173 break;
1174 } else {
1175 buf += ret;
1176 len -= ret;
1179 return len1 - len;
1182 void socket_set_nonblock(int fd)
1184 unsigned long opt = 1;
1185 ioctlsocket(fd, FIONBIO, &opt);
1188 #else
1190 static int unix_write(int fd, const uint8_t *buf, int len1)
1192 int ret, sel_ret, len;
1193 int max_fd;
1194 fd_set writefds;
1195 struct timeval timeout;
1197 max_fd = fd;
1199 len = len1;
1200 while (len > 0) {
1201 FD_ZERO(&writefds);
1202 FD_SET(fd, &writefds);
1203 timeout.tv_sec = 0;
1204 timeout.tv_usec = 0;
1205 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1206 if (sel_ret <= 0) {
1207 /* Timeout or select error */
1208 return -1;
1209 } else {
1210 ret = write(fd, buf, len);
1211 if (ret < 0) {
1212 if (errno != EINTR && errno != EAGAIN)
1213 return -1;
1214 } else if (ret == 0) {
1215 break;
1216 } else {
1217 buf += ret;
1218 len -= ret;
1222 return len1 - len;
1225 static inline int send_all(int fd, const uint8_t *buf, int len1)
1227 return unix_write(fd, buf, len1);
1230 void socket_set_nonblock(int fd)
1232 fcntl(fd, F_SETFL, O_NONBLOCK);
1234 #endif /* !_WIN32 */
1236 #ifndef _WIN32
1238 typedef struct {
1239 int fd_in, fd_out;
1240 IOCanRWHandler *fd_can_read;
1241 IOReadHandler *fd_read;
1242 void *fd_opaque;
1243 int max_size;
1244 } FDCharDriver;
1246 #define STDIO_MAX_CLIENTS 2
1248 static int stdio_nb_clients;
1249 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1251 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1253 FDCharDriver *s = chr->opaque;
1254 return unix_write(s->fd_out, buf, len);
1257 static int fd_chr_read_poll(void *opaque)
1259 CharDriverState *chr = opaque;
1260 FDCharDriver *s = chr->opaque;
1262 s->max_size = s->fd_can_read(s->fd_opaque);
1263 return s->max_size;
1266 static void fd_chr_read(void *opaque)
1268 CharDriverState *chr = opaque;
1269 FDCharDriver *s = chr->opaque;
1270 int size, len;
1271 uint8_t buf[1024];
1273 len = sizeof(buf);
1274 if (len > s->max_size)
1275 len = s->max_size;
1276 if (len == 0)
1277 return;
1278 size = read(s->fd_in, buf, len);
1279 if (size > 0) {
1280 s->fd_read(s->fd_opaque, buf, size);
1284 static void fd_chr_add_read_handler(CharDriverState *chr,
1285 IOCanRWHandler *fd_can_read,
1286 IOReadHandler *fd_read, void *opaque)
1288 FDCharDriver *s = chr->opaque;
1290 if (s->fd_in >= 0) {
1291 s->fd_can_read = fd_can_read;
1292 s->fd_read = fd_read;
1293 s->fd_opaque = opaque;
1294 if (nographic && s->fd_in == 0) {
1295 } else {
1296 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1297 fd_chr_read, NULL, chr);
1302 /* open a character device to a unix fd */
1303 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1305 CharDriverState *chr;
1306 FDCharDriver *s;
1308 chr = qemu_mallocz(sizeof(CharDriverState));
1309 if (!chr)
1310 return NULL;
1311 s = qemu_mallocz(sizeof(FDCharDriver));
1312 if (!s) {
1313 free(chr);
1314 return NULL;
1316 s->fd_in = fd_in;
1317 s->fd_out = fd_out;
1318 chr->opaque = s;
1319 chr->chr_write = fd_chr_write;
1320 chr->chr_add_read_handler = fd_chr_add_read_handler;
1321 return chr;
1324 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1326 int fd_out;
1328 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1329 if (fd_out < 0)
1330 return NULL;
1331 return qemu_chr_open_fd(-1, fd_out);
1334 CharDriverState *qemu_chr_open_pipe(const char *filename)
1336 int fd;
1338 fd = open(filename, O_RDWR | O_BINARY);
1339 if (fd < 0)
1340 return NULL;
1341 return qemu_chr_open_fd(fd, fd);
1345 /* for STDIO, we handle the case where several clients use it
1346 (nographic mode) */
1348 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1350 #define TERM_FIFO_MAX_SIZE 1
1352 static int term_got_escape, client_index;
1353 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1354 static int term_fifo_size;
1355 static int term_timestamps;
1356 static int64_t term_timestamps_start;
1358 void term_print_help(void)
1360 printf("\n"
1361 "C-a h print this help\n"
1362 "C-a x exit emulator\n"
1363 "C-a s save disk data back to file (if -snapshot)\n"
1364 "C-a b send break (magic sysrq)\n"
1365 "C-a t toggle console timestamps\n"
1366 "C-a c switch between console and monitor\n"
1367 "C-a C-a send C-a\n"
1368 );
1371 /* called when a char is received */
1372 static void stdio_received_byte(int ch)
1374 if (term_got_escape) {
1375 term_got_escape = 0;
1376 switch(ch) {
1377 case 'h':
1378 term_print_help();
1379 break;
1380 case 'x':
1381 exit(0);
1382 break;
1383 case 's':
1385 int i;
1386 for (i = 0; i < MAX_DISKS; i++) {
1387 if (bs_table[i])
1388 bdrv_commit(bs_table[i]);
1391 break;
1392 case 'b':
1393 if (client_index < stdio_nb_clients) {
1394 CharDriverState *chr;
1395 FDCharDriver *s;
1397 chr = stdio_clients[client_index];
1398 s = chr->opaque;
1399 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1401 break;
1402 case 'c':
1403 client_index++;
1404 if (client_index >= stdio_nb_clients)
1405 client_index = 0;
1406 if (client_index == 0) {
1407 /* send a new line in the monitor to get the prompt */
1408 ch = '\r';
1409 goto send_char;
1411 break;
1412 case 't':
1413 term_timestamps = !term_timestamps;
1414 term_timestamps_start = -1;
1415 break;
1416 case TERM_ESCAPE:
1417 goto send_char;
1419 } else if (ch == TERM_ESCAPE) {
1420 term_got_escape = 1;
1421 } else {
1422 send_char:
1423 if (client_index < stdio_nb_clients) {
1424 uint8_t buf[1];
1425 CharDriverState *chr;
1426 FDCharDriver *s;
1428 chr = stdio_clients[client_index];
1429 s = chr->opaque;
1430 if (s->fd_can_read(s->fd_opaque) > 0) {
1431 buf[0] = ch;
1432 s->fd_read(s->fd_opaque, buf, 1);
1433 } else if (term_fifo_size == 0) {
1434 term_fifo[term_fifo_size++] = ch;
1440 static int stdio_read_poll(void *opaque)
1442 CharDriverState *chr;
1443 FDCharDriver *s;
1445 if (client_index < stdio_nb_clients) {
1446 chr = stdio_clients[client_index];
1447 s = chr->opaque;
1448 /* try to flush the queue if needed */
1449 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1450 s->fd_read(s->fd_opaque, term_fifo, 1);
1451 term_fifo_size = 0;
1453 /* see if we can absorb more chars */
1454 if (term_fifo_size == 0)
1455 return 1;
1456 else
1457 return 0;
1458 } else {
1459 return 1;
1463 static void stdio_read(void *opaque)
1465 int size;
1466 uint8_t buf[1];
1468 size = read(0, buf, 1);
1469 if (size > 0)
1470 stdio_received_byte(buf[0]);
1473 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1475 FDCharDriver *s = chr->opaque;
1476 if (!term_timestamps) {
1477 return unix_write(s->fd_out, buf, len);
1478 } else {
1479 int i;
1480 char buf1[64];
1482 for(i = 0; i < len; i++) {
1483 unix_write(s->fd_out, buf + i, 1);
1484 if (buf[i] == '\n') {
1485 int64_t ti;
1486 int secs;
1488 ti = get_clock();
1489 if (term_timestamps_start == -1)
1490 term_timestamps_start = ti;
1491 ti -= term_timestamps_start;
1492 secs = ti / 1000000000;
1493 snprintf(buf1, sizeof(buf1),
1494 "[%02d:%02d:%02d.%03d] ",
1495 secs / 3600,
1496 (secs / 60) % 60,
1497 secs % 60,
1498 (int)((ti / 1000000) % 1000));
1499 unix_write(s->fd_out, buf1, strlen(buf1));
1502 return len;
1506 /* init terminal so that we can grab keys */
1507 static struct termios oldtty;
1508 static int old_fd0_flags;
1510 static void term_exit(void)
1512 tcsetattr (0, TCSANOW, &oldtty);
1513 fcntl(0, F_SETFL, old_fd0_flags);
1516 static void term_init(void)
1518 struct termios tty;
1520 tcgetattr (0, &tty);
1521 oldtty = tty;
1522 old_fd0_flags = fcntl(0, F_GETFL);
1524 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1525 |INLCR|IGNCR|ICRNL|IXON);
1526 tty.c_oflag |= OPOST;
1527 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1528 /* if graphical mode, we allow Ctrl-C handling */
1529 if (nographic)
1530 tty.c_lflag &= ~ISIG;
1531 tty.c_cflag &= ~(CSIZE|PARENB);
1532 tty.c_cflag |= CS8;
1533 tty.c_cc[VMIN] = 1;
1534 tty.c_cc[VTIME] = 0;
1536 tcsetattr (0, TCSANOW, &tty);
1538 atexit(term_exit);
1540 fcntl(0, F_SETFL, O_NONBLOCK);
1543 CharDriverState *qemu_chr_open_stdio(void)
1545 CharDriverState *chr;
1547 if (nographic) {
1548 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1549 return NULL;
1550 chr = qemu_chr_open_fd(0, 1);
1551 chr->chr_write = stdio_write;
1552 if (stdio_nb_clients == 0)
1553 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1554 client_index = stdio_nb_clients;
1555 } else {
1556 if (stdio_nb_clients != 0)
1557 return NULL;
1558 chr = qemu_chr_open_fd(0, 1);
1560 stdio_clients[stdio_nb_clients++] = chr;
1561 if (stdio_nb_clients == 1) {
1562 /* set the terminal in raw mode */
1563 term_init();
1565 return chr;
1568 int store_console_dev(int domid, char *pts)
1570 int xc_handle;
1571 struct xs_handle *xs;
1572 char *path;
1574 xs = xs_daemon_open();
1575 if (xs == NULL) {
1576 fprintf(logfile, "Could not contact XenStore\n");
1577 return -1;
1580 xc_handle = xc_interface_open();
1581 if (xc_handle == -1) {
1582 fprintf(logfile, "xc_interface_open() error\n");
1583 return -1;
1586 path = xs_get_domain_path(xs, domid);
1587 if (path == NULL) {
1588 fprintf(logfile, "xs_get_domain_path() error\n");
1589 return -1;
1591 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1592 if (path == NULL) {
1593 fprintf(logfile, "realloc error\n");
1594 return -1;
1596 strcat(path, "/console/tty");
1597 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1598 fprintf(logfile, "xs_write for console fail");
1599 return -1;
1602 free(path);
1603 xs_daemon_close(xs);
1604 close(xc_handle);
1606 return 0;
1609 #if defined(__linux__)
1610 CharDriverState *qemu_chr_open_pty(void)
1612 struct termios tty;
1613 int master_fd, slave_fd;
1615 /* Not satisfying */
1616 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1617 return NULL;
1620 /* Set raw attributes on the pty. */
1621 cfmakeraw(&tty);
1622 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1624 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1625 store_console_dev(domid, ptsname(master_fd));
1627 return qemu_chr_open_fd(master_fd, master_fd);
1630 static void tty_serial_init(int fd, int speed,
1631 int parity, int data_bits, int stop_bits)
1633 struct termios tty;
1634 speed_t spd;
1636 #if 0
1637 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1638 speed, parity, data_bits, stop_bits);
1639 #endif
1640 tcgetattr (fd, &tty);
1642 switch(speed) {
1643 case 50:
1644 spd = B50;
1645 break;
1646 case 75:
1647 spd = B75;
1648 break;
1649 case 300:
1650 spd = B300;
1651 break;
1652 case 600:
1653 spd = B600;
1654 break;
1655 case 1200:
1656 spd = B1200;
1657 break;
1658 case 2400:
1659 spd = B2400;
1660 break;
1661 case 4800:
1662 spd = B4800;
1663 break;
1664 case 9600:
1665 spd = B9600;
1666 break;
1667 case 19200:
1668 spd = B19200;
1669 break;
1670 case 38400:
1671 spd = B38400;
1672 break;
1673 case 57600:
1674 spd = B57600;
1675 break;
1676 default:
1677 case 115200:
1678 spd = B115200;
1679 break;
1682 cfsetispeed(&tty, spd);
1683 cfsetospeed(&tty, spd);
1685 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1686 |INLCR|IGNCR|ICRNL|IXON);
1687 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1688 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1689 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1690 switch(data_bits) {
1691 default:
1692 case 8:
1693 tty.c_cflag |= CS8;
1694 break;
1695 case 7:
1696 tty.c_cflag |= CS7;
1697 break;
1698 case 6:
1699 tty.c_cflag |= CS6;
1700 break;
1701 case 5:
1702 tty.c_cflag |= CS5;
1703 break;
1705 switch(parity) {
1706 default:
1707 case 'N':
1708 break;
1709 case 'E':
1710 tty.c_cflag |= PARENB;
1711 break;
1712 case 'O':
1713 tty.c_cflag |= PARENB | PARODD;
1714 break;
1717 tcsetattr (fd, TCSANOW, &tty);
1720 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1722 FDCharDriver *s = chr->opaque;
1724 switch(cmd) {
1725 case CHR_IOCTL_SERIAL_SET_PARAMS:
1727 QEMUSerialSetParams *ssp = arg;
1728 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1729 ssp->data_bits, ssp->stop_bits);
1731 break;
1732 case CHR_IOCTL_SERIAL_SET_BREAK:
1734 int enable = *(int *)arg;
1735 if (enable)
1736 tcsendbreak(s->fd_in, 1);
1738 break;
1739 default:
1740 return -ENOTSUP;
1742 return 0;
1745 CharDriverState *qemu_chr_open_tty(const char *filename)
1747 CharDriverState *chr;
1748 int fd;
1750 fd = open(filename, O_RDWR | O_NONBLOCK);
1751 if (fd < 0)
1752 return NULL;
1753 fcntl(fd, F_SETFL, O_NONBLOCK);
1754 tty_serial_init(fd, 115200, 'N', 8, 1);
1755 chr = qemu_chr_open_fd(fd, fd);
1756 if (!chr)
1757 return NULL;
1758 chr->chr_ioctl = tty_serial_ioctl;
1759 return chr;
1762 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1764 int fd = (int)chr->opaque;
1765 uint8_t b;
1767 switch(cmd) {
1768 case CHR_IOCTL_PP_READ_DATA:
1769 if (ioctl(fd, PPRDATA, &b) < 0)
1770 return -ENOTSUP;
1771 *(uint8_t *)arg = b;
1772 break;
1773 case CHR_IOCTL_PP_WRITE_DATA:
1774 b = *(uint8_t *)arg;
1775 if (ioctl(fd, PPWDATA, &b) < 0)
1776 return -ENOTSUP;
1777 break;
1778 case CHR_IOCTL_PP_READ_CONTROL:
1779 if (ioctl(fd, PPRCONTROL, &b) < 0)
1780 return -ENOTSUP;
1781 *(uint8_t *)arg = b;
1782 break;
1783 case CHR_IOCTL_PP_WRITE_CONTROL:
1784 b = *(uint8_t *)arg;
1785 if (ioctl(fd, PPWCONTROL, &b) < 0)
1786 return -ENOTSUP;
1787 break;
1788 case CHR_IOCTL_PP_READ_STATUS:
1789 if (ioctl(fd, PPRSTATUS, &b) < 0)
1790 return -ENOTSUP;
1791 *(uint8_t *)arg = b;
1792 break;
1793 default:
1794 return -ENOTSUP;
1796 return 0;
1799 CharDriverState *qemu_chr_open_pp(const char *filename)
1801 CharDriverState *chr;
1802 int fd;
1804 fd = open(filename, O_RDWR);
1805 if (fd < 0)
1806 return NULL;
1808 if (ioctl(fd, PPCLAIM) < 0) {
1809 close(fd);
1810 return NULL;
1813 chr = qemu_mallocz(sizeof(CharDriverState));
1814 if (!chr) {
1815 close(fd);
1816 return NULL;
1818 chr->opaque = (void *)fd;
1819 chr->chr_write = null_chr_write;
1820 chr->chr_add_read_handler = null_chr_add_read_handler;
1821 chr->chr_ioctl = pp_ioctl;
1822 return chr;
1825 #else
1826 CharDriverState *qemu_chr_open_pty(void)
1828 return NULL;
1830 #endif
1832 #endif /* !defined(_WIN32) */
1834 #ifdef _WIN32
1835 typedef struct {
1836 IOCanRWHandler *fd_can_read;
1837 IOReadHandler *fd_read;
1838 void *win_opaque;
1839 int max_size;
1840 HANDLE hcom, hrecv, hsend;
1841 OVERLAPPED orecv, osend;
1842 BOOL fpipe;
1843 DWORD len;
1844 } WinCharState;
1846 #define NSENDBUF 2048
1847 #define NRECVBUF 2048
1848 #define MAXCONNECT 1
1849 #define NTIMEOUT 5000
1851 static int win_chr_poll(void *opaque);
1852 static int win_chr_pipe_poll(void *opaque);
1854 static void win_chr_close2(WinCharState *s)
1856 if (s->hsend) {
1857 CloseHandle(s->hsend);
1858 s->hsend = NULL;
1860 if (s->hrecv) {
1861 CloseHandle(s->hrecv);
1862 s->hrecv = NULL;
1864 if (s->hcom) {
1865 CloseHandle(s->hcom);
1866 s->hcom = NULL;
1868 if (s->fpipe)
1869 qemu_del_polling_cb(win_chr_pipe_poll, s);
1870 else
1871 qemu_del_polling_cb(win_chr_poll, s);
1874 static void win_chr_close(CharDriverState *chr)
1876 WinCharState *s = chr->opaque;
1877 win_chr_close2(s);
1880 static int win_chr_init(WinCharState *s, const char *filename)
1882 COMMCONFIG comcfg;
1883 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1884 COMSTAT comstat;
1885 DWORD size;
1886 DWORD err;
1888 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1889 if (!s->hsend) {
1890 fprintf(stderr, "Failed CreateEvent\n");
1891 goto fail;
1893 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1894 if (!s->hrecv) {
1895 fprintf(stderr, "Failed CreateEvent\n");
1896 goto fail;
1899 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1900 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1901 if (s->hcom == INVALID_HANDLE_VALUE) {
1902 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1903 s->hcom = NULL;
1904 goto fail;
1907 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1908 fprintf(stderr, "Failed SetupComm\n");
1909 goto fail;
1912 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1913 size = sizeof(COMMCONFIG);
1914 GetDefaultCommConfig(filename, &comcfg, &size);
1915 comcfg.dcb.DCBlength = sizeof(DCB);
1916 CommConfigDialog(filename, NULL, &comcfg);
1918 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1919 fprintf(stderr, "Failed SetCommState\n");
1920 goto fail;
1923 if (!SetCommMask(s->hcom, EV_ERR)) {
1924 fprintf(stderr, "Failed SetCommMask\n");
1925 goto fail;
1928 cto.ReadIntervalTimeout = MAXDWORD;
1929 if (!SetCommTimeouts(s->hcom, &cto)) {
1930 fprintf(stderr, "Failed SetCommTimeouts\n");
1931 goto fail;
1934 if (!ClearCommError(s->hcom, &err, &comstat)) {
1935 fprintf(stderr, "Failed ClearCommError\n");
1936 goto fail;
1938 qemu_add_polling_cb(win_chr_poll, s);
1939 return 0;
1941 fail:
1942 win_chr_close2(s);
1943 return -1;
1946 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1948 WinCharState *s = chr->opaque;
1949 DWORD len, ret, size, err;
1951 len = len1;
1952 ZeroMemory(&s->osend, sizeof(s->osend));
1953 s->osend.hEvent = s->hsend;
1954 while (len > 0) {
1955 if (s->hsend)
1956 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1957 else
1958 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1959 if (!ret) {
1960 err = GetLastError();
1961 if (err == ERROR_IO_PENDING) {
1962 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1963 if (ret) {
1964 buf += size;
1965 len -= size;
1966 } else {
1967 break;
1969 } else {
1970 break;
1972 } else {
1973 buf += size;
1974 len -= size;
1977 return len1 - len;
1980 static int win_chr_read_poll(WinCharState *s)
1982 s->max_size = s->fd_can_read(s->win_opaque);
1983 return s->max_size;
1986 static void win_chr_readfile(WinCharState *s)
1988 int ret, err;
1989 uint8_t buf[1024];
1990 DWORD size;
1992 ZeroMemory(&s->orecv, sizeof(s->orecv));
1993 s->orecv.hEvent = s->hrecv;
1994 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1995 if (!ret) {
1996 err = GetLastError();
1997 if (err == ERROR_IO_PENDING) {
1998 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2002 if (size > 0) {
2003 s->fd_read(s->win_opaque, buf, size);
2007 static void win_chr_read(WinCharState *s)
2009 if (s->len > s->max_size)
2010 s->len = s->max_size;
2011 if (s->len == 0)
2012 return;
2014 win_chr_readfile(s);
2017 static int win_chr_poll(void *opaque)
2019 WinCharState *s = opaque;
2020 COMSTAT status;
2021 DWORD comerr;
2023 ClearCommError(s->hcom, &comerr, &status);
2024 if (status.cbInQue > 0) {
2025 s->len = status.cbInQue;
2026 win_chr_read_poll(s);
2027 win_chr_read(s);
2028 return 1;
2030 return 0;
2033 static void win_chr_add_read_handler(CharDriverState *chr,
2034 IOCanRWHandler *fd_can_read,
2035 IOReadHandler *fd_read, void *opaque)
2037 WinCharState *s = chr->opaque;
2039 s->fd_can_read = fd_can_read;
2040 s->fd_read = fd_read;
2041 s->win_opaque = opaque;
2044 CharDriverState *qemu_chr_open_win(const char *filename)
2046 CharDriverState *chr;
2047 WinCharState *s;
2049 chr = qemu_mallocz(sizeof(CharDriverState));
2050 if (!chr)
2051 return NULL;
2052 s = qemu_mallocz(sizeof(WinCharState));
2053 if (!s) {
2054 free(chr);
2055 return NULL;
2057 chr->opaque = s;
2058 chr->chr_write = win_chr_write;
2059 chr->chr_add_read_handler = win_chr_add_read_handler;
2060 chr->chr_close = win_chr_close;
2062 if (win_chr_init(s, filename) < 0) {
2063 free(s);
2064 free(chr);
2065 return NULL;
2067 return chr;
2070 static int win_chr_pipe_poll(void *opaque)
2072 WinCharState *s = opaque;
2073 DWORD size;
2075 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2076 if (size > 0) {
2077 s->len = size;
2078 win_chr_read_poll(s);
2079 win_chr_read(s);
2080 return 1;
2082 return 0;
2085 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2087 OVERLAPPED ov;
2088 int ret;
2089 DWORD size;
2090 char openname[256];
2092 s->fpipe = TRUE;
2094 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2095 if (!s->hsend) {
2096 fprintf(stderr, "Failed CreateEvent\n");
2097 goto fail;
2099 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2100 if (!s->hrecv) {
2101 fprintf(stderr, "Failed CreateEvent\n");
2102 goto fail;
2105 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2106 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2107 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2108 PIPE_WAIT,
2109 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2110 if (s->hcom == INVALID_HANDLE_VALUE) {
2111 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2112 s->hcom = NULL;
2113 goto fail;
2116 ZeroMemory(&ov, sizeof(ov));
2117 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2118 ret = ConnectNamedPipe(s->hcom, &ov);
2119 if (ret) {
2120 fprintf(stderr, "Failed ConnectNamedPipe\n");
2121 goto fail;
2124 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2125 if (!ret) {
2126 fprintf(stderr, "Failed GetOverlappedResult\n");
2127 if (ov.hEvent) {
2128 CloseHandle(ov.hEvent);
2129 ov.hEvent = NULL;
2131 goto fail;
2134 if (ov.hEvent) {
2135 CloseHandle(ov.hEvent);
2136 ov.hEvent = NULL;
2138 qemu_add_polling_cb(win_chr_pipe_poll, s);
2139 return 0;
2141 fail:
2142 win_chr_close2(s);
2143 return -1;
2147 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2149 CharDriverState *chr;
2150 WinCharState *s;
2152 chr = qemu_mallocz(sizeof(CharDriverState));
2153 if (!chr)
2154 return NULL;
2155 s = qemu_mallocz(sizeof(WinCharState));
2156 if (!s) {
2157 free(chr);
2158 return NULL;
2160 chr->opaque = s;
2161 chr->chr_write = win_chr_write;
2162 chr->chr_add_read_handler = win_chr_add_read_handler;
2163 chr->chr_close = win_chr_close;
2165 if (win_chr_pipe_init(s, filename) < 0) {
2166 free(s);
2167 free(chr);
2168 return NULL;
2170 return chr;
2173 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2175 CharDriverState *chr;
2176 WinCharState *s;
2178 chr = qemu_mallocz(sizeof(CharDriverState));
2179 if (!chr)
2180 return NULL;
2181 s = qemu_mallocz(sizeof(WinCharState));
2182 if (!s) {
2183 free(chr);
2184 return NULL;
2186 s->hcom = fd_out;
2187 chr->opaque = s;
2188 chr->chr_write = win_chr_write;
2189 chr->chr_add_read_handler = win_chr_add_read_handler;
2190 return chr;
2193 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2195 HANDLE fd_out;
2197 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2198 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2199 if (fd_out == INVALID_HANDLE_VALUE)
2200 return NULL;
2202 return qemu_chr_open_win_file(fd_out);
2204 #endif
2206 /***********************************************************/
2207 /* UDP Net console */
2209 typedef struct {
2210 IOCanRWHandler *fd_can_read;
2211 IOReadHandler *fd_read;
2212 void *fd_opaque;
2213 int fd;
2214 struct sockaddr_in daddr;
2215 char buf[1024];
2216 int bufcnt;
2217 int bufptr;
2218 int max_size;
2219 } NetCharDriver;
2221 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2223 NetCharDriver *s = chr->opaque;
2225 return sendto(s->fd, buf, len, 0,
2226 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2229 static int udp_chr_read_poll(void *opaque)
2231 CharDriverState *chr = opaque;
2232 NetCharDriver *s = chr->opaque;
2234 s->max_size = s->fd_can_read(s->fd_opaque);
2236 /* If there were any stray characters in the queue process them
2237 * first
2238 */
2239 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2240 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2241 s->bufptr++;
2242 s->max_size = s->fd_can_read(s->fd_opaque);
2244 return s->max_size;
2247 static void udp_chr_read(void *opaque)
2249 CharDriverState *chr = opaque;
2250 NetCharDriver *s = chr->opaque;
2252 if (s->max_size == 0)
2253 return;
2254 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2255 s->bufptr = s->bufcnt;
2256 if (s->bufcnt <= 0)
2257 return;
2259 s->bufptr = 0;
2260 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2261 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2262 s->bufptr++;
2263 s->max_size = s->fd_can_read(s->fd_opaque);
2267 static void udp_chr_add_read_handler(CharDriverState *chr,
2268 IOCanRWHandler *fd_can_read,
2269 IOReadHandler *fd_read, void *opaque)
2271 NetCharDriver *s = chr->opaque;
2273 if (s->fd >= 0) {
2274 s->fd_can_read = fd_can_read;
2275 s->fd_read = fd_read;
2276 s->fd_opaque = opaque;
2277 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2278 udp_chr_read, NULL, chr);
2282 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2283 int parse_host_src_port(struct sockaddr_in *haddr,
2284 struct sockaddr_in *saddr,
2285 const char *str);
2287 CharDriverState *qemu_chr_open_udp(const char *def)
2289 CharDriverState *chr = NULL;
2290 NetCharDriver *s = NULL;
2291 int fd = -1;
2292 struct sockaddr_in saddr;
2294 chr = qemu_mallocz(sizeof(CharDriverState));
2295 if (!chr)
2296 goto return_err;
2297 s = qemu_mallocz(sizeof(NetCharDriver));
2298 if (!s)
2299 goto return_err;
2301 fd = socket(PF_INET, SOCK_DGRAM, 0);
2302 if (fd < 0) {
2303 perror("socket(PF_INET, SOCK_DGRAM)");
2304 goto return_err;
2307 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2308 printf("Could not parse: %s\n", def);
2309 goto return_err;
2312 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2314 perror("bind");
2315 goto return_err;
2318 s->fd = fd;
2319 s->bufcnt = 0;
2320 s->bufptr = 0;
2321 chr->opaque = s;
2322 chr->chr_write = udp_chr_write;
2323 chr->chr_add_read_handler = udp_chr_add_read_handler;
2324 return chr;
2326 return_err:
2327 if (chr)
2328 free(chr);
2329 if (s)
2330 free(s);
2331 if (fd >= 0)
2332 closesocket(fd);
2333 return NULL;
2336 /***********************************************************/
2337 /* TCP Net console */
2339 typedef struct {
2340 IOCanRWHandler *fd_can_read;
2341 IOReadHandler *fd_read;
2342 void *fd_opaque;
2343 int fd, listen_fd;
2344 int connected;
2345 int max_size;
2346 int do_telnetopt;
2347 } TCPCharDriver;
2349 static void tcp_chr_accept(void *opaque);
2351 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2353 TCPCharDriver *s = chr->opaque;
2354 if (s->connected) {
2355 return send_all(s->fd, buf, len);
2356 } else {
2357 /* XXX: indicate an error ? */
2358 return len;
2362 static int tcp_chr_read_poll(void *opaque)
2364 CharDriverState *chr = opaque;
2365 TCPCharDriver *s = chr->opaque;
2366 if (!s->connected)
2367 return 0;
2368 s->max_size = s->fd_can_read(s->fd_opaque);
2369 return s->max_size;
2372 #define IAC 255
2373 #define IAC_BREAK 243
2374 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2375 TCPCharDriver *s,
2376 char *buf, int *size)
2378 /* Handle any telnet client's basic IAC options to satisfy char by
2379 * char mode with no echo. All IAC options will be removed from
2380 * the buf and the do_telnetopt variable will be used to track the
2381 * state of the width of the IAC information.
2383 * IAC commands come in sets of 3 bytes with the exception of the
2384 * "IAC BREAK" command and the double IAC.
2385 */
2387 int i;
2388 int j = 0;
2390 for (i = 0; i < *size; i++) {
2391 if (s->do_telnetopt > 1) {
2392 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2393 /* Double IAC means send an IAC */
2394 if (j != i)
2395 buf[j] = buf[i];
2396 j++;
2397 s->do_telnetopt = 1;
2398 } else {
2399 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2400 /* Handle IAC break commands by sending a serial break */
2401 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2402 s->do_telnetopt++;
2404 s->do_telnetopt++;
2406 if (s->do_telnetopt >= 4) {
2407 s->do_telnetopt = 1;
2409 } else {
2410 if ((unsigned char)buf[i] == IAC) {
2411 s->do_telnetopt = 2;
2412 } else {
2413 if (j != i)
2414 buf[j] = buf[i];
2415 j++;
2419 *size = j;
2422 static void tcp_chr_read(void *opaque)
2424 CharDriverState *chr = opaque;
2425 TCPCharDriver *s = chr->opaque;
2426 uint8_t buf[1024];
2427 int len, size;
2429 if (!s->connected || s->max_size <= 0)
2430 return;
2431 len = sizeof(buf);
2432 if (len > s->max_size)
2433 len = s->max_size;
2434 size = recv(s->fd, buf, len, 0);
2435 if (size == 0) {
2436 /* connection closed */
2437 s->connected = 0;
2438 if (s->listen_fd >= 0) {
2439 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2441 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2442 closesocket(s->fd);
2443 s->fd = -1;
2444 } else if (size > 0) {
2445 if (s->do_telnetopt)
2446 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2447 if (size > 0)
2448 s->fd_read(s->fd_opaque, buf, size);
2452 static void tcp_chr_add_read_handler(CharDriverState *chr,
2453 IOCanRWHandler *fd_can_read,
2454 IOReadHandler *fd_read, void *opaque)
2456 TCPCharDriver *s = chr->opaque;
2458 s->fd_can_read = fd_can_read;
2459 s->fd_read = fd_read;
2460 s->fd_opaque = opaque;
2463 static void tcp_chr_connect(void *opaque)
2465 CharDriverState *chr = opaque;
2466 TCPCharDriver *s = chr->opaque;
2468 s->connected = 1;
2469 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2470 tcp_chr_read, NULL, chr);
2473 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2474 static void tcp_chr_telnet_init(int fd)
2476 char buf[3];
2477 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2478 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2479 send(fd, (char *)buf, 3, 0);
2480 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2481 send(fd, (char *)buf, 3, 0);
2482 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2483 send(fd, (char *)buf, 3, 0);
2484 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2485 send(fd, (char *)buf, 3, 0);
2488 static void tcp_chr_accept(void *opaque)
2490 CharDriverState *chr = opaque;
2491 TCPCharDriver *s = chr->opaque;
2492 struct sockaddr_in saddr;
2493 socklen_t len;
2494 int fd;
2496 for(;;) {
2497 len = sizeof(saddr);
2498 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2499 if (fd < 0 && errno != EINTR) {
2500 return;
2501 } else if (fd >= 0) {
2502 if (s->do_telnetopt)
2503 tcp_chr_telnet_init(fd);
2504 break;
2507 socket_set_nonblock(fd);
2508 s->fd = fd;
2509 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2510 tcp_chr_connect(chr);
2513 static void tcp_chr_close(CharDriverState *chr)
2515 TCPCharDriver *s = chr->opaque;
2516 if (s->fd >= 0)
2517 closesocket(s->fd);
2518 if (s->listen_fd >= 0)
2519 closesocket(s->listen_fd);
2520 qemu_free(s);
2523 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2524 int is_telnet)
2526 CharDriverState *chr = NULL;
2527 TCPCharDriver *s = NULL;
2528 int fd = -1, ret, err, val;
2529 int is_listen = 0;
2530 int is_waitconnect = 1;
2531 const char *ptr;
2532 struct sockaddr_in saddr;
2533 int opt;
2535 if (parse_host_port(&saddr, host_str) < 0)
2536 goto fail;
2538 ptr = host_str;
2539 while((ptr = strchr(ptr,','))) {
2540 ptr++;
2541 if (!strncmp(ptr,"server",6)) {
2542 is_listen = 1;
2543 } else if (!strncmp(ptr,"nowait",6)) {
2544 is_waitconnect = 0;
2545 } else {
2546 printf("Unknown option: %s\n", ptr);
2547 goto fail;
2550 if (!is_listen)
2551 is_waitconnect = 0;
2553 chr = qemu_mallocz(sizeof(CharDriverState));
2554 if (!chr)
2555 goto fail;
2556 s = qemu_mallocz(sizeof(TCPCharDriver));
2557 if (!s)
2558 goto fail;
2560 fd = socket(PF_INET, SOCK_STREAM, 0);
2561 if (fd < 0)
2562 goto fail;
2564 if (!is_waitconnect)
2565 socket_set_nonblock(fd);
2567 s->connected = 0;
2568 s->fd = -1;
2569 s->listen_fd = -1;
2570 if (is_listen) {
2571 /* allow fast reuse */
2572 val = 1;
2573 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2575 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2576 if (ret < 0)
2577 goto fail;
2578 ret = listen(fd, 0);
2579 if (ret < 0)
2580 goto fail;
2581 s->listen_fd = fd;
2582 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2583 if (is_telnet)
2584 s->do_telnetopt = 1;
2585 } else {
2586 for(;;) {
2587 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2588 if (ret < 0) {
2589 err = socket_error();
2590 if (err == EINTR || err == EWOULDBLOCK) {
2591 } else if (err == EINPROGRESS) {
2592 break;
2593 } else {
2594 goto fail;
2596 } else {
2597 s->connected = 1;
2598 break;
2601 s->fd = fd;
2602 opt = 1;
2603 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
2604 if (s->connected)
2605 tcp_chr_connect(chr);
2606 else
2607 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2610 chr->opaque = s;
2611 chr->chr_write = tcp_chr_write;
2612 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2613 chr->chr_close = tcp_chr_close;
2614 if (is_listen && is_waitconnect) {
2615 printf("QEMU waiting for connection on: %s\n", host_str);
2616 tcp_chr_accept(chr);
2617 socket_set_nonblock(s->listen_fd);
2620 return chr;
2621 fail:
2622 if (fd >= 0)
2623 closesocket(fd);
2624 qemu_free(s);
2625 qemu_free(chr);
2626 return NULL;
2629 CharDriverState *qemu_chr_open(const char *filename)
2631 const char *p;
2633 if (!strcmp(filename, "vc")) {
2634 return text_console_init(&display_state);
2635 } else if (!strcmp(filename, "null")) {
2636 return qemu_chr_open_null();
2637 } else
2638 if (strstart(filename, "tcp:", &p)) {
2639 return qemu_chr_open_tcp(p, 0);
2640 } else
2641 if (strstart(filename, "telnet:", &p)) {
2642 return qemu_chr_open_tcp(p, 1);
2643 } else
2644 if (strstart(filename, "udp:", &p)) {
2645 return qemu_chr_open_udp(p);
2646 } else
2647 #ifndef _WIN32
2648 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;
2763 /*
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".
2767 */
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(struct sockaddr_in *saddr, const char *buf)
2795 struct hostent *he;
2797 if ((he = gethostbyname(buf)) != NULL) {
2798 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2799 } else {
2800 if (!inet_aton(buf, &saddr->sin_addr))
2801 return -1;
2803 return 0;
2806 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2808 char buf[512];
2809 const char *p, *r;
2810 int port;
2812 p = str;
2813 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2814 return -1;
2815 saddr->sin_family = AF_INET;
2816 if (buf[0] == '\0') {
2817 saddr->sin_addr.s_addr = 0;
2818 } else {
2819 if (parse_host(saddr, buf) == -1)
2820 return -1;
2822 port = strtol(p, (char **)&r, 0);
2823 if (r == p)
2824 return -1;
2825 saddr->sin_port = htons(port);
2826 return 0;
2829 /* find or alloc a new VLAN */
2830 VLANState *qemu_find_vlan(int id)
2832 VLANState **pvlan, *vlan;
2833 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2834 if (vlan->id == id)
2835 return vlan;
2837 vlan = qemu_mallocz(sizeof(VLANState));
2838 if (!vlan)
2839 return NULL;
2840 vlan->id = id;
2841 vlan->next = NULL;
2842 pvlan = &first_vlan;
2843 while (*pvlan != NULL)
2844 pvlan = &(*pvlan)->next;
2845 *pvlan = vlan;
2846 return vlan;
2849 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2850 IOReadHandler *fd_read,
2851 IOCanRWHandler *fd_can_read,
2852 void *opaque)
2854 VLANClientState *vc, **pvc;
2855 vc = qemu_mallocz(sizeof(VLANClientState));
2856 if (!vc)
2857 return NULL;
2858 vc->fd_read = fd_read;
2859 vc->fd_can_read = fd_can_read;
2860 vc->opaque = opaque;
2861 vc->vlan = vlan;
2863 vc->next = NULL;
2864 pvc = &vlan->first_client;
2865 while (*pvc != NULL)
2866 pvc = &(*pvc)->next;
2867 *pvc = vc;
2868 return vc;
2871 int qemu_can_send_packet(VLANClientState *vc1)
2873 VLANState *vlan = vc1->vlan;
2874 VLANClientState *vc;
2876 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2877 if (vc != vc1) {
2878 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2879 return 0;
2882 return 1;
2885 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2887 VLANState *vlan = vc1->vlan;
2888 VLANClientState *vc;
2890 #if 0
2891 printf("vlan %d send:\n", vlan->id);
2892 hex_dump(stdout, buf, size);
2893 #endif
2894 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2895 if (vc != vc1) {
2896 vc->fd_read(vc->opaque, buf, size);
2901 #if defined(CONFIG_SLIRP)
2903 /* slirp network adapter */
2905 static int slirp_inited;
2906 static VLANClientState *slirp_vc;
2908 int slirp_can_output(void)
2910 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2913 void slirp_output(const uint8_t *pkt, int pkt_len)
2915 #if 0
2916 printf("slirp output:\n");
2917 hex_dump(stdout, pkt, pkt_len);
2918 #endif
2919 if (!slirp_vc)
2920 return;
2921 qemu_send_packet(slirp_vc, pkt, pkt_len);
2924 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2926 #if 0
2927 printf("slirp input:\n");
2928 hex_dump(stdout, buf, size);
2929 #endif
2930 slirp_input(buf, size);
2933 static int net_slirp_init(VLANState *vlan)
2935 if (!slirp_inited) {
2936 slirp_inited = 1;
2937 slirp_init();
2939 slirp_vc = qemu_new_vlan_client(vlan,
2940 slirp_receive, NULL, NULL);
2941 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2942 return 0;
2945 static void net_slirp_redir(const char *redir_str)
2947 int is_udp;
2948 char buf[256], *r;
2949 const char *p;
2950 struct in_addr guest_addr;
2951 int host_port, guest_port;
2953 if (!slirp_inited) {
2954 slirp_inited = 1;
2955 slirp_init();
2958 p = redir_str;
2959 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2960 goto fail;
2961 if (!strcmp(buf, "tcp")) {
2962 is_udp = 0;
2963 } else if (!strcmp(buf, "udp")) {
2964 is_udp = 1;
2965 } else {
2966 goto fail;
2969 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2970 goto fail;
2971 host_port = strtol(buf, &r, 0);
2972 if (r == buf)
2973 goto fail;
2975 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2976 goto fail;
2977 if (buf[0] == '\0') {
2978 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2980 if (!inet_aton(buf, &guest_addr))
2981 goto fail;
2983 guest_port = strtol(p, &r, 0);
2984 if (r == p)
2985 goto fail;
2987 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2988 fprintf(stderr, "qemu: could not set up redirection\n");
2989 exit(1);
2991 return;
2992 fail:
2993 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2994 exit(1);
2997 #ifndef _WIN32
2999 char smb_dir[1024];
3001 static void smb_exit(void)
3003 DIR *d;
3004 struct dirent *de;
3005 char filename[1024];
3007 /* erase all the files in the directory */
3008 d = opendir(smb_dir);
3009 for(;;) {
3010 de = readdir(d);
3011 if (!de)
3012 break;
3013 if (strcmp(de->d_name, ".") != 0 &&
3014 strcmp(de->d_name, "..") != 0) {
3015 snprintf(filename, sizeof(filename), "%s/%s",
3016 smb_dir, de->d_name);
3017 unlink(filename);
3020 closedir(d);
3021 rmdir(smb_dir);
3024 /* automatic user mode samba server configuration */
3025 void net_slirp_smb(const char *exported_dir)
3027 char smb_conf[1024];
3028 char smb_cmdline[1024];
3029 FILE *f;
3031 if (!slirp_inited) {
3032 slirp_inited = 1;
3033 slirp_init();
3036 /* XXX: better tmp dir construction */
3037 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3038 if (mkdir(smb_dir, 0700) < 0) {
3039 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3040 exit(1);
3042 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3044 f = fopen(smb_conf, "w");
3045 if (!f) {
3046 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3047 exit(1);
3049 fprintf(f,
3050 "[global]\n"
3051 "private dir=%s\n"
3052 "smb ports=0\n"
3053 "socket address=127.0.0.1\n"
3054 "pid directory=%s\n"
3055 "lock directory=%s\n"
3056 "log file=%s/log.smbd\n"
3057 "smb passwd file=%s/smbpasswd\n"
3058 "security = share\n"
3059 "[qemu]\n"
3060 "path=%s\n"
3061 "read only=no\n"
3062 "guest ok=yes\n",
3063 smb_dir,
3064 smb_dir,
3065 smb_dir,
3066 smb_dir,
3067 smb_dir,
3068 exported_dir
3069 );
3070 fclose(f);
3071 atexit(smb_exit);
3073 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3074 smb_conf);
3076 slirp_add_exec(0, smb_cmdline, 4, 139);
3079 #endif /* !defined(_WIN32) */
3081 #endif /* CONFIG_SLIRP */
3083 #if !defined(_WIN32)
3085 typedef struct TAPState {
3086 VLANClientState *vc;
3087 int fd;
3088 } TAPState;
3090 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3092 TAPState *s = opaque;
3093 int ret;
3094 for(;;) {
3095 ret = write(s->fd, buf, size);
3096 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3097 } else {
3098 break;
3103 static void tap_send(void *opaque)
3105 TAPState *s = opaque;
3106 uint8_t buf[4096];
3107 int size;
3109 size = read(s->fd, buf, sizeof(buf));
3110 if (size > 0) {
3111 qemu_send_packet(s->vc, buf, size);
3115 /* fd support */
3117 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3119 TAPState *s;
3121 s = qemu_mallocz(sizeof(TAPState));
3122 if (!s)
3123 return NULL;
3124 s->fd = fd;
3125 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3126 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3127 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3128 return s;
3131 #ifdef _BSD
3132 static int tap_open(char *ifname, int ifname_size)
3134 int fd;
3135 char *dev;
3136 struct stat s;
3138 fd = open("/dev/tap", O_RDWR);
3139 if (fd < 0) {
3140 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3141 return -1;
3144 fstat(fd, &s);
3145 dev = devname(s.st_rdev, S_IFCHR);
3146 pstrcpy(ifname, ifname_size, dev);
3148 fcntl(fd, F_SETFL, O_NONBLOCK);
3149 return fd;
3151 #elif defined(__sun__)
3152 static int tap_open(char *ifname, int ifname_size)
3154 fprintf(stderr, "warning: tap_open not yet implemented\n");
3155 return -1;
3157 #else
3158 static int tap_open(char *ifname, int ifname_size)
3160 struct ifreq ifr;
3161 int fd, ret;
3163 fd = open("/dev/net/tun", O_RDWR);
3164 if (fd < 0) {
3165 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3166 return -1;
3168 memset(&ifr, 0, sizeof(ifr));
3169 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3170 if (ifname[0] != '\0')
3171 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3172 else
3173 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3174 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3175 if (ret != 0) {
3176 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3177 close(fd);
3178 return -1;
3180 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3181 fcntl(fd, F_SETFL, O_NONBLOCK);
3182 return fd;
3184 #endif
3186 static int net_tap_init(VLANState *vlan, const char *ifname1,
3187 const char *setup_script, const char *bridge)
3189 TAPState *s;
3190 int pid, status, fd;
3191 char *args[4];
3192 char **parg;
3193 char ifname[128];
3195 if (ifname1 != NULL)
3196 pstrcpy(ifname, sizeof(ifname), ifname1);
3197 else
3198 ifname[0] = '\0';
3199 fd = tap_open(ifname, sizeof(ifname));
3200 if (fd < 0)
3201 return -1;
3203 if (!setup_script)
3204 setup_script = "";
3205 if (setup_script[0] != '\0') {
3206 /* try to launch network init script */
3207 pid = fork();
3208 if (pid >= 0) {
3209 if (pid == 0) {
3210 parg = args;
3211 *parg++ = (char *)setup_script;
3212 *parg++ = ifname;
3213 *parg++ = (char *)bridge;
3214 *parg++ = NULL;
3215 execv(setup_script, args);
3216 _exit(1);
3218 while (waitpid(pid, &status, 0) != pid);
3219 if (!WIFEXITED(status) ||
3220 WEXITSTATUS(status) != 0) {
3221 fprintf(stderr, "%s: could not launch network script\n",
3222 setup_script);
3223 return -1;
3227 s = net_tap_fd_init(vlan, fd);
3228 if (!s)
3229 return -1;
3230 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3231 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3232 return 0;
3235 #endif /* !_WIN32 */
3237 /* network connection */
3238 typedef struct NetSocketState {
3239 VLANClientState *vc;
3240 int fd;
3241 int state; /* 0 = getting length, 1 = getting data */
3242 int index;
3243 int packet_len;
3244 uint8_t buf[4096];
3245 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3246 } NetSocketState;
3248 typedef struct NetSocketListenState {
3249 VLANState *vlan;
3250 int fd;
3251 } NetSocketListenState;
3253 /* XXX: we consider we can send the whole packet without blocking */
3254 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3256 NetSocketState *s = opaque;
3257 uint32_t len;
3258 len = htonl(size);
3260 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3261 send_all(s->fd, buf, size);
3264 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3266 NetSocketState *s = opaque;
3267 sendto(s->fd, buf, size, 0,
3268 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3271 static void net_socket_send(void *opaque)
3273 NetSocketState *s = opaque;
3274 int l, size, err;
3275 uint8_t buf1[4096];
3276 const uint8_t *buf;
3278 size = recv(s->fd, buf1, sizeof(buf1), 0);
3279 if (size < 0) {
3280 err = socket_error();
3281 if (err != EWOULDBLOCK)
3282 goto eoc;
3283 } else if (size == 0) {
3284 /* end of connection */
3285 eoc:
3286 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3287 closesocket(s->fd);
3288 return;
3290 buf = buf1;
3291 while (size > 0) {
3292 /* reassemble a packet from the network */
3293 switch(s->state) {
3294 case 0:
3295 l = 4 - s->index;
3296 if (l > size)
3297 l = size;
3298 memcpy(s->buf + s->index, buf, l);
3299 buf += l;
3300 size -= l;
3301 s->index += l;
3302 if (s->index == 4) {
3303 /* got length */
3304 s->packet_len = ntohl(*(uint32_t *)s->buf);
3305 s->index = 0;
3306 s->state = 1;
3308 break;
3309 case 1:
3310 l = s->packet_len - s->index;
3311 if (l > size)
3312 l = size;
3313 memcpy(s->buf + s->index, buf, l);
3314 s->index += l;
3315 buf += l;
3316 size -= l;
3317 if (s->index >= s->packet_len) {
3318 qemu_send_packet(s->vc, s->buf, s->packet_len);
3319 s->index = 0;
3320 s->state = 0;
3322 break;
3327 static void net_socket_send_dgram(void *opaque)
3329 NetSocketState *s = opaque;
3330 int size;
3332 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3333 if (size < 0)
3334 return;
3335 if (size == 0) {
3336 /* end of connection */
3337 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3338 return;
3340 qemu_send_packet(s->vc, s->buf, size);
3343 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3345 struct ip_mreq imr;
3346 int fd;
3347 int val, ret;
3348 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3349 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3350 inet_ntoa(mcastaddr->sin_addr),
3351 (int)ntohl(mcastaddr->sin_addr.s_addr));
3352 return -1;
3355 fd = socket(PF_INET, SOCK_DGRAM, 0);
3356 if (fd < 0) {
3357 perror("socket(PF_INET, SOCK_DGRAM)");
3358 return -1;
3361 val = 1;
3362 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3363 (const char *)&val, sizeof(val));
3364 if (ret < 0) {
3365 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3366 goto fail;
3369 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3370 if (ret < 0) {
3371 perror("bind");
3372 goto fail;
3375 /* Add host to multicast group */
3376 imr.imr_multiaddr = mcastaddr->sin_addr;
3377 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3379 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3380 (const char *)&imr, sizeof(struct ip_mreq));
3381 if (ret < 0) {
3382 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3383 goto fail;
3386 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3387 val = 1;
3388 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3389 (const char *)&val, sizeof(val));
3390 if (ret < 0) {
3391 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3392 goto fail;
3395 socket_set_nonblock(fd);
3396 return fd;
3397 fail:
3398 if (fd >= 0)
3399 closesocket(fd);
3400 return -1;
3403 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3404 int is_connected)
3406 struct sockaddr_in saddr;
3407 int newfd;
3408 socklen_t saddr_len;
3409 NetSocketState *s;
3411 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3412 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3413 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3414 */
3416 if (is_connected) {
3417 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3418 /* must be bound */
3419 if (saddr.sin_addr.s_addr==0) {
3420 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3421 fd);
3422 return NULL;
3424 /* clone dgram socket */
3425 newfd = net_socket_mcast_create(&saddr);
3426 if (newfd < 0) {
3427 /* error already reported by net_socket_mcast_create() */
3428 close(fd);
3429 return NULL;
3431 /* clone newfd to fd, close newfd */
3432 dup2(newfd, fd);
3433 close(newfd);
3435 } else {
3436 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3437 fd, strerror(errno));
3438 return NULL;
3442 s = qemu_mallocz(sizeof(NetSocketState));
3443 if (!s)
3444 return NULL;
3445 s->fd = fd;
3447 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3448 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3450 /* mcast: save bound address as dst */
3451 if (is_connected) s->dgram_dst=saddr;
3453 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3454 "socket: fd=%d (%s mcast=%s:%d)",
3455 fd, is_connected? "cloned" : "",
3456 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3457 return s;
3460 static void net_socket_connect(void *opaque)
3462 NetSocketState *s = opaque;
3463 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3466 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3467 int is_connected)
3469 NetSocketState *s;
3470 s = qemu_mallocz(sizeof(NetSocketState));
3471 if (!s)
3472 return NULL;
3473 s->fd = fd;
3474 s->vc = qemu_new_vlan_client(vlan,
3475 net_socket_receive, NULL, s);
3476 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3477 "socket: fd=%d", fd);
3478 if (is_connected) {
3479 net_socket_connect(s);
3480 } else {
3481 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3483 return s;
3486 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3487 int is_connected)
3489 int so_type=-1, optlen=sizeof(so_type);
3491 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3492 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3493 return NULL;
3495 switch(so_type) {
3496 case SOCK_DGRAM:
3497 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3498 case SOCK_STREAM:
3499 return net_socket_fd_init_stream(vlan, fd, is_connected);
3500 default:
3501 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3502 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3503 return net_socket_fd_init_stream(vlan, fd, is_connected);
3505 return NULL;
3508 static void net_socket_accept(void *opaque)
3510 NetSocketListenState *s = opaque;
3511 NetSocketState *s1;
3512 struct sockaddr_in saddr;
3513 socklen_t len;
3514 int fd;
3516 for(;;) {
3517 len = sizeof(saddr);
3518 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3519 if (fd < 0 && errno != EINTR) {
3520 return;
3521 } else if (fd >= 0) {
3522 break;
3525 s1 = net_socket_fd_init(s->vlan, fd, 1);
3526 if (!s1) {
3527 closesocket(fd);
3528 } else {
3529 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3530 "socket: connection from %s:%d",
3531 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3535 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3537 NetSocketListenState *s;
3538 int fd, val, ret;
3539 struct sockaddr_in saddr;
3541 if (parse_host_port(&saddr, host_str) < 0)
3542 return -1;
3544 s = qemu_mallocz(sizeof(NetSocketListenState));
3545 if (!s)
3546 return -1;
3548 fd = socket(PF_INET, SOCK_STREAM, 0);
3549 if (fd < 0) {
3550 perror("socket");
3551 return -1;
3553 socket_set_nonblock(fd);
3555 /* allow fast reuse */
3556 val = 1;
3557 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3559 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3560 if (ret < 0) {
3561 perror("bind");
3562 return -1;
3564 ret = listen(fd, 0);
3565 if (ret < 0) {
3566 perror("listen");
3567 return -1;
3569 s->vlan = vlan;
3570 s->fd = fd;
3571 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3572 return 0;
3575 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3577 NetSocketState *s;
3578 int fd, connected, ret, err;
3579 struct sockaddr_in saddr;
3581 if (parse_host_port(&saddr, host_str) < 0)
3582 return -1;
3584 fd = socket(PF_INET, SOCK_STREAM, 0);
3585 if (fd < 0) {
3586 perror("socket");
3587 return -1;
3589 socket_set_nonblock(fd);
3591 connected = 0;
3592 for(;;) {
3593 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3594 if (ret < 0) {
3595 err = socket_error();
3596 if (err == EINTR || err == EWOULDBLOCK) {
3597 } else if (err == EINPROGRESS) {
3598 break;
3599 } else {
3600 perror("connect");
3601 closesocket(fd);
3602 return -1;
3604 } else {
3605 connected = 1;
3606 break;
3609 s = net_socket_fd_init(vlan, fd, connected);
3610 if (!s)
3611 return -1;
3612 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3613 "socket: connect to %s:%d",
3614 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3615 return 0;
3618 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3620 NetSocketState *s;
3621 int fd;
3622 struct sockaddr_in saddr;
3624 if (parse_host_port(&saddr, host_str) < 0)
3625 return -1;
3628 fd = net_socket_mcast_create(&saddr);
3629 if (fd < 0)
3630 return -1;
3632 s = net_socket_fd_init(vlan, fd, 0);
3633 if (!s)
3634 return -1;
3636 s->dgram_dst = saddr;
3638 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3639 "socket: mcast=%s:%d",
3640 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3641 return 0;
3645 static int get_param_value(char *buf, int buf_size,
3646 const char *tag, const char *str)
3648 const char *p;
3649 char *q;
3650 char option[128];
3652 p = str;
3653 for(;;) {
3654 q = option;
3655 while (*p != '\0' && *p != '=') {
3656 if ((q - option) < sizeof(option) - 1)
3657 *q++ = *p;
3658 p++;
3660 *q = '\0';
3661 if (*p != '=')
3662 break;
3663 p++;
3664 if (!strcmp(tag, option)) {
3665 q = buf;
3666 while (*p != '\0' && *p != ',') {
3667 if ((q - buf) < buf_size - 1)
3668 *q++ = *p;
3669 p++;
3671 *q = '\0';
3672 return q - buf;
3673 } else {
3674 while (*p != '\0' && *p != ',') {
3675 p++;
3678 if (*p != ',')
3679 break;
3680 p++;
3682 return 0;
3685 int net_client_init(const char *str)
3687 const char *p;
3688 char *q;
3689 char device[64];
3690 char buf[1024];
3691 int vlan_id, ret;
3692 VLANState *vlan;
3694 p = str;
3695 q = device;
3696 while (*p != '\0' && *p != ',') {
3697 if ((q - device) < sizeof(device) - 1)
3698 *q++ = *p;
3699 p++;
3701 *q = '\0';
3702 if (*p == ',')
3703 p++;
3704 vlan_id = 0;
3705 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3706 vlan_id = strtol(buf, NULL, 0);
3708 vlan = qemu_find_vlan(vlan_id);
3709 if (!vlan) {
3710 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3711 return -1;
3713 if (!strcmp(device, "nic")) {
3714 NICInfo *nd;
3715 uint8_t *macaddr;
3717 if (nb_nics >= MAX_NICS) {
3718 fprintf(stderr, "Too Many NICs\n");
3719 return -1;
3721 nd = &nd_table[nb_nics];
3722 macaddr = nd->macaddr;
3723 macaddr[0] = 0x52;
3724 macaddr[1] = 0x54;
3725 macaddr[2] = 0x00;
3726 macaddr[3] = 0x12;
3727 macaddr[4] = 0x34;
3728 macaddr[5] = 0x56 + nb_nics;
3730 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3731 if (parse_macaddr(macaddr, buf) < 0) {
3732 fprintf(stderr, "invalid syntax for ethernet address\n");
3733 return -1;
3736 if (get_param_value(buf, sizeof(buf), "model", p)) {
3737 nd->model = strdup(buf);
3739 nd->vlan = vlan;
3740 nb_nics++;
3741 ret = 0;
3742 } else
3743 if (!strcmp(device, "none")) {
3744 /* does nothing. It is needed to signal that no network cards
3745 are wanted */
3746 ret = 0;
3747 } else
3748 #ifdef CONFIG_SLIRP
3749 if (!strcmp(device, "user")) {
3750 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3751 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3753 ret = net_slirp_init(vlan);
3754 } else
3755 #endif
3756 #ifdef _WIN32
3757 if (!strcmp(device, "tap")) {
3758 char ifname[64];
3759 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3760 fprintf(stderr, "tap: no interface name\n");
3761 return -1;
3763 ret = tap_win32_init(vlan, ifname);
3764 } else
3765 #else
3766 if (!strcmp(device, "tap")) {
3767 char ifname[64];
3768 char setup_script[1024];
3769 char bridge[16];
3770 int fd;
3771 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3772 fd = strtol(buf, NULL, 0);
3773 ret = -1;
3774 if (net_tap_fd_init(vlan, fd))
3775 ret = 0;
3776 } else {
3777 ifname[0] = '\0';
3778 get_param_value(ifname, sizeof(ifname), "ifname", p);
3779 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3780 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3782 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3783 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3785 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3787 } else
3788 #endif
3789 if (!strcmp(device, "socket")) {
3790 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3791 int fd;
3792 fd = strtol(buf, NULL, 0);
3793 ret = -1;
3794 if (net_socket_fd_init(vlan, fd, 1))
3795 ret = 0;
3796 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3797 ret = net_socket_listen_init(vlan, buf);
3798 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3799 ret = net_socket_connect_init(vlan, buf);
3800 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3801 ret = net_socket_mcast_init(vlan, buf);
3802 } else {
3803 fprintf(stderr, "Unknown socket options: %s\n", p);
3804 return -1;
3806 } else
3808 fprintf(stderr, "Unknown network device: %s\n", device);
3809 return -1;
3811 if (ret < 0) {
3812 fprintf(stderr, "Could not initialize device '%s'\n", device);
3815 return ret;
3818 void do_info_network(void)
3820 VLANState *vlan;
3821 VLANClientState *vc;
3823 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3824 term_printf("VLAN %d devices:\n", vlan->id);
3825 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3826 term_printf(" %s\n", vc->info_str);
3830 /***********************************************************/
3831 /* USB devices */
3833 static USBPort *used_usb_ports;
3834 static USBPort *free_usb_ports;
3836 /* ??? Maybe change this to register a hub to keep track of the topology. */
3837 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3838 usb_attachfn attach)
3840 port->opaque = opaque;
3841 port->index = index;
3842 port->attach = attach;
3843 port->next = free_usb_ports;
3844 free_usb_ports = port;
3847 static int usb_device_add(const char *devname)
3849 const char *p;
3850 USBDevice *dev;
3851 USBPort *port;
3853 if (!free_usb_ports)
3854 return -1;
3856 if (strstart(devname, "host:", &p)) {
3857 dev = usb_host_device_open(p);
3858 } else if (!strcmp(devname, "mouse")) {
3859 dev = usb_mouse_init();
3860 } else if (!strcmp(devname, "tablet")) {
3861 dev = usb_tablet_init();
3862 } else if (strstart(devname, "disk:", &p)) {
3863 dev = usb_msd_init(p);
3864 } else {
3865 return -1;
3867 if (!dev)
3868 return -1;
3870 /* Find a USB port to add the device to. */
3871 port = free_usb_ports;
3872 if (!port->next) {
3873 USBDevice *hub;
3875 /* Create a new hub and chain it on. */
3876 free_usb_ports = NULL;
3877 port->next = used_usb_ports;
3878 used_usb_ports = port;
3880 hub = usb_hub_init(VM_USB_HUB_SIZE);
3881 usb_attach(port, hub);
3882 port = free_usb_ports;
3885 free_usb_ports = port->next;
3886 port->next = used_usb_ports;
3887 used_usb_ports = port;
3888 usb_attach(port, dev);
3889 return 0;
3892 static int usb_device_del(const char *devname)
3894 USBPort *port;
3895 USBPort **lastp;
3896 USBDevice *dev;
3897 int bus_num, addr;
3898 const char *p;
3900 if (!used_usb_ports)
3901 return -1;
3903 p = strchr(devname, '.');
3904 if (!p)
3905 return -1;
3906 bus_num = strtoul(devname, NULL, 0);
3907 addr = strtoul(p + 1, NULL, 0);
3908 if (bus_num != 0)
3909 return -1;
3911 lastp = &used_usb_ports;
3912 port = used_usb_ports;
3913 while (port && port->dev->addr != addr) {
3914 lastp = &port->next;
3915 port = port->next;
3918 if (!port)
3919 return -1;
3921 dev = port->dev;
3922 *lastp = port->next;
3923 usb_attach(port, NULL);
3924 dev->handle_destroy(dev);
3925 port->next = free_usb_ports;
3926 free_usb_ports = port;
3927 return 0;
3930 void do_usb_add(const char *devname)
3932 int ret;
3933 ret = usb_device_add(devname);
3934 if (ret < 0)
3935 term_printf("Could not add USB device '%s'\n", devname);
3938 void do_usb_del(const char *devname)
3940 int ret;
3941 ret = usb_device_del(devname);
3942 if (ret < 0)
3943 term_printf("Could not remove USB device '%s'\n", devname);
3946 void usb_info(void)
3948 USBDevice *dev;
3949 USBPort *port;
3950 const char *speed_str;
3952 if (!usb_enabled) {
3953 term_printf("USB support not enabled\n");
3954 return;
3957 for (port = used_usb_ports; port; port = port->next) {
3958 dev = port->dev;
3959 if (!dev)
3960 continue;
3961 switch(dev->speed) {
3962 case USB_SPEED_LOW:
3963 speed_str = "1.5";
3964 break;
3965 case USB_SPEED_FULL:
3966 speed_str = "12";
3967 break;
3968 case USB_SPEED_HIGH:
3969 speed_str = "480";
3970 break;
3971 default:
3972 speed_str = "?";
3973 break;
3975 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3976 0, dev->addr, speed_str, dev->devname);
3980 /***********************************************************/
3981 /* pid file */
3983 static char *pid_filename;
3985 /* Remove PID file. Called on normal exit */
3987 static void remove_pidfile(void)
3989 unlink (pid_filename);
3992 static void create_pidfile(const char *filename)
3994 struct stat pidstat;
3995 FILE *f;
3997 /* Try to write our PID to the named file */
3998 if (stat(filename, &pidstat) < 0) {
3999 if (errno == ENOENT) {
4000 if ((f = fopen (filename, "w")) == NULL) {
4001 perror("Opening pidfile");
4002 exit(1);
4004 fprintf(f, "%ld\n", (long)getpid());
4005 fclose(f);
4006 pid_filename = qemu_strdup(filename);
4007 if (!pid_filename) {
4008 fprintf(stderr, "Could not save PID filename");
4009 exit(1);
4011 atexit(remove_pidfile);
4013 } else {
4014 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4015 filename);
4016 exit(1);
4020 /***********************************************************/
4021 /* dumb display */
4023 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4027 static void dumb_resize(DisplayState *ds, int w, int h)
4031 static void dumb_refresh(DisplayState *ds)
4033 vga_hw_update();
4036 void dumb_display_init(DisplayState *ds)
4038 ds->data = NULL;
4039 ds->linesize = 0;
4040 ds->depth = 0;
4041 ds->dpy_update = dumb_update;
4042 ds->dpy_resize = dumb_resize;
4043 ds->dpy_refresh = dumb_refresh;
4046 /***********************************************************/
4047 /* I/O handling */
4049 #define MAX_IO_HANDLERS 64
4051 typedef struct IOHandlerRecord {
4052 int fd;
4053 IOCanRWHandler *fd_read_poll;
4054 IOHandler *fd_read;
4055 IOHandler *fd_write;
4056 void *opaque;
4057 /* temporary data */
4058 struct pollfd *ufd;
4059 struct IOHandlerRecord *next;
4060 } IOHandlerRecord;
4062 static IOHandlerRecord *first_io_handler;
4064 /* XXX: fd_read_poll should be suppressed, but an API change is
4065 necessary in the character devices to suppress fd_can_read(). */
4066 int qemu_set_fd_handler2(int fd,
4067 IOCanRWHandler *fd_read_poll,
4068 IOHandler *fd_read,
4069 IOHandler *fd_write,
4070 void *opaque)
4072 IOHandlerRecord **pioh, *ioh;
4074 if (!fd_read && !fd_write) {
4075 pioh = &first_io_handler;
4076 for(;;) {
4077 ioh = *pioh;
4078 if (ioh == NULL)
4079 break;
4080 if (ioh->fd == fd) {
4081 *pioh = ioh->next;
4082 qemu_free(ioh);
4083 break;
4085 pioh = &ioh->next;
4087 } else {
4088 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4089 if (ioh->fd == fd)
4090 goto found;
4092 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4093 if (!ioh)
4094 return -1;
4095 ioh->next = first_io_handler;
4096 first_io_handler = ioh;
4097 found:
4098 ioh->fd = fd;
4099 ioh->fd_read_poll = fd_read_poll;
4100 ioh->fd_read = fd_read;
4101 ioh->fd_write = fd_write;
4102 ioh->opaque = opaque;
4104 return 0;
4107 int qemu_set_fd_handler(int fd,
4108 IOHandler *fd_read,
4109 IOHandler *fd_write,
4110 void *opaque)
4112 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4115 /***********************************************************/
4116 /* Polling handling */
4118 typedef struct PollingEntry {
4119 PollingFunc *func;
4120 void *opaque;
4121 struct PollingEntry *next;
4122 } PollingEntry;
4124 static PollingEntry *first_polling_entry;
4126 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4128 PollingEntry **ppe, *pe;
4129 pe = qemu_mallocz(sizeof(PollingEntry));
4130 if (!pe)
4131 return -1;
4132 pe->func = func;
4133 pe->opaque = opaque;
4134 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4135 *ppe = pe;
4136 return 0;
4139 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4141 PollingEntry **ppe, *pe;
4142 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4143 pe = *ppe;
4144 if (pe->func == func && pe->opaque == opaque) {
4145 *ppe = pe->next;
4146 qemu_free(pe);
4147 break;
4152 #ifdef _WIN32
4153 /***********************************************************/
4154 /* Wait objects support */
4155 typedef struct WaitObjects {
4156 int num;
4157 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4158 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4159 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4160 } WaitObjects;
4162 static WaitObjects wait_objects = {0};
4164 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4166 WaitObjects *w = &wait_objects;
4168 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4169 return -1;
4170 w->events[w->num] = handle;
4171 w->func[w->num] = func;
4172 w->opaque[w->num] = opaque;
4173 w->num++;
4174 return 0;
4177 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4179 int i, found;
4180 WaitObjects *w = &wait_objects;
4182 found = 0;
4183 for (i = 0; i < w->num; i++) {
4184 if (w->events[i] == handle)
4185 found = 1;
4186 if (found) {
4187 w->events[i] = w->events[i + 1];
4188 w->func[i] = w->func[i + 1];
4189 w->opaque[i] = w->opaque[i + 1];
4192 if (found)
4193 w->num--;
4195 #endif
4197 /***********************************************************/
4198 /* savevm/loadvm support */
4200 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4202 fwrite(buf, 1, size, f);
4205 void qemu_put_byte(QEMUFile *f, int v)
4207 fputc(v, f);
4210 void qemu_put_be16(QEMUFile *f, unsigned int v)
4212 qemu_put_byte(f, v >> 8);
4213 qemu_put_byte(f, v);
4216 void qemu_put_be32(QEMUFile *f, unsigned int v)
4218 qemu_put_byte(f, v >> 24);
4219 qemu_put_byte(f, v >> 16);
4220 qemu_put_byte(f, v >> 8);
4221 qemu_put_byte(f, v);
4224 void qemu_put_be64(QEMUFile *f, uint64_t v)
4226 qemu_put_be32(f, v >> 32);
4227 qemu_put_be32(f, v);
4230 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4232 return fread(buf, 1, size, f);
4235 int qemu_get_byte(QEMUFile *f)
4237 int v;
4238 v = fgetc(f);
4239 if (v == EOF)
4240 return 0;
4241 else
4242 return v;
4245 unsigned int qemu_get_be16(QEMUFile *f)
4247 unsigned int v;
4248 v = qemu_get_byte(f) << 8;
4249 v |= qemu_get_byte(f);
4250 return v;
4253 unsigned int qemu_get_be32(QEMUFile *f)
4255 unsigned int v;
4256 v = qemu_get_byte(f) << 24;
4257 v |= qemu_get_byte(f) << 16;
4258 v |= qemu_get_byte(f) << 8;
4259 v |= qemu_get_byte(f);
4260 return v;
4263 uint64_t qemu_get_be64(QEMUFile *f)
4265 uint64_t v;
4266 v = (uint64_t)qemu_get_be32(f) << 32;
4267 v |= qemu_get_be32(f);
4268 return v;
4271 int64_t qemu_ftell(QEMUFile *f)
4273 return ftell(f);
4276 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4278 if (fseek(f, pos, whence) < 0)
4279 return -1;
4280 return ftell(f);
4283 typedef struct SaveStateEntry {
4284 char idstr[256];
4285 int instance_id;
4286 int version_id;
4287 SaveStateHandler *save_state;
4288 LoadStateHandler *load_state;
4289 void *opaque;
4290 struct SaveStateEntry *next;
4291 } SaveStateEntry;
4293 static SaveStateEntry *first_se;
4295 int register_savevm(const char *idstr,
4296 int instance_id,
4297 int version_id,
4298 SaveStateHandler *save_state,
4299 LoadStateHandler *load_state,
4300 void *opaque)
4302 SaveStateEntry *se, **pse;
4304 se = qemu_malloc(sizeof(SaveStateEntry));
4305 if (!se)
4306 return -1;
4307 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4308 se->instance_id = instance_id;
4309 se->version_id = version_id;
4310 se->save_state = save_state;
4311 se->load_state = load_state;
4312 se->opaque = opaque;
4313 se->next = NULL;
4315 /* add at the end of list */
4316 pse = &first_se;
4317 while (*pse != NULL)
4318 pse = &(*pse)->next;
4319 *pse = se;
4320 return 0;
4323 #define QEMU_VM_FILE_MAGIC 0x5145564d
4324 #define QEMU_VM_FILE_VERSION 0x00000001
4326 int qemu_savevm(const char *filename)
4328 SaveStateEntry *se;
4329 QEMUFile *f;
4330 int len, len_pos, cur_pos, saved_vm_running, ret;
4332 saved_vm_running = vm_running;
4333 vm_stop(0);
4335 f = fopen(filename, "wb");
4336 if (!f) {
4337 ret = -1;
4338 goto the_end;
4341 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4342 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4344 for(se = first_se; se != NULL; se = se->next) {
4345 /* ID string */
4346 len = strlen(se->idstr);
4347 qemu_put_byte(f, len);
4348 qemu_put_buffer(f, se->idstr, len);
4350 qemu_put_be32(f, se->instance_id);
4351 qemu_put_be32(f, se->version_id);
4353 /* record size: filled later */
4354 len_pos = ftell(f);
4355 qemu_put_be32(f, 0);
4357 se->save_state(f, se->opaque);
4359 /* fill record size */
4360 cur_pos = ftell(f);
4361 len = ftell(f) - len_pos - 4;
4362 fseek(f, len_pos, SEEK_SET);
4363 qemu_put_be32(f, len);
4364 fseek(f, cur_pos, SEEK_SET);
4367 fclose(f);
4368 ret = 0;
4369 the_end:
4370 if (saved_vm_running)
4371 vm_start();
4372 return ret;
4375 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4377 SaveStateEntry *se;
4379 for(se = first_se; se != NULL; se = se->next) {
4380 if (!strcmp(se->idstr, idstr) &&
4381 instance_id == se->instance_id)
4382 return se;
4384 return NULL;
4387 int qemu_loadvm(const char *filename)
4389 SaveStateEntry *se;
4390 QEMUFile *f;
4391 int len, cur_pos, ret, instance_id, record_len, version_id;
4392 int saved_vm_running;
4393 unsigned int v;
4394 char idstr[256];
4396 saved_vm_running = vm_running;
4397 vm_stop(0);
4399 f = fopen(filename, "rb");
4400 if (!f) {
4401 ret = -1;
4402 goto the_end;
4405 v = qemu_get_be32(f);
4406 if (v != QEMU_VM_FILE_MAGIC)
4407 goto fail;
4408 v = qemu_get_be32(f);
4409 if (v != QEMU_VM_FILE_VERSION) {
4410 fail:
4411 fclose(f);
4412 ret = -1;
4413 goto the_end;
4415 for(;;) {
4416 len = qemu_get_byte(f);
4417 if (feof(f))
4418 break;
4419 qemu_get_buffer(f, idstr, len);
4420 idstr[len] = '\0';
4421 instance_id = qemu_get_be32(f);
4422 version_id = qemu_get_be32(f);
4423 record_len = qemu_get_be32(f);
4424 #if 0
4425 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4426 idstr, instance_id, version_id, record_len);
4427 #endif
4428 cur_pos = ftell(f);
4429 se = find_se(idstr, instance_id);
4430 if (!se) {
4431 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4432 instance_id, idstr);
4433 } else {
4434 ret = se->load_state(f, se->opaque, version_id);
4435 if (ret < 0) {
4436 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4437 instance_id, idstr);
4440 /* always seek to exact end of record */
4441 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4443 fclose(f);
4444 ret = 0;
4445 the_end:
4446 if (saved_vm_running)
4447 vm_start();
4448 return ret;
4451 #ifndef CONFIG_DM
4452 /***********************************************************/
4453 /* cpu save/restore */
4455 #if defined(TARGET_I386)
4457 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4459 qemu_put_be32(f, dt->selector);
4460 qemu_put_betl(f, dt->base);
4461 qemu_put_be32(f, dt->limit);
4462 qemu_put_be32(f, dt->flags);
4465 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4467 dt->selector = qemu_get_be32(f);
4468 dt->base = qemu_get_betl(f);
4469 dt->limit = qemu_get_be32(f);
4470 dt->flags = qemu_get_be32(f);
4473 void cpu_save(QEMUFile *f, void *opaque)
4475 CPUState *env = opaque;
4476 uint16_t fptag, fpus, fpuc, fpregs_format;
4477 uint32_t hflags;
4478 int i;
4480 for(i = 0; i < CPU_NB_REGS; i++)
4481 qemu_put_betls(f, &env->regs[i]);
4482 qemu_put_betls(f, &env->eip);
4483 qemu_put_betls(f, &env->eflags);
4484 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4485 qemu_put_be32s(f, &hflags);
4487 /* FPU */
4488 fpuc = env->fpuc;
4489 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4490 fptag = 0;
4491 for(i = 0; i < 8; i++) {
4492 fptag |= ((!env->fptags[i]) << i);
4495 qemu_put_be16s(f, &fpuc);
4496 qemu_put_be16s(f, &fpus);
4497 qemu_put_be16s(f, &fptag);
4499 #ifdef USE_X86LDOUBLE
4500 fpregs_format = 0;
4501 #else
4502 fpregs_format = 1;
4503 #endif
4504 qemu_put_be16s(f, &fpregs_format);
4506 for(i = 0; i < 8; i++) {
4507 #ifdef USE_X86LDOUBLE
4509 uint64_t mant;
4510 uint16_t exp;
4511 /* we save the real CPU data (in case of MMX usage only 'mant'
4512 contains the MMX register */
4513 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4514 qemu_put_be64(f, mant);
4515 qemu_put_be16(f, exp);
4517 #else
4518 /* if we use doubles for float emulation, we save the doubles to
4519 avoid losing information in case of MMX usage. It can give
4520 problems if the image is restored on a CPU where long
4521 doubles are used instead. */
4522 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4523 #endif
4526 for(i = 0; i < 6; i++)
4527 cpu_put_seg(f, &env->segs[i]);
4528 cpu_put_seg(f, &env->ldt);
4529 cpu_put_seg(f, &env->tr);
4530 cpu_put_seg(f, &env->gdt);
4531 cpu_put_seg(f, &env->idt);
4533 qemu_put_be32s(f, &env->sysenter_cs);
4534 qemu_put_be32s(f, &env->sysenter_esp);
4535 qemu_put_be32s(f, &env->sysenter_eip);
4537 qemu_put_betls(f, &env->cr[0]);
4538 qemu_put_betls(f, &env->cr[2]);
4539 qemu_put_betls(f, &env->cr[3]);
4540 qemu_put_betls(f, &env->cr[4]);
4542 for(i = 0; i < 8; i++)
4543 qemu_put_betls(f, &env->dr[i]);
4545 /* MMU */
4546 qemu_put_be32s(f, &env->a20_mask);
4548 /* XMM */
4549 qemu_put_be32s(f, &env->mxcsr);
4550 for(i = 0; i < CPU_NB_REGS; i++) {
4551 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4552 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4555 #ifdef TARGET_X86_64
4556 qemu_put_be64s(f, &env->efer);
4557 qemu_put_be64s(f, &env->star);
4558 qemu_put_be64s(f, &env->lstar);
4559 qemu_put_be64s(f, &env->cstar);
4560 qemu_put_be64s(f, &env->fmask);
4561 qemu_put_be64s(f, &env->kernelgsbase);
4562 #endif
4565 #ifdef USE_X86LDOUBLE
4566 /* XXX: add that in a FPU generic layer */
4567 union x86_longdouble {
4568 uint64_t mant;
4569 uint16_t exp;
4570 };
4572 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4573 #define EXPBIAS1 1023
4574 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4575 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4577 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4579 int e;
4580 /* mantissa */
4581 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4582 /* exponent + sign */
4583 e = EXPD1(temp) - EXPBIAS1 + 16383;
4584 e |= SIGND1(temp) >> 16;
4585 p->exp = e;
4587 #endif
4589 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4591 CPUState *env = opaque;
4592 int i, guess_mmx;
4593 uint32_t hflags;
4594 uint16_t fpus, fpuc, fptag, fpregs_format;
4596 if (version_id != 3)
4597 return -EINVAL;
4598 for(i = 0; i < CPU_NB_REGS; i++)
4599 qemu_get_betls(f, &env->regs[i]);
4600 qemu_get_betls(f, &env->eip);
4601 qemu_get_betls(f, &env->eflags);
4602 qemu_get_be32s(f, &hflags);
4604 qemu_get_be16s(f, &fpuc);
4605 qemu_get_be16s(f, &fpus);
4606 qemu_get_be16s(f, &fptag);
4607 qemu_get_be16s(f, &fpregs_format);
4609 /* NOTE: we cannot always restore the FPU state if the image come
4610 from a host with a different 'USE_X86LDOUBLE' define. We guess
4611 if we are in an MMX state to restore correctly in that case. */
4612 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4613 for(i = 0; i < 8; i++) {
4614 uint64_t mant;
4615 uint16_t exp;
4617 switch(fpregs_format) {
4618 case 0:
4619 mant = qemu_get_be64(f);
4620 exp = qemu_get_be16(f);
4621 #ifdef USE_X86LDOUBLE
4622 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4623 #else
4624 /* difficult case */
4625 if (guess_mmx)
4626 env->fpregs[i].mmx.MMX_Q(0) = mant;
4627 else
4628 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4629 #endif
4630 break;
4631 case 1:
4632 mant = qemu_get_be64(f);
4633 #ifdef USE_X86LDOUBLE
4635 union x86_longdouble *p;
4636 /* difficult case */
4637 p = (void *)&env->fpregs[i];
4638 if (guess_mmx) {
4639 p->mant = mant;
4640 p->exp = 0xffff;
4641 } else {
4642 fp64_to_fp80(p, mant);
4645 #else
4646 env->fpregs[i].mmx.MMX_Q(0) = mant;
4647 #endif
4648 break;
4649 default:
4650 return -EINVAL;
4654 env->fpuc = fpuc;
4655 /* XXX: restore FPU round state */
4656 env->fpstt = (fpus >> 11) & 7;
4657 env->fpus = fpus & ~0x3800;
4658 fptag ^= 0xff;
4659 for(i = 0; i < 8; i++) {
4660 env->fptags[i] = (fptag >> i) & 1;
4663 for(i = 0; i < 6; i++)
4664 cpu_get_seg(f, &env->segs[i]);
4665 cpu_get_seg(f, &env->ldt);
4666 cpu_get_seg(f, &env->tr);
4667 cpu_get_seg(f, &env->gdt);
4668 cpu_get_seg(f, &env->idt);
4670 qemu_get_be32s(f, &env->sysenter_cs);
4671 qemu_get_be32s(f, &env->sysenter_esp);
4672 qemu_get_be32s(f, &env->sysenter_eip);
4674 qemu_get_betls(f, &env->cr[0]);
4675 qemu_get_betls(f, &env->cr[2]);
4676 qemu_get_betls(f, &env->cr[3]);
4677 qemu_get_betls(f, &env->cr[4]);
4679 for(i = 0; i < 8; i++)
4680 qemu_get_betls(f, &env->dr[i]);
4682 /* MMU */
4683 qemu_get_be32s(f, &env->a20_mask);
4685 qemu_get_be32s(f, &env->mxcsr);
4686 for(i = 0; i < CPU_NB_REGS; i++) {
4687 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4688 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4691 #ifdef TARGET_X86_64
4692 qemu_get_be64s(f, &env->efer);
4693 qemu_get_be64s(f, &env->star);
4694 qemu_get_be64s(f, &env->lstar);
4695 qemu_get_be64s(f, &env->cstar);
4696 qemu_get_be64s(f, &env->fmask);
4697 qemu_get_be64s(f, &env->kernelgsbase);
4698 #endif
4700 /* XXX: compute hflags from scratch, except for CPL and IIF */
4701 env->hflags = hflags;
4702 tlb_flush(env, 1);
4703 return 0;
4706 #elif defined(TARGET_PPC)
4707 void cpu_save(QEMUFile *f, void *opaque)
4711 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4713 return 0;
4716 #elif defined(TARGET_MIPS)
4717 void cpu_save(QEMUFile *f, void *opaque)
4721 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4723 return 0;
4726 #elif defined(TARGET_SPARC)
4727 void cpu_save(QEMUFile *f, void *opaque)
4729 CPUState *env = opaque;
4730 int i;
4731 uint32_t tmp;
4733 for(i = 0; i < 8; i++)
4734 qemu_put_betls(f, &env->gregs[i]);
4735 for(i = 0; i < NWINDOWS * 16; i++)
4736 qemu_put_betls(f, &env->regbase[i]);
4738 /* FPU */
4739 for(i = 0; i < TARGET_FPREGS; i++) {
4740 union {
4741 float32 f;
4742 uint32_t i;
4743 } u;
4744 u.f = env->fpr[i];
4745 qemu_put_be32(f, u.i);
4748 qemu_put_betls(f, &env->pc);
4749 qemu_put_betls(f, &env->npc);
4750 qemu_put_betls(f, &env->y);
4751 tmp = GET_PSR(env);
4752 qemu_put_be32(f, tmp);
4753 qemu_put_betls(f, &env->fsr);
4754 qemu_put_betls(f, &env->tbr);
4755 #ifndef TARGET_SPARC64
4756 qemu_put_be32s(f, &env->wim);
4757 /* MMU */
4758 for(i = 0; i < 16; i++)
4759 qemu_put_be32s(f, &env->mmuregs[i]);
4760 #endif
4763 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4765 CPUState *env = opaque;
4766 int i;
4767 uint32_t tmp;
4769 for(i = 0; i < 8; i++)
4770 qemu_get_betls(f, &env->gregs[i]);
4771 for(i = 0; i < NWINDOWS * 16; i++)
4772 qemu_get_betls(f, &env->regbase[i]);
4774 /* FPU */
4775 for(i = 0; i < TARGET_FPREGS; i++) {
4776 union {
4777 float32 f;
4778 uint32_t i;
4779 } u;
4780 u.i = qemu_get_be32(f);
4781 env->fpr[i] = u.f;
4784 qemu_get_betls(f, &env->pc);
4785 qemu_get_betls(f, &env->npc);
4786 qemu_get_betls(f, &env->y);
4787 tmp = qemu_get_be32(f);
4788 env->cwp = 0; /* needed to ensure that the wrapping registers are
4789 correctly updated */
4790 PUT_PSR(env, tmp);
4791 qemu_get_betls(f, &env->fsr);
4792 qemu_get_betls(f, &env->tbr);
4793 #ifndef TARGET_SPARC64
4794 qemu_get_be32s(f, &env->wim);
4795 /* MMU */
4796 for(i = 0; i < 16; i++)
4797 qemu_get_be32s(f, &env->mmuregs[i]);
4798 #endif
4799 tlb_flush(env, 1);
4800 return 0;
4803 #elif defined(TARGET_ARM)
4805 /* ??? Need to implement these. */
4806 void cpu_save(QEMUFile *f, void *opaque)
4810 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4812 return 0;
4815 #else
4817 #warning No CPU save/restore functions
4819 #endif
4821 /***********************************************************/
4822 /* ram save/restore */
4824 /* we just avoid storing empty pages */
4825 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4827 int i, v;
4829 v = buf[0];
4830 for(i = 1; i < len; i++) {
4831 if (buf[i] != v)
4832 goto normal_save;
4834 qemu_put_byte(f, 1);
4835 qemu_put_byte(f, v);
4836 return;
4837 normal_save:
4838 qemu_put_byte(f, 0);
4839 qemu_put_buffer(f, buf, len);
4842 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4844 int v;
4846 v = qemu_get_byte(f);
4847 switch(v) {
4848 case 0:
4849 if (qemu_get_buffer(f, buf, len) != len)
4850 return -EIO;
4851 break;
4852 case 1:
4853 v = qemu_get_byte(f);
4854 memset(buf, v, len);
4855 break;
4856 default:
4857 return -EINVAL;
4859 return 0;
4862 static void ram_save(QEMUFile *f, void *opaque)
4864 int i;
4865 qemu_put_be32(f, phys_ram_size);
4866 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4867 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4871 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4873 int i, ret;
4875 if (version_id != 1)
4876 return -EINVAL;
4877 if (qemu_get_be32(f) != phys_ram_size)
4878 return -EINVAL;
4879 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4880 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4881 if (ret)
4882 return ret;
4884 return 0;
4886 #else /* CONFIG_DM */
4887 void cpu_save(QEMUFile *f, void *opaque)
4891 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4893 return 0;
4896 static void ram_save(QEMUFile *f, void *opaque)
4900 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4902 return 0;
4904 #endif /* CONFIG_DM */
4906 /***********************************************************/
4907 /* machine registration */
4909 QEMUMachine *first_machine = NULL;
4911 int qemu_register_machine(QEMUMachine *m)
4913 QEMUMachine **pm;
4914 pm = &first_machine;
4915 while (*pm != NULL)
4916 pm = &(*pm)->next;
4917 m->next = NULL;
4918 *pm = m;
4919 return 0;
4922 QEMUMachine *find_machine(const char *name)
4924 QEMUMachine *m;
4926 for(m = first_machine; m != NULL; m = m->next) {
4927 if (!strcmp(m->name, name))
4928 return m;
4930 return NULL;
4933 /***********************************************************/
4934 /* main execution loop */
4936 void gui_update(void *opaque)
4938 display_state.dpy_refresh(&display_state);
4939 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4942 struct vm_change_state_entry {
4943 VMChangeStateHandler *cb;
4944 void *opaque;
4945 LIST_ENTRY (vm_change_state_entry) entries;
4946 };
4948 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4950 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4951 void *opaque)
4953 VMChangeStateEntry *e;
4955 e = qemu_mallocz(sizeof (*e));
4956 if (!e)
4957 return NULL;
4959 e->cb = cb;
4960 e->opaque = opaque;
4961 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4962 return e;
4965 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4967 LIST_REMOVE (e, entries);
4968 qemu_free (e);
4971 static void vm_state_notify(int running)
4973 VMChangeStateEntry *e;
4975 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4976 e->cb(e->opaque, running);
4980 /* XXX: support several handlers */
4981 static VMStopHandler *vm_stop_cb;
4982 static void *vm_stop_opaque;
4984 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4986 vm_stop_cb = cb;
4987 vm_stop_opaque = opaque;
4988 return 0;
4991 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4993 vm_stop_cb = NULL;
4996 void vm_start(void)
4998 if (!vm_running) {
4999 cpu_enable_ticks();
5000 vm_running = 1;
5001 vm_state_notify(1);
5005 void vm_stop(int reason)
5007 if (vm_running) {
5008 cpu_disable_ticks();
5009 vm_running = 0;
5010 if (reason != 0) {
5011 if (vm_stop_cb) {
5012 vm_stop_cb(vm_stop_opaque, reason);
5015 vm_state_notify(0);
5019 /* reset/shutdown handler */
5021 typedef struct QEMUResetEntry {
5022 QEMUResetHandler *func;
5023 void *opaque;
5024 struct QEMUResetEntry *next;
5025 } QEMUResetEntry;
5027 static QEMUResetEntry *first_reset_entry;
5028 int reset_requested;
5029 int shutdown_requested;
5030 static int powerdown_requested;
5032 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5034 QEMUResetEntry **pre, *re;
5036 pre = &first_reset_entry;
5037 while (*pre != NULL)
5038 pre = &(*pre)->next;
5039 re = qemu_mallocz(sizeof(QEMUResetEntry));
5040 re->func = func;
5041 re->opaque = opaque;
5042 re->next = NULL;
5043 *pre = re;
5046 void qemu_system_reset(void)
5048 QEMUResetEntry *re;
5050 /* reset all devices */
5051 for(re = first_reset_entry; re != NULL; re = re->next) {
5052 re->func(re->opaque);
5056 void qemu_system_reset_request(void)
5058 reset_requested = 1;
5059 if (cpu_single_env)
5060 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5063 void qemu_system_shutdown_request(void)
5065 shutdown_requested = 1;
5066 if (cpu_single_env)
5067 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5070 void qemu_system_powerdown_request(void)
5072 powerdown_requested = 1;
5073 if (cpu_single_env)
5074 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5077 void main_loop_wait(int timeout)
5079 IOHandlerRecord *ioh, *ioh_next;
5080 fd_set rfds, wfds, xfds;
5081 int ret, nfds;
5082 struct timeval tv;
5083 PollingEntry *pe;
5086 /* XXX: need to suppress polling by better using win32 events */
5087 ret = 0;
5088 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5089 ret |= pe->func(pe->opaque);
5091 #ifdef _WIN32
5092 if (ret == 0 && timeout > 0) {
5093 int err;
5094 WaitObjects *w = &wait_objects;
5096 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5097 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5098 if (w->func[ret - WAIT_OBJECT_0])
5099 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5100 } else if (ret == WAIT_TIMEOUT) {
5101 } else {
5102 err = GetLastError();
5103 fprintf(stderr, "Wait error %d %d\n", ret, err);
5106 #endif
5107 /* poll any events */
5108 /* XXX: separate device handlers from system ones */
5109 nfds = -1;
5110 FD_ZERO(&rfds);
5111 FD_ZERO(&wfds);
5112 FD_ZERO(&xfds);
5113 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5114 if (ioh->fd_read &&
5115 (!ioh->fd_read_poll ||
5116 ioh->fd_read_poll(ioh->opaque) != 0)) {
5117 FD_SET(ioh->fd, &rfds);
5118 if (ioh->fd > nfds)
5119 nfds = ioh->fd;
5121 if (ioh->fd_write) {
5122 FD_SET(ioh->fd, &wfds);
5123 if (ioh->fd > nfds)
5124 nfds = ioh->fd;
5128 tv.tv_sec = 0;
5129 #ifdef _WIN32
5130 tv.tv_usec = 0;
5131 #else
5132 tv.tv_usec = timeout * 1000;
5133 #endif
5134 #if defined(CONFIG_SLIRP)
5135 if (slirp_inited) {
5136 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5138 #endif
5139 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5140 if (ret > 0) {
5141 /* XXX: better handling of removal */
5142 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5143 ioh_next = ioh->next;
5144 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
5145 ioh->fd_read(ioh->opaque);
5147 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
5148 ioh->fd_write(ioh->opaque);
5152 #if defined(CONFIG_SLIRP)
5153 if (slirp_inited) {
5154 if (ret < 0) {
5155 FD_ZERO(&rfds);
5156 FD_ZERO(&wfds);
5157 FD_ZERO(&xfds);
5159 slirp_select_poll(&rfds, &wfds, &xfds);
5161 #endif
5162 #ifdef _WIN32
5163 tap_win32_poll();
5164 #endif
5166 if (vm_running) {
5167 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5168 qemu_get_clock(vm_clock));
5169 /* run dma transfers, if any */
5170 DMA_run();
5173 /* real time timers */
5174 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5175 qemu_get_clock(rt_clock));
5178 #ifndef CONFIG_DM
5179 static CPUState *cur_cpu;
5181 int main_loop(void)
5183 int ret, timeout;
5184 #ifdef CONFIG_PROFILER
5185 int64_t ti;
5186 #endif
5187 CPUState *env;
5189 cur_cpu = first_cpu;
5190 for(;;) {
5191 if (vm_running) {
5193 env = cur_cpu;
5194 for(;;) {
5195 /* get next cpu */
5196 env = env->next_cpu;
5197 if (!env)
5198 env = first_cpu;
5199 #ifdef CONFIG_PROFILER
5200 ti = profile_getclock();
5201 #endif
5202 ret = cpu_exec(env);
5203 #ifdef CONFIG_PROFILER
5204 qemu_time += profile_getclock() - ti;
5205 #endif
5206 if (ret != EXCP_HALTED)
5207 break;
5208 /* all CPUs are halted ? */
5209 if (env == cur_cpu) {
5210 ret = EXCP_HLT;
5211 break;
5214 cur_cpu = env;
5216 if (shutdown_requested) {
5217 ret = EXCP_INTERRUPT;
5218 break;
5220 if (reset_requested) {
5221 reset_requested = 0;
5222 qemu_system_reset();
5223 ret = EXCP_INTERRUPT;
5225 if (powerdown_requested) {
5226 powerdown_requested = 0;
5227 qemu_system_powerdown();
5228 ret = EXCP_INTERRUPT;
5230 if (ret == EXCP_DEBUG) {
5231 vm_stop(EXCP_DEBUG);
5233 /* if hlt instruction, we wait until the next IRQ */
5234 /* XXX: use timeout computed from timers */
5235 if (ret == EXCP_HLT)
5236 timeout = 10;
5237 else
5238 timeout = 0;
5239 } else {
5240 timeout = 10;
5242 #ifdef CONFIG_PROFILER
5243 ti = profile_getclock();
5244 #endif
5245 main_loop_wait(timeout);
5246 #ifdef CONFIG_PROFILER
5247 dev_time += profile_getclock() - ti;
5248 #endif
5250 cpu_disable_ticks();
5251 return ret;
5253 #endif /* !CONFIG_DM */
5255 void help(void)
5257 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5258 "usage: %s [options] [disk_image]\n"
5259 "\n"
5260 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5261 "\n"
5262 "Standard options:\n"
5263 "-M machine select emulated machine (-M ? for list)\n"
5264 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5265 #ifndef CONFIG_DM
5266 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5267 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5268 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5269 #endif /* !CONFIG_DM */
5270 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5271 "-snapshot write to temporary files instead of disk image files\n"
5272 #ifdef TARGET_I386
5273 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5274 #endif
5275 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5276 "-smp n set the number of CPUs to 'n' [default=1]\n"
5277 "-nographic disable graphical output and redirect serial I/Os to console\n"
5278 "-vcpus set CPU number of guest platform\n"
5279 #ifndef _WIN32
5280 "-k language use keyboard layout (for example \"fr\" for French)\n"
5281 #endif
5282 #ifdef HAS_AUDIO
5283 "-audio-help print list of audio drivers and their options\n"
5284 "-soundhw c1,... enable audio support\n"
5285 " and only specified sound cards (comma separated list)\n"
5286 " use -soundhw ? to get the list of supported cards\n"
5287 " use -soundhw all to enable all of them\n"
5288 #endif
5289 "-localtime set the real time clock to local time [default=utc]\n"
5290 "-full-screen start in full screen\n"
5291 #ifdef TARGET_I386
5292 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5293 #endif
5294 "-usb enable the USB driver (will be the default soon)\n"
5295 "-usbdevice name add the host or guest USB device 'name'\n"
5296 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5297 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5298 #endif
5299 "\n"
5300 "Network options:\n"
5301 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5302 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5303 #ifdef CONFIG_SLIRP
5304 "-net user[,vlan=n][,hostname=host]\n"
5305 " connect the user mode network stack to VLAN 'n' and send\n"
5306 " hostname 'host' to DHCP clients\n"
5307 #endif
5308 #ifdef _WIN32
5309 "-net tap[,vlan=n],ifname=name\n"
5310 " connect the host TAP network interface to VLAN 'n'\n"
5311 #else
5312 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
5313 " connect the host TAP network interface to VLAN 'n' and use\n"
5314 " the network script 'file' (default=%s);\n"
5315 " use 'fd=h' to connect to an already opened TAP interface\n"
5316 #endif
5317 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5318 " connect the vlan 'n' to another VLAN using a socket connection\n"
5319 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5320 " connect the vlan 'n' to multicast maddr and port\n"
5321 "-net none use it alone to have zero network devices; if no -net option\n"
5322 " is provided, the default is '-net nic -net user'\n"
5323 "\n"
5324 #ifdef CONFIG_SLIRP
5325 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5326 #ifndef _WIN32
5327 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5328 #endif
5329 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5330 " redirect TCP or UDP connections from host to guest [-net user]\n"
5331 #endif
5332 "\n"
5333 "Linux boot specific:\n"
5334 "-kernel bzImage use 'bzImage' as kernel image\n"
5335 "-append cmdline use 'cmdline' as kernel command line\n"
5336 "-initrd file use 'file' as initial ram disk\n"
5337 "\n"
5338 "Debug/Expert options:\n"
5339 "-monitor dev redirect the monitor to char device 'dev'\n"
5340 "-serial dev redirect the serial port to char device 'dev'\n"
5341 "-parallel dev redirect the parallel port to char device 'dev'\n"
5342 "-pidfile file Write PID to 'file'\n"
5343 "-S freeze CPU at startup (use 'c' to start execution)\n"
5344 "-s wait gdb connection to port %d\n"
5345 "-p port change gdb connection port\n"
5346 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
5347 "-d domain domain that we're serving\n"
5348 "-domain-name domain name that we're serving\n"
5349 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5350 " translation (t=none or lba) (usually qemu can guess them)\n"
5351 "-L path set the directory for the BIOS and VGA BIOS\n"
5352 #ifdef USE_KQEMU
5353 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5354 "-no-kqemu disable KQEMU kernel module usage\n"
5355 #endif
5356 #ifdef USE_CODE_COPY
5357 "-no-code-copy disable code copy acceleration\n"
5358 #endif
5359 #ifdef TARGET_I386
5360 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5361 " (default is CL-GD5446 PCI VGA)\n"
5362 "-no-acpi disable ACPI\n"
5363 #endif
5364 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5365 "-vnc display start a VNC server on display\n"
5366 "-vncviewer start a vncviewer process for this domain\n"
5367 "-vncunused bind the VNC server to an unused port\n"
5368 "-vnclisten bind the VNC server to this address\n"
5369 "-timeoffset time offset (in seconds) from local time\n"
5370 "-acpi disable or enable ACPI of HVM domain \n"
5371 "\n"
5372 "During emulation, the following keys are useful:\n"
5373 "ctrl-alt-f toggle full screen\n"
5374 "ctrl-alt-n switch to virtual console 'n'\n"
5375 "ctrl-alt toggle mouse and keyboard grab\n"
5376 "\n"
5377 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5379 "qemu",
5380 DEFAULT_RAM_SIZE,
5381 #ifndef _WIN32
5382 DEFAULT_NETWORK_SCRIPT,
5383 #endif
5384 DEFAULT_GDBSTUB_PORT,
5385 "/tmp/qemu.log");
5386 exit(1);
5389 #define HAS_ARG 0x0001
5391 enum {
5392 QEMU_OPTION_h,
5394 QEMU_OPTION_M,
5395 QEMU_OPTION_fda,
5396 QEMU_OPTION_fdb,
5397 #ifndef CONFIG_DM
5398 QEMU_OPTION_hda,
5399 QEMU_OPTION_hdb,
5400 QEMU_OPTION_hdc,
5401 QEMU_OPTION_hdd,
5402 QEMU_OPTION_cdrom,
5403 #endif /* !CONFIG_DM */
5404 QEMU_OPTION_boot,
5405 QEMU_OPTION_snapshot,
5406 #ifdef TARGET_I386
5407 QEMU_OPTION_no_fd_bootchk,
5408 #endif
5409 QEMU_OPTION_m,
5410 QEMU_OPTION_nographic,
5411 #ifdef HAS_AUDIO
5412 QEMU_OPTION_audio_help,
5413 QEMU_OPTION_soundhw,
5414 #endif
5416 QEMU_OPTION_net,
5417 QEMU_OPTION_tftp,
5418 QEMU_OPTION_smb,
5419 QEMU_OPTION_redir,
5421 QEMU_OPTION_kernel,
5422 QEMU_OPTION_append,
5423 QEMU_OPTION_initrd,
5425 QEMU_OPTION_S,
5426 QEMU_OPTION_s,
5427 QEMU_OPTION_p,
5428 QEMU_OPTION_l,
5429 QEMU_OPTION_hdachs,
5430 QEMU_OPTION_L,
5431 #ifdef USE_CODE_COPY
5432 QEMU_OPTION_no_code_copy,
5433 #endif
5434 QEMU_OPTION_k,
5435 QEMU_OPTION_localtime,
5436 QEMU_OPTION_cirrusvga,
5437 QEMU_OPTION_g,
5438 QEMU_OPTION_std_vga,
5439 QEMU_OPTION_monitor,
5440 QEMU_OPTION_domainname,
5441 QEMU_OPTION_serial,
5442 QEMU_OPTION_parallel,
5443 QEMU_OPTION_loadvm,
5444 QEMU_OPTION_full_screen,
5445 QEMU_OPTION_pidfile,
5446 QEMU_OPTION_no_kqemu,
5447 QEMU_OPTION_kernel_kqemu,
5448 QEMU_OPTION_win2k_hack,
5449 QEMU_OPTION_usb,
5450 QEMU_OPTION_usbdevice,
5451 QEMU_OPTION_smp,
5452 QEMU_OPTION_vnc,
5453 QEMU_OPTION_no_acpi,
5455 QEMU_OPTION_d,
5456 QEMU_OPTION_vcpus,
5457 QEMU_OPTION_timeoffset,
5458 QEMU_OPTION_acpi,
5459 QEMU_OPTION_vncviewer,
5460 QEMU_OPTION_vncunused,
5461 QEMU_OPTION_vnclisten,
5462 };
5464 typedef struct QEMUOption {
5465 const char *name;
5466 int flags;
5467 int index;
5468 } QEMUOption;
5470 const QEMUOption qemu_options[] = {
5471 { "h", 0, QEMU_OPTION_h },
5473 { "M", HAS_ARG, QEMU_OPTION_M },
5474 { "fda", HAS_ARG, QEMU_OPTION_fda },
5475 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5476 #ifndef CONFIG_DM
5477 { "hda", HAS_ARG, QEMU_OPTION_hda },
5478 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5479 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5480 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5481 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5482 #endif /* !CONFIG_DM */
5483 { "boot", HAS_ARG, QEMU_OPTION_boot },
5484 { "snapshot", 0, QEMU_OPTION_snapshot },
5485 #ifdef TARGET_I386
5486 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5487 #endif
5488 { "m", HAS_ARG, QEMU_OPTION_m },
5489 { "nographic", 0, QEMU_OPTION_nographic },
5490 { "k", HAS_ARG, QEMU_OPTION_k },
5491 #ifdef HAS_AUDIO
5492 { "audio-help", 0, QEMU_OPTION_audio_help },
5493 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5494 #endif
5496 { "net", HAS_ARG, QEMU_OPTION_net},
5497 #ifdef CONFIG_SLIRP
5498 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5499 #ifndef _WIN32
5500 { "smb", HAS_ARG, QEMU_OPTION_smb },
5501 #endif
5502 { "redir", HAS_ARG, QEMU_OPTION_redir },
5503 #endif
5505 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5506 { "append", HAS_ARG, QEMU_OPTION_append },
5507 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5509 { "S", 0, QEMU_OPTION_S },
5510 { "s", 0, QEMU_OPTION_s },
5511 { "p", HAS_ARG, QEMU_OPTION_p },
5512 { "l", HAS_ARG, QEMU_OPTION_l },
5513 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5514 { "L", HAS_ARG, QEMU_OPTION_L },
5515 #ifdef USE_CODE_COPY
5516 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5517 #endif
5518 #ifdef USE_KQEMU
5519 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5520 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5521 #endif
5522 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5523 { "g", 1, QEMU_OPTION_g },
5524 #endif
5525 { "localtime", 0, QEMU_OPTION_localtime },
5526 { "std-vga", 0, QEMU_OPTION_std_vga },
5527 { "monitor", 1, QEMU_OPTION_monitor },
5528 { "domain-name", 1, QEMU_OPTION_domainname },
5529 { "serial", 1, QEMU_OPTION_serial },
5530 { "parallel", 1, QEMU_OPTION_parallel },
5531 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5532 { "full-screen", 0, QEMU_OPTION_full_screen },
5533 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5534 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5535 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5536 { "smp", HAS_ARG, QEMU_OPTION_smp },
5537 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5538 { "vncviewer", 0, QEMU_OPTION_vncviewer },
5539 { "vncunused", 0, QEMU_OPTION_vncunused },
5540 { "vnclisten", HAS_ARG, QEMU_OPTION_vnclisten },
5542 /* temporary options */
5543 { "usb", 0, QEMU_OPTION_usb },
5544 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5545 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5547 { "d", HAS_ARG, QEMU_OPTION_d },
5548 { "vcpus", 1, QEMU_OPTION_vcpus },
5549 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
5550 { "acpi", 0, QEMU_OPTION_acpi },
5551 { NULL },
5552 };
5554 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5556 /* this stack is only used during signal handling */
5557 #define SIGNAL_STACK_SIZE 32768
5559 static uint8_t *signal_stack;
5561 #endif
5563 /* password input */
5565 static BlockDriverState *get_bdrv(int index)
5567 BlockDriverState *bs;
5569 if (index < 4) {
5570 bs = bs_table[index];
5571 } else if (index < 6) {
5572 bs = fd_table[index - 4];
5573 } else {
5574 bs = NULL;
5576 return bs;
5579 static void read_passwords(void)
5581 BlockDriverState *bs;
5582 int i, j;
5583 char password[256];
5585 for(i = 0; i < 6; i++) {
5586 bs = get_bdrv(i);
5587 if (bs && bdrv_is_encrypted(bs)) {
5588 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5589 for(j = 0; j < 3; j++) {
5590 monitor_readline("Password: ",
5591 1, password, sizeof(password));
5592 if (bdrv_set_key(bs, password) == 0)
5593 break;
5594 term_printf("invalid password\n");
5600 /* XXX: currently we cannot use simultaneously different CPUs */
5601 void register_machines(void)
5603 #if defined(TARGET_I386)
5604 qemu_register_machine(&pc_machine);
5605 qemu_register_machine(&isapc_machine);
5606 #elif defined(TARGET_PPC)
5607 qemu_register_machine(&heathrow_machine);
5608 qemu_register_machine(&core99_machine);
5609 qemu_register_machine(&prep_machine);
5610 #elif defined(TARGET_MIPS)
5611 qemu_register_machine(&mips_machine);
5612 #elif defined(TARGET_SPARC)
5613 #ifdef TARGET_SPARC64
5614 qemu_register_machine(&sun4u_machine);
5615 #else
5616 qemu_register_machine(&sun4m_machine);
5617 #endif
5618 #elif defined(TARGET_ARM)
5619 qemu_register_machine(&integratorcp926_machine);
5620 qemu_register_machine(&integratorcp1026_machine);
5621 qemu_register_machine(&versatilepb_machine);
5622 qemu_register_machine(&versatileab_machine);
5623 #elif defined(TARGET_SH4)
5624 qemu_register_machine(&shix_machine);
5625 #else
5626 #error unsupported CPU
5627 #endif
5630 #ifdef HAS_AUDIO
5631 struct soundhw soundhw[] = {
5632 #ifndef CONFIG_DM
5633 #ifdef TARGET_I386
5635 "pcspk",
5636 "PC speaker",
5637 0,
5638 1,
5639 { .init_isa = pcspk_audio_init }
5640 },
5641 #endif
5642 #endif /* !CONFIG_DM */
5644 "sb16",
5645 "Creative Sound Blaster 16",
5646 0,
5647 1,
5648 { .init_isa = SB16_init }
5649 },
5651 #ifdef CONFIG_ADLIB
5653 "adlib",
5654 #ifdef HAS_YMF262
5655 "Yamaha YMF262 (OPL3)",
5656 #else
5657 "Yamaha YM3812 (OPL2)",
5658 #endif
5659 0,
5660 1,
5661 { .init_isa = Adlib_init }
5662 },
5663 #endif
5665 #ifdef CONFIG_GUS
5667 "gus",
5668 "Gravis Ultrasound GF1",
5669 0,
5670 1,
5671 { .init_isa = GUS_init }
5672 },
5673 #endif
5676 "es1370",
5677 "ENSONIQ AudioPCI ES1370",
5678 0,
5679 0,
5680 { .init_pci = es1370_init }
5681 },
5683 { NULL, NULL, 0, 0, { NULL } }
5684 };
5686 static void select_soundhw (const char *optarg)
5688 struct soundhw *c;
5690 if (*optarg == '?') {
5691 show_valid_cards:
5693 printf ("Valid sound card names (comma separated):\n");
5694 for (c = soundhw; c->name; ++c) {
5695 printf ("%-11s %s\n", c->name, c->descr);
5697 printf ("\n-soundhw all will enable all of the above\n");
5698 exit (*optarg != '?');
5700 else {
5701 size_t l;
5702 const char *p;
5703 char *e;
5704 int bad_card = 0;
5706 if (!strcmp (optarg, "all")) {
5707 for (c = soundhw; c->name; ++c) {
5708 c->enabled = 1;
5710 return;
5713 p = optarg;
5714 while (*p) {
5715 e = strchr (p, ',');
5716 l = !e ? strlen (p) : (size_t) (e - p);
5718 for (c = soundhw; c->name; ++c) {
5719 if (!strncmp (c->name, p, l)) {
5720 c->enabled = 1;
5721 break;
5725 if (!c->name) {
5726 if (l > 80) {
5727 fprintf (stderr,
5728 "Unknown sound card name (too big to show)\n");
5730 else {
5731 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5732 (int) l, p);
5734 bad_card = 1;
5736 p += l + (e != NULL);
5739 if (bad_card)
5740 goto show_valid_cards;
5743 #endif
5745 #ifdef _WIN32
5746 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5748 exit(STATUS_CONTROL_C_EXIT);
5749 return TRUE;
5751 #endif
5753 #define MAX_NET_CLIENTS 32
5755 #include <xg_private.h>
5757 /* FIXME Flush the shadow page */
5758 int unset_mm_mapping(int xc_handle, uint32_t domid,
5759 unsigned long nr_pages, unsigned int address_bits,
5760 xen_pfn_t *extent_start)
5762 int err = 0;
5763 xc_dominfo_t info;
5765 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5766 nr_pages, 0, extent_start);
5767 if (err)
5768 fprintf(stderr, "Failed to decrease physmap\n");
5770 xc_domain_getinfo(xc_handle, domid, 1, &info);
5772 if ((info.nr_pages - nr_pages) <= 0) {
5773 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5774 err = -1;
5777 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5778 PAGE_SIZE/1024) != 0) {
5779 fprintf(logfile, "set maxmem returned error %d\n", errno);
5780 err = -1;
5783 return err;
5786 int set_mm_mapping(int xc_handle, uint32_t domid,
5787 unsigned long nr_pages, unsigned int address_bits,
5788 xen_pfn_t *extent_start)
5790 xc_dominfo_t info;
5791 int err = 0;
5793 xc_domain_getinfo(xc_handle, domid, 1, &info);
5795 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5796 nr_pages * PAGE_SIZE/1024) != 0) {
5797 fprintf(logfile, "set maxmem returned error %d\n", errno);
5798 return -1;
5801 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5802 address_bits, extent_start);
5803 if (err) {
5804 fprintf(stderr, "Failed to populate physmap\n");
5805 return -1;
5808 return 0;
5811 int main(int argc, char **argv)
5813 #ifdef CONFIG_GDBSTUB
5814 int use_gdbstub, gdbstub_port;
5815 #endif
5816 int i;
5817 #ifndef CONFIG_DM
5818 int cdrom_index;
5819 #endif /* !CONFIG_DM */
5820 int snapshot, linux_boot;
5821 const char *initrd_filename;
5822 #ifndef CONFIG_DM
5823 const char *hd_filename[MAX_DISKS];
5824 #endif /* !CONFIG_DM */
5825 const char *fd_filename[MAX_FD];
5826 const char *kernel_filename, *kernel_cmdline;
5827 DisplayState *ds = &display_state;
5828 int cyls, heads, secs, translation;
5829 int start_emulation = 1;
5830 char net_clients[MAX_NET_CLIENTS][256];
5831 int nb_net_clients;
5832 int optind;
5833 const char *r, *optarg;
5834 CharDriverState *monitor_hd;
5835 char monitor_device[128];
5836 char serial_devices[MAX_SERIAL_PORTS][128];
5837 int serial_device_index;
5838 char parallel_devices[MAX_PARALLEL_PORTS][128];
5839 int parallel_device_index;
5840 const char *loadvm = NULL;
5841 QEMUMachine *machine;
5842 char usb_devices[MAX_USB_CMDLINE][128];
5843 int usb_devices_index;
5844 unsigned long nr_pages, tmp_nr_pages, shared_page_nr;
5845 xen_pfn_t *page_array;
5846 extern void *shared_page;
5847 extern void *buffered_io_page;
5849 char qemu_dm_logfilename[64];
5851 LIST_INIT (&vm_change_state_head);
5852 #ifndef _WIN32
5854 struct sigaction act;
5855 sigfillset(&act.sa_mask);
5856 act.sa_flags = 0;
5857 act.sa_handler = SIG_IGN;
5858 sigaction(SIGPIPE, &act, NULL);
5860 #else
5861 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5862 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5863 QEMU to run on a single CPU */
5865 HANDLE h;
5866 DWORD mask, smask;
5867 int i;
5868 h = GetCurrentProcess();
5869 if (GetProcessAffinityMask(h, &mask, &smask)) {
5870 for(i = 0; i < 32; i++) {
5871 if (mask & (1 << i))
5872 break;
5874 if (i != 32) {
5875 mask = 1 << i;
5876 SetProcessAffinityMask(h, mask);
5880 #endif
5882 register_machines();
5883 machine = first_machine;
5884 initrd_filename = NULL;
5885 for(i = 0; i < MAX_FD; i++)
5886 fd_filename[i] = NULL;
5887 #ifndef CONFIG_DM
5888 for(i = 0; i < MAX_DISKS; i++)
5889 hd_filename[i] = NULL;
5890 #endif /* !CONFIG_DM */
5891 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5892 vga_ram_size = VGA_RAM_SIZE;
5893 bios_size = BIOS_SIZE;
5894 #ifdef CONFIG_GDBSTUB
5895 use_gdbstub = 0;
5896 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5897 #endif
5898 snapshot = 0;
5899 nographic = 0;
5900 vncviewer = 0;
5901 vncunused = 0;
5902 kernel_filename = NULL;
5903 kernel_cmdline = "";
5904 *vncpasswd = '\0';
5905 #ifndef CONFIG_DM
5906 #ifdef TARGET_PPC
5907 cdrom_index = 1;
5908 #else
5909 cdrom_index = 2;
5910 #endif
5911 #endif /* !CONFIG_DM */
5912 cyls = heads = secs = 0;
5913 translation = BIOS_ATA_TRANSLATION_AUTO;
5914 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5916 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5917 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5918 serial_devices[i][0] = '\0';
5919 serial_device_index = 0;
5921 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5922 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5923 parallel_devices[i][0] = '\0';
5924 parallel_device_index = 0;
5926 usb_devices_index = 0;
5928 nb_net_clients = 0;
5930 nb_nics = 0;
5931 /* default mac address of the first network interface */
5933 memset(&vnclisten_addr.sin_addr, 0, sizeof(vnclisten_addr.sin_addr));
5935 /* init debug */
5936 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm.%ld.log", (long)getpid());
5937 cpu_set_log_filename(qemu_dm_logfilename);
5938 cpu_set_log(0);
5940 optind = 1;
5941 for(;;) {
5942 if (optind >= argc)
5943 break;
5944 r = argv[optind];
5945 if (r[0] != '-') {
5946 #ifndef CONFIG_DM
5947 hd_filename[0] = argv[optind++];
5948 #else
5949 help();
5950 #endif /* !CONFIG_DM */
5951 } else {
5952 const QEMUOption *popt;
5954 optind++;
5955 popt = qemu_options;
5956 for(;;) {
5957 if (!popt->name) {
5958 fprintf(stderr, "%s: invalid option -- '%s'\n",
5959 argv[0], r);
5960 exit(1);
5962 if (!strcmp(popt->name, r + 1))
5963 break;
5964 popt++;
5966 if (popt->flags & HAS_ARG) {
5967 if (optind >= argc) {
5968 fprintf(stderr, "%s: option '%s' requires an argument\n",
5969 argv[0], r);
5970 exit(1);
5972 optarg = argv[optind++];
5973 } else {
5974 optarg = NULL;
5977 switch(popt->index) {
5978 case QEMU_OPTION_M:
5979 machine = find_machine(optarg);
5980 if (!machine) {
5981 QEMUMachine *m;
5982 printf("Supported machines are:\n");
5983 for(m = first_machine; m != NULL; m = m->next) {
5984 printf("%-10s %s%s\n",
5985 m->name, m->desc,
5986 m == first_machine ? " (default)" : "");
5988 exit(1);
5990 break;
5991 case QEMU_OPTION_initrd:
5992 initrd_filename = optarg;
5993 break;
5994 #ifndef CONFIG_DM
5995 case QEMU_OPTION_hda:
5996 case QEMU_OPTION_hdb:
5997 case QEMU_OPTION_hdc:
5998 case QEMU_OPTION_hdd:
6000 int hd_index;
6001 hd_index = popt->index - QEMU_OPTION_hda;
6002 hd_filename[hd_index] = optarg;
6003 if (hd_index == cdrom_index)
6004 cdrom_index = -1;
6006 break;
6007 #endif /* !CONFIG_DM */
6008 case QEMU_OPTION_snapshot:
6009 snapshot = 1;
6010 break;
6011 case QEMU_OPTION_hdachs:
6013 const char *p;
6014 p = optarg;
6015 cyls = strtol(p, (char **)&p, 0);
6016 if (cyls < 1 || cyls > 16383)
6017 goto chs_fail;
6018 if (*p != ',')
6019 goto chs_fail;
6020 p++;
6021 heads = strtol(p, (char **)&p, 0);
6022 if (heads < 1 || heads > 16)
6023 goto chs_fail;
6024 if (*p != ',')
6025 goto chs_fail;
6026 p++;
6027 secs = strtol(p, (char **)&p, 0);
6028 if (secs < 1 || secs > 63)
6029 goto chs_fail;
6030 if (*p == ',') {
6031 p++;
6032 if (!strcmp(p, "none"))
6033 translation = BIOS_ATA_TRANSLATION_NONE;
6034 else if (!strcmp(p, "lba"))
6035 translation = BIOS_ATA_TRANSLATION_LBA;
6036 else if (!strcmp(p, "auto"))
6037 translation = BIOS_ATA_TRANSLATION_AUTO;
6038 else
6039 goto chs_fail;
6040 } else if (*p != '\0') {
6041 chs_fail:
6042 fprintf(stderr, "qemu: invalid physical CHS format\n");
6043 exit(1);
6046 break;
6047 case QEMU_OPTION_nographic:
6048 if(!strcmp(monitor_device, "vc"))
6049 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6050 if(!strcmp(serial_devices[0], "vc"))
6051 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
6052 "null");
6053 nographic = 1;
6054 break;
6055 case QEMU_OPTION_kernel:
6056 kernel_filename = optarg;
6057 break;
6058 case QEMU_OPTION_append:
6059 kernel_cmdline = optarg;
6060 break;
6061 #ifndef CONFIG_DM
6062 case QEMU_OPTION_cdrom:
6063 if (cdrom_index >= 0) {
6064 hd_filename[cdrom_index] = optarg;
6066 break;
6067 #endif /* !CONFIG_DM */
6068 case QEMU_OPTION_boot:
6069 boot_device = strdup(optarg);
6070 if (strspn(boot_device, "acd"
6071 #ifdef TARGET_SPARC
6072 "n"
6073 #endif
6074 ) != strlen(boot_device)) {
6075 fprintf(stderr, "qemu: invalid boot device in '%s'\n",
6076 boot_device);
6077 exit(1);
6079 break;
6080 case QEMU_OPTION_fda:
6081 fd_filename[0] = optarg;
6082 break;
6083 case QEMU_OPTION_fdb:
6084 fd_filename[1] = optarg;
6085 break;
6086 #ifdef TARGET_I386
6087 case QEMU_OPTION_no_fd_bootchk:
6088 fd_bootchk = 0;
6089 break;
6090 #endif
6091 #ifdef USE_CODE_COPY
6092 case QEMU_OPTION_no_code_copy:
6093 code_copy_enabled = 0;
6094 break;
6095 #endif
6096 case QEMU_OPTION_net:
6097 if (nb_net_clients >= MAX_NET_CLIENTS) {
6098 fprintf(stderr, "qemu: too many network clients\n");
6099 exit(1);
6101 pstrcpy(net_clients[nb_net_clients],
6102 sizeof(net_clients[0]),
6103 optarg);
6104 nb_net_clients++;
6105 break;
6106 #ifdef CONFIG_SLIRP
6107 case QEMU_OPTION_tftp:
6108 tftp_prefix = optarg;
6109 break;
6110 #ifndef _WIN32
6111 case QEMU_OPTION_smb:
6112 net_slirp_smb(optarg);
6113 break;
6114 #endif
6115 case QEMU_OPTION_redir:
6116 net_slirp_redir(optarg);
6117 break;
6118 #endif
6119 #ifdef HAS_AUDIO
6120 case QEMU_OPTION_audio_help:
6121 AUD_help ();
6122 exit (0);
6123 break;
6124 case QEMU_OPTION_soundhw:
6125 select_soundhw (optarg);
6126 break;
6127 #endif
6128 case QEMU_OPTION_h:
6129 help();
6130 break;
6131 case QEMU_OPTION_m:
6132 ram_size = atol(optarg) * 1024 * 1024;
6133 if (ram_size <= 0)
6134 help();
6135 #ifndef CONFIG_DM
6136 if (ram_size > PHYS_RAM_MAX_SIZE) {
6137 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6138 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6139 exit(1);
6141 #endif /* !CONFIG_DM */
6142 break;
6143 case QEMU_OPTION_l:
6145 int mask;
6146 CPULogItem *item;
6148 mask = cpu_str_to_log_mask(optarg);
6149 if (!mask) {
6150 printf("Log items (comma separated):\n");
6151 for(item = cpu_log_items; item->mask != 0; item++) {
6152 printf("%-10s %s\n", item->name, item->help);
6154 exit(1);
6156 cpu_set_log(mask);
6158 break;
6159 #ifdef CONFIG_GDBSTUB
6160 case QEMU_OPTION_s:
6161 use_gdbstub = 1;
6162 break;
6163 case QEMU_OPTION_p:
6164 gdbstub_port = atoi(optarg);
6165 break;
6166 #endif
6167 case QEMU_OPTION_L:
6168 bios_dir = optarg;
6169 break;
6170 case QEMU_OPTION_S:
6171 start_emulation = 0;
6172 break;
6173 case QEMU_OPTION_k:
6174 keyboard_layout = optarg;
6175 break;
6176 case QEMU_OPTION_localtime:
6177 rtc_utc = 0;
6178 break;
6179 case QEMU_OPTION_cirrusvga:
6180 cirrus_vga_enabled = 1;
6181 break;
6182 case QEMU_OPTION_std_vga:
6183 cirrus_vga_enabled = 0;
6184 break;
6185 case QEMU_OPTION_g:
6187 const char *p;
6188 int w, h, depth;
6189 p = optarg;
6190 w = strtol(p, (char **)&p, 10);
6191 if (w <= 0) {
6192 graphic_error:
6193 fprintf(stderr, "qemu: invalid resolution or depth\n");
6194 exit(1);
6196 if (*p != 'x')
6197 goto graphic_error;
6198 p++;
6199 h = strtol(p, (char **)&p, 10);
6200 if (h <= 0)
6201 goto graphic_error;
6202 if (*p == 'x') {
6203 p++;
6204 depth = strtol(p, (char **)&p, 10);
6205 if (depth != 8 && depth != 15 && depth != 16 &&
6206 depth != 24 && depth != 32)
6207 goto graphic_error;
6208 } else if (*p == '\0') {
6209 depth = graphic_depth;
6210 } else {
6211 goto graphic_error;
6214 graphic_width = w;
6215 graphic_height = h;
6216 graphic_depth = depth;
6218 break;
6219 case QEMU_OPTION_monitor:
6220 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6221 break;
6222 case QEMU_OPTION_serial:
6223 if (serial_device_index >= MAX_SERIAL_PORTS) {
6224 fprintf(stderr, "qemu: too many serial ports\n");
6225 exit(1);
6227 pstrcpy(serial_devices[serial_device_index],
6228 sizeof(serial_devices[0]), optarg);
6229 serial_device_index++;
6230 break;
6231 case QEMU_OPTION_parallel:
6232 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6233 fprintf(stderr, "qemu: too many parallel ports\n");
6234 exit(1);
6236 pstrcpy(parallel_devices[parallel_device_index],
6237 sizeof(parallel_devices[0]), optarg);
6238 parallel_device_index++;
6239 break;
6240 case QEMU_OPTION_loadvm:
6241 loadvm = optarg;
6242 break;
6243 case QEMU_OPTION_full_screen:
6244 full_screen = 1;
6245 break;
6246 case QEMU_OPTION_pidfile:
6247 create_pidfile(optarg);
6248 break;
6249 #ifdef TARGET_I386
6250 case QEMU_OPTION_win2k_hack:
6251 win2k_install_hack = 1;
6252 break;
6253 #endif
6254 #ifdef USE_KQEMU
6255 case QEMU_OPTION_no_kqemu:
6256 kqemu_allowed = 0;
6257 break;
6258 case QEMU_OPTION_kernel_kqemu:
6259 kqemu_allowed = 2;
6260 break;
6261 #endif
6262 case QEMU_OPTION_usb:
6263 usb_enabled = 1;
6264 break;
6265 case QEMU_OPTION_usbdevice:
6266 usb_enabled = 1;
6267 if (usb_devices_index >= MAX_USB_CMDLINE) {
6268 fprintf(stderr, "Too many USB devices\n");
6269 exit(1);
6271 pstrcpy(usb_devices[usb_devices_index],
6272 sizeof(usb_devices[usb_devices_index]),
6273 optarg);
6274 usb_devices_index++;
6275 break;
6276 case QEMU_OPTION_smp:
6277 smp_cpus = atoi(optarg);
6278 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6279 fprintf(stderr, "Invalid number of CPUs\n");
6280 exit(1);
6282 break;
6283 case QEMU_OPTION_vnc:
6284 vnc_display = atoi(optarg);
6285 if (vnc_display < 0) {
6286 fprintf(stderr, "Invalid VNC display\n");
6287 exit(1);
6289 break;
6290 case QEMU_OPTION_no_acpi:
6291 acpi_enabled = 0;
6292 break;
6293 case QEMU_OPTION_domainname:
6294 strncat(domain_name, optarg, sizeof(domain_name) - 20);
6295 break;
6296 case QEMU_OPTION_d:
6297 domid = atoi(optarg);
6298 fprintf(logfile, "domid: %d\n", domid);
6299 break;
6300 case QEMU_OPTION_vcpus:
6301 vcpus = atoi(optarg);
6302 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
6303 break;
6304 case QEMU_OPTION_timeoffset:
6305 timeoffset = strtol(optarg, NULL, 0);
6306 break;
6307 case QEMU_OPTION_acpi:
6308 acpi_enabled = 1;
6309 break;
6310 case QEMU_OPTION_vncviewer:
6311 vncviewer++;
6312 break;
6313 case QEMU_OPTION_vncunused:
6314 vncunused++;
6315 if (vnc_display == -1)
6316 vnc_display = 0;
6317 break;
6318 case QEMU_OPTION_vnclisten:
6319 parse_host(&vnclisten_addr, optarg);
6320 break;
6325 #ifdef CONFIG_DM
6326 bdrv_init();
6327 xenstore_parse_domain_config(domid);
6328 #endif /* CONFIG_DM */
6330 #ifdef USE_KQEMU
6331 if (smp_cpus > 1)
6332 kqemu_allowed = 0;
6333 #endif
6334 linux_boot = (kernel_filename != NULL);
6336 #ifndef CONFIG_DM
6337 if (!linux_boot &&
6338 hd_filename[0] == '\0' &&
6339 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6340 fd_filename[0] == '\0')
6341 help();
6343 #if 0
6344 /* boot to cd by default if no hard disk */
6345 if (hd_filename[0] == '\0' && boot_device == 'c') {
6346 if (fd_filename[0] != '\0')
6347 boot_device = 'a';
6348 else
6349 boot_device = 'd';
6351 #endif
6352 #endif /* !CONFIG_DM */
6354 setvbuf(stdout, NULL, _IOLBF, 0);
6356 init_timers();
6357 init_timer_alarm();
6359 #ifdef _WIN32
6360 socket_init();
6361 #endif
6363 #ifndef CONFIG_DM
6364 /* init network clients */
6365 if (nb_net_clients == 0) {
6366 /* if no clients, we use a default config */
6367 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6368 "nic");
6369 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6370 "user");
6371 nb_net_clients = 2;
6373 #endif /* !CONFIG_DM */
6375 for(i = 0;i < nb_net_clients; i++) {
6376 if (net_client_init(net_clients[i]) < 0)
6377 exit(1);
6380 #if defined (__ia64__)
6381 if (ram_size > MMIO_START)
6382 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
6383 #endif
6385 /* init the memory */
6386 phys_ram_size = ram_size + vga_ram_size + bios_size;
6388 #ifdef CONFIG_DM
6390 xc_handle = xc_interface_open();
6392 nr_pages = ram_size/PAGE_SIZE;
6393 tmp_nr_pages = nr_pages;
6395 #if defined(__i386__) || defined(__x86_64__)
6396 if (ram_size > HVM_BELOW_4G_RAM_END) {
6397 tmp_nr_pages += HVM_BELOW_4G_MMIO_LENGTH >> PAGE_SHIFT;
6398 shared_page_nr = (HVM_BELOW_4G_RAM_END >> PAGE_SHIFT) - 1;
6399 } else
6400 shared_page_nr = nr_pages - 1;
6401 #endif
6403 page_array = (xen_pfn_t *)malloc(tmp_nr_pages * sizeof(xen_pfn_t));
6404 if (page_array == NULL) {
6405 fprintf(logfile, "malloc returned error %d\n", errno);
6406 exit(-1);
6409 #if defined(__i386__) || defined(__x86_64__)
6410 for ( i = 0; i < tmp_nr_pages; i++)
6411 page_array[i] = i;
6413 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6414 PROT_READ|PROT_WRITE, page_array,
6415 tmp_nr_pages);
6416 if (phys_ram_base == NULL) {
6417 fprintf(logfile, "batch map guest memory returned error %d\n", errno);
6418 exit(-1);
6421 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6422 PROT_READ|PROT_WRITE,
6423 page_array[shared_page_nr]);
6424 if (shared_page == NULL) {
6425 fprintf(logfile, "map shared IO page returned error %d\n", errno);
6426 exit(-1);
6429 fprintf(logfile, "shared page at pfn:%lx, mfn: %"PRIx64"\n",
6430 shared_page_nr, (uint64_t)(page_array[shared_page_nr]));
6432 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6433 PROT_READ|PROT_WRITE,
6434 page_array[shared_page_nr - 2]);
6435 if (buffered_io_page == NULL) {
6436 fprintf(logfile, "map buffered IO page returned error %d\n", errno);
6437 exit(-1);
6440 fprintf(logfile, "buffered io page at pfn:%lx, mfn: %"PRIx64"\n",
6441 shared_page_nr - 2, (uint64_t)(page_array[shared_page_nr - 2]));
6443 free(page_array);
6445 #elif defined(__ia64__)
6447 if (xc_ia64_get_pfn_list(xc_handle, domid, page_array,
6448 IO_PAGE_START >> PAGE_SHIFT, 3) != 3) {
6449 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
6450 exit(-1);
6453 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6454 PROT_READ|PROT_WRITE,
6455 page_array[0]);
6457 fprintf(logfile, "shared page at pfn:%lx, mfn: %016lx\n",
6458 IO_PAGE_START >> PAGE_SHIFT, page_array[0]);
6460 buffered_io_page =xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6461 PROT_READ|PROT_WRITE,
6462 page_array[2]);
6463 fprintf(logfile, "Buffered IO page at pfn:%lx, mfn: %016lx\n",
6464 BUFFER_IO_PAGE_START >> PAGE_SHIFT, page_array[2]);
6466 if (xc_ia64_get_pfn_list(xc_handle, domid,
6467 page_array, 0, nr_pages) != nr_pages) {
6468 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
6469 exit(-1);
6472 if (ram_size > MMIO_START) {
6473 for (i = 0 ; i < (MEM_G >> PAGE_SHIFT); i++)
6474 page_array[(MMIO_START >> PAGE_SHIFT) + i] =
6475 page_array[(IO_PAGE_START >> PAGE_SHIFT) + 1];
6478 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6479 PROT_READ|PROT_WRITE,
6480 page_array, nr_pages);
6481 if (phys_ram_base == 0) {
6482 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6483 exit(-1);
6485 free(page_array);
6486 #endif
6487 #else /* !CONFIG_DM */
6489 phys_ram_base = qemu_vmalloc(phys_ram_size);
6490 if (!phys_ram_base) {
6491 fprintf(stderr, "Could not allocate physical memory\n");
6492 exit(1);
6495 #endif /* !CONFIG_DM */
6497 #ifndef CONFIG_DM
6498 /* we always create the cdrom drive, even if no disk is there */
6499 bdrv_init();
6500 if (cdrom_index >= 0) {
6501 bs_table[cdrom_index] = bdrv_new("cdrom");
6502 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6505 /* open the virtual block devices */
6506 for(i = 0; i < MAX_DISKS; i++) {
6507 if (hd_filename[i]) {
6508 if (!bs_table[i]) {
6509 char buf[64];
6510 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6511 bs_table[i] = bdrv_new(buf);
6513 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6514 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6515 hd_filename[i]);
6516 exit(1);
6518 if (i == 0 && cyls != 0) {
6519 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6520 bdrv_set_translation_hint(bs_table[i], translation);
6524 #endif /* !CONFIG_DM */
6526 /* we always create at least one floppy disk */
6527 fd_table[0] = bdrv_new("fda");
6528 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6530 for(i = 0; i < MAX_FD; i++) {
6531 if (fd_filename[i]) {
6532 if (!fd_table[i]) {
6533 char buf[64];
6534 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6535 fd_table[i] = bdrv_new(buf);
6536 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6538 if (fd_filename[i] != '\0') {
6539 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6540 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6541 fd_filename[i]);
6542 exit(1);
6548 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6549 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6551 init_ioports();
6553 /* read vncpasswd from xenstore */
6554 if (0 > xenstore_read_vncpasswd(domid))
6555 exit(1);
6557 /* terminal init */
6558 if (nographic) {
6559 dumb_display_init(ds);
6560 } else if (vnc_display != -1) {
6561 vnc_display = vnc_display_init(ds, vnc_display, vncunused, &vnclisten_addr);
6562 if (vncviewer)
6563 vnc_start_viewer(vnc_display);
6564 xenstore_write_vncport(vnc_display);
6565 } else {
6566 #if defined(CONFIG_SDL)
6567 sdl_display_init(ds, full_screen);
6568 #elif defined(CONFIG_COCOA)
6569 cocoa_display_init(ds, full_screen);
6570 #else
6571 dumb_display_init(ds);
6572 #endif
6575 monitor_hd = qemu_chr_open(monitor_device);
6576 if (!monitor_hd) {
6577 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6578 exit(1);
6580 monitor_init(monitor_hd, !nographic);
6582 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6583 if (serial_devices[i][0] != '\0') {
6584 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6585 if (!serial_hds[i]) {
6586 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6587 serial_devices[i]);
6588 exit(1);
6590 if (!strcmp(serial_devices[i], "vc"))
6591 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6595 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6596 if (parallel_devices[i][0] != '\0') {
6597 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6598 if (!parallel_hds[i]) {
6599 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6600 parallel_devices[i]);
6601 exit(1);
6603 if (!strcmp(parallel_devices[i], "vc"))
6604 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6608 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6610 machine->init(ram_size, vga_ram_size, boot_device,
6611 ds, fd_filename, snapshot,
6612 kernel_filename, kernel_cmdline, initrd_filename,
6613 timeoffset);
6614 free(boot_device);
6616 /* init USB devices */
6617 if (usb_enabled) {
6618 for(i = 0; i < usb_devices_index; i++) {
6619 if (usb_device_add(usb_devices[i]) < 0) {
6620 fprintf(stderr, "Warning: could not add USB device %s\n",
6621 usb_devices[i]);
6626 if (vnc_display == -1) {
6627 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6628 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6631 #ifdef CONFIG_GDBSTUB
6632 if (use_gdbstub) {
6633 if (gdbserver_start(gdbstub_port) < 0) {
6634 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6635 gdbstub_port);
6636 exit(1);
6637 } else {
6638 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6640 } else
6641 #endif
6642 if (loadvm)
6643 qemu_loadvm(loadvm);
6646 /* XXX: simplify init */
6647 read_passwords();
6648 if (start_emulation) {
6649 vm_start();
6652 main_loop();
6653 quit_timers();
6654 return 0;