ia64/xen-unstable

view tools/ioemu/vl.c @ 11179:a774cbd38187

[qemu] Default monitor/serial ports to /dev/null if -nographic.
qemu-dm runs daemonized and the default for -nographic is to redirect
the monitor and serial ports to stdio which causes qemu-dm to busy
read from stdin. Change the default for -nographic to redirect the
monitor and serial ports to /dev/null.

Based on a patch from: Steven Smith <sos22-xen@srcf.ucam.org>
Signed-off-by: Christian Limpach <Christian.Limpach@xensource.com>
author chris@kneesaa.uk.xensource.com
date Thu Aug 17 11:34:13 2006 +0100 (2006-08-17)
parents bd04004865ba
children 078bfd250677
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 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
128 uint64_t ram_size;
129 int pit_min_timer_count = 0;
130 int nb_nics;
131 NICInfo nd_table[MAX_NICS];
132 QEMUTimer *gui_timer;
133 int vm_running;
134 int rtc_utc = 1;
135 int cirrus_vga_enabled = 1;
136 #ifdef TARGET_SPARC
137 int graphic_width = 1024;
138 int graphic_height = 768;
139 #else
140 int graphic_width = 800;
141 int graphic_height = 600;
142 #endif
143 int graphic_depth = 15;
144 int full_screen = 0;
145 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
146 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
147 #ifdef TARGET_I386
148 int win2k_install_hack = 0;
149 #endif
150 int usb_enabled = 0;
151 static VLANState *first_vlan;
152 int smp_cpus = 1;
153 int vnc_display = -1;
154 #if defined(TARGET_SPARC)
155 #define MAX_CPUS 16
156 #elif defined(TARGET_I386)
157 #define MAX_CPUS 255
158 #else
159 #define MAX_CPUS 1
160 #endif
161 int acpi_enabled = 0;
162 int fd_bootchk = 1;
164 extern int vcpus;
166 int xc_handle;
168 time_t timeoffset = 0;
170 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
171 extern int domid;
173 /***********************************************************/
174 /* x86 ISA bus support */
176 target_phys_addr_t isa_mem_base = 0;
177 PicState2 *isa_pic;
179 uint32_t default_ioport_readb(void *opaque, uint32_t address)
180 {
181 #ifdef DEBUG_UNUSED_IOPORT
182 fprintf(stderr, "inb: port=0x%04x\n", address);
183 #endif
184 return 0xff;
185 }
187 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
188 {
189 #ifdef DEBUG_UNUSED_IOPORT
190 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
191 #endif
192 }
194 /* default is to make two byte accesses */
195 uint32_t default_ioport_readw(void *opaque, uint32_t address)
196 {
197 uint32_t data;
198 data = ioport_read_table[0][address](ioport_opaque[address], address);
199 address = (address + 1) & (MAX_IOPORTS - 1);
200 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
201 return data;
202 }
204 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
205 {
206 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
207 address = (address + 1) & (MAX_IOPORTS - 1);
208 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
209 }
211 uint32_t default_ioport_readl(void *opaque, uint32_t address)
212 {
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "inl: port=0x%04x\n", address);
215 #endif
216 return 0xffffffff;
217 }
219 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
220 {
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
223 #endif
224 }
226 void init_ioports(void)
227 {
228 int i;
230 for(i = 0; i < MAX_IOPORTS; i++) {
231 ioport_read_table[0][i] = default_ioport_readb;
232 ioport_write_table[0][i] = default_ioport_writeb;
233 ioport_read_table[1][i] = default_ioport_readw;
234 ioport_write_table[1][i] = default_ioport_writew;
235 ioport_read_table[2][i] = default_ioport_readl;
236 ioport_write_table[2][i] = default_ioport_writel;
237 }
238 }
240 /* size is the word size in byte */
241 int register_ioport_read(int start, int length, int size,
242 IOPortReadFunc *func, void *opaque)
243 {
244 int i, bsize;
246 if (size == 1) {
247 bsize = 0;
248 } else if (size == 2) {
249 bsize = 1;
250 } else if (size == 4) {
251 bsize = 2;
252 } else {
253 hw_error("register_ioport_read: invalid size");
254 return -1;
255 }
256 for(i = start; i < start + length; i += size) {
257 ioport_read_table[bsize][i] = func;
258 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
259 hw_error("register_ioport_read: invalid opaque");
260 ioport_opaque[i] = opaque;
261 }
262 return 0;
263 }
265 /* size is the word size in byte */
266 int register_ioport_write(int start, int length, int size,
267 IOPortWriteFunc *func, void *opaque)
268 {
269 int i, bsize;
271 if (size == 1) {
272 bsize = 0;
273 } else if (size == 2) {
274 bsize = 1;
275 } else if (size == 4) {
276 bsize = 2;
277 } else {
278 hw_error("register_ioport_write: invalid size");
279 return -1;
280 }
281 for(i = start; i < start + length; i += size) {
282 ioport_write_table[bsize][i] = func;
283 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
284 hw_error("register_ioport_read: invalid opaque");
285 ioport_opaque[i] = opaque;
286 }
287 return 0;
288 }
290 void isa_unassign_ioport(int start, int length)
291 {
292 int i;
294 for(i = start; i < start + length; i++) {
295 ioport_read_table[0][i] = default_ioport_readb;
296 ioport_read_table[1][i] = default_ioport_readw;
297 ioport_read_table[2][i] = default_ioport_readl;
299 ioport_write_table[0][i] = default_ioport_writeb;
300 ioport_write_table[1][i] = default_ioport_writew;
301 ioport_write_table[2][i] = default_ioport_writel;
302 }
303 }
305 /***********************************************************/
307 void pstrcpy(char *buf, int buf_size, const char *str)
308 {
309 int c;
310 char *q = buf;
312 if (buf_size <= 0)
313 return;
315 for(;;) {
316 c = *str++;
317 if (c == 0 || q >= buf + buf_size - 1)
318 break;
319 *q++ = c;
320 }
321 *q = '\0';
322 }
324 /* strcat and truncate. */
325 char *pstrcat(char *buf, int buf_size, const char *s)
326 {
327 int len;
328 len = strlen(buf);
329 if (len < buf_size)
330 pstrcpy(buf + len, buf_size - len, s);
331 return buf;
332 }
334 int strstart(const char *str, const char *val, const char **ptr)
335 {
336 const char *p, *q;
337 p = str;
338 q = val;
339 while (*q != '\0') {
340 if (*p != *q)
341 return 0;
342 p++;
343 q++;
344 }
345 if (ptr)
346 *ptr = p;
347 return 1;
348 }
350 void cpu_outb(CPUState *env, int addr, int val)
351 {
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outb: %04x %02x\n", addr, val);
355 #endif
356 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
361 }
363 void cpu_outw(CPUState *env, int addr, int val)
364 {
365 #ifdef DEBUG_IOPORT
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outw: %04x %04x\n", addr, val);
368 #endif
369 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
370 #ifdef USE_KQEMU
371 if (env)
372 env->last_io_time = cpu_get_time_fast();
373 #endif
374 }
376 void cpu_outl(CPUState *env, int addr, int val)
377 {
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "outl: %04x %08x\n", addr, val);
381 #endif
382 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
387 }
389 int cpu_inb(CPUState *env, int addr)
390 {
391 int val;
392 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inb : %04x %02x\n", addr, val);
396 #endif
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
401 return val;
402 }
404 int cpu_inw(CPUState *env, int addr)
405 {
406 int val;
407 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inw : %04x %04x\n", addr, val);
411 #endif
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
416 return val;
417 }
419 int cpu_inl(CPUState *env, int addr)
420 {
421 int val;
422 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 #endif
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
431 return val;
432 }
434 /***********************************************************/
435 void hw_error(const char *fmt, ...)
436 {
437 va_list ap;
438 #ifndef CONFIG_DM
439 CPUState *env;
440 #endif /* !CONFIG_DM */
442 va_start(ap, fmt);
443 fprintf(stderr, "qemu: hardware error: ");
444 vfprintf(stderr, fmt, ap);
445 fprintf(stderr, "\n");
446 #ifndef CONFIG_DM
447 for(env = first_cpu; env != NULL; env = env->next_cpu) {
448 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
449 #ifdef TARGET_I386
450 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
451 #else
452 cpu_dump_state(env, stderr, fprintf, 0);
453 #endif
454 }
455 #endif /* !CONFIG_DM */
456 va_end(ap);
457 abort();
458 }
460 /***********************************************************/
461 /* keyboard/mouse */
463 static QEMUPutKBDEvent *qemu_put_kbd_event;
464 static void *qemu_put_kbd_event_opaque;
465 static QEMUPutMouseEvent *qemu_put_mouse_event;
466 static void *qemu_put_mouse_event_opaque;
467 static int qemu_put_mouse_event_absolute;
469 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
470 {
471 qemu_put_kbd_event_opaque = opaque;
472 qemu_put_kbd_event = func;
473 }
475 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
476 {
477 qemu_put_mouse_event_opaque = opaque;
478 qemu_put_mouse_event = func;
479 qemu_put_mouse_event_absolute = absolute;
480 }
482 void kbd_put_keycode(int keycode)
483 {
484 if (qemu_put_kbd_event) {
485 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
486 }
487 }
489 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
490 {
491 if (qemu_put_mouse_event) {
492 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
493 dx, dy, dz, buttons_state);
494 }
495 }
497 int kbd_mouse_is_absolute(void)
498 {
499 return qemu_put_mouse_event_absolute;
500 }
502 /* compute with 96 bit intermediate result: (a*b)/c */
503 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
504 {
505 union {
506 uint64_t ll;
507 struct {
508 #ifdef WORDS_BIGENDIAN
509 uint32_t high, low;
510 #else
511 uint32_t low, high;
512 #endif
513 } l;
514 } u, res;
515 uint64_t rl, rh;
517 u.ll = a;
518 rl = (uint64_t)u.l.low * (uint64_t)b;
519 rh = (uint64_t)u.l.high * (uint64_t)b;
520 rh += (rl >> 32);
521 res.l.high = rh / c;
522 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
523 return res.ll;
524 }
526 /***********************************************************/
527 /* real time host monotonic timer */
529 #define QEMU_TIMER_BASE 1000000000LL
531 #ifdef WIN32
533 static int64_t clock_freq;
535 static void init_get_clock(void)
536 {
537 LARGE_INTEGER freq;
538 int ret;
539 ret = QueryPerformanceFrequency(&freq);
540 if (ret == 0) {
541 fprintf(stderr, "Could not calibrate ticks\n");
542 exit(1);
543 }
544 clock_freq = freq.QuadPart;
545 }
547 static int64_t get_clock(void)
548 {
549 LARGE_INTEGER ti;
550 QueryPerformanceCounter(&ti);
551 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
552 }
554 #else
556 static int use_rt_clock;
558 static void init_get_clock(void)
559 {
560 use_rt_clock = 0;
561 #if defined(__linux__)
562 {
563 struct timespec ts;
564 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
565 use_rt_clock = 1;
566 }
567 }
568 #endif
569 }
571 static int64_t get_clock(void)
572 {
573 #if defined(__linux__)
574 if (use_rt_clock) {
575 struct timespec ts;
576 clock_gettime(CLOCK_MONOTONIC, &ts);
577 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
578 } else
579 #endif
580 {
581 /* XXX: using gettimeofday leads to problems if the date
582 changes, so it should be avoided. */
583 struct timeval tv;
584 gettimeofday(&tv, NULL);
585 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
586 }
587 }
589 #endif
591 /***********************************************************/
592 /* guest cycle counter */
594 static int64_t cpu_ticks_prev;
595 static int64_t cpu_ticks_offset;
596 static int64_t cpu_clock_offset;
597 static int cpu_ticks_enabled;
599 /* return the host CPU cycle counter and handle stop/restart */
600 int64_t cpu_get_ticks(void)
601 {
602 if (!cpu_ticks_enabled) {
603 return cpu_ticks_offset;
604 } else {
605 int64_t ticks;
606 ticks = cpu_get_real_ticks();
607 if (cpu_ticks_prev > ticks) {
608 /* Note: non increasing ticks may happen if the host uses
609 software suspend */
610 cpu_ticks_offset += cpu_ticks_prev - ticks;
611 }
612 cpu_ticks_prev = ticks;
613 return ticks + cpu_ticks_offset;
614 }
615 }
617 /* return the host CPU monotonic timer and handle stop/restart */
618 static int64_t cpu_get_clock(void)
619 {
620 int64_t ti;
621 if (!cpu_ticks_enabled) {
622 return cpu_clock_offset;
623 } else {
624 ti = get_clock();
625 return ti + cpu_clock_offset;
626 }
627 }
629 /* enable cpu_get_ticks() */
630 void cpu_enable_ticks(void)
631 {
632 if (!cpu_ticks_enabled) {
633 cpu_ticks_offset -= cpu_get_real_ticks();
634 cpu_clock_offset -= get_clock();
635 cpu_ticks_enabled = 1;
636 }
637 }
639 /* disable cpu_get_ticks() : the clock is stopped. You must not call
640 cpu_get_ticks() after that. */
641 void cpu_disable_ticks(void)
642 {
643 if (cpu_ticks_enabled) {
644 cpu_ticks_offset = cpu_get_ticks();
645 cpu_clock_offset = cpu_get_clock();
646 cpu_ticks_enabled = 0;
647 }
648 }
650 /***********************************************************/
651 /* timers */
653 #define QEMU_TIMER_REALTIME 0
654 #define QEMU_TIMER_VIRTUAL 1
656 struct QEMUClock {
657 int type;
658 /* XXX: add frequency */
659 };
661 struct QEMUTimer {
662 QEMUClock *clock;
663 int64_t expire_time;
664 QEMUTimerCB *cb;
665 void *opaque;
666 struct QEMUTimer *next;
667 };
669 QEMUClock *rt_clock;
670 QEMUClock *vm_clock;
672 static QEMUTimer *active_timers[2];
673 #ifdef _WIN32
674 static MMRESULT timerID;
675 static HANDLE host_alarm = NULL;
676 static unsigned int period = 1;
677 #else
678 /* frequency of the times() clock tick */
679 static int timer_freq;
680 #endif
682 QEMUClock *qemu_new_clock(int type)
683 {
684 QEMUClock *clock;
685 clock = qemu_mallocz(sizeof(QEMUClock));
686 if (!clock)
687 return NULL;
688 clock->type = type;
689 return clock;
690 }
692 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
693 {
694 QEMUTimer *ts;
696 ts = qemu_mallocz(sizeof(QEMUTimer));
697 ts->clock = clock;
698 ts->cb = cb;
699 ts->opaque = opaque;
700 return ts;
701 }
703 void qemu_free_timer(QEMUTimer *ts)
704 {
705 qemu_free(ts);
706 }
708 /* stop a timer, but do not dealloc it */
709 void qemu_del_timer(QEMUTimer *ts)
710 {
711 QEMUTimer **pt, *t;
713 /* NOTE: this code must be signal safe because
714 qemu_timer_expired() can be called from a signal. */
715 pt = &active_timers[ts->clock->type];
716 for(;;) {
717 t = *pt;
718 if (!t)
719 break;
720 if (t == ts) {
721 *pt = t->next;
722 break;
723 }
724 pt = &t->next;
725 }
726 }
728 /* modify the current timer so that it will be fired when current_time
729 >= expire_time. The corresponding callback will be called. */
730 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
731 {
732 QEMUTimer **pt, *t;
734 qemu_del_timer(ts);
736 /* add the timer in the sorted list */
737 /* NOTE: this code must be signal safe because
738 qemu_timer_expired() can be called from a signal. */
739 pt = &active_timers[ts->clock->type];
740 for(;;) {
741 t = *pt;
742 if (!t)
743 break;
744 if (t->expire_time > expire_time)
745 break;
746 pt = &t->next;
747 }
748 ts->expire_time = expire_time;
749 ts->next = *pt;
750 *pt = ts;
751 }
753 int qemu_timer_pending(QEMUTimer *ts)
754 {
755 QEMUTimer *t;
756 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
757 if (t == ts)
758 return 1;
759 }
760 return 0;
761 }
763 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
764 {
765 if (!timer_head)
766 return 0;
767 return (timer_head->expire_time <= current_time);
768 }
770 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
771 {
772 QEMUTimer *ts;
774 for(;;) {
775 ts = *ptimer_head;
776 if (!ts || ts->expire_time > current_time)
777 break;
778 /* remove timer from the list before calling the callback */
779 *ptimer_head = ts->next;
780 ts->next = NULL;
782 /* run the callback (the timer list can be modified) */
783 ts->cb(ts->opaque);
784 }
785 }
787 int64_t qemu_get_clock(QEMUClock *clock)
788 {
789 switch(clock->type) {
790 case QEMU_TIMER_REALTIME:
791 return get_clock() / 1000000;
792 default:
793 case QEMU_TIMER_VIRTUAL:
794 return cpu_get_clock();
795 }
796 }
798 static void init_timers(void)
799 {
800 init_get_clock();
801 ticks_per_sec = QEMU_TIMER_BASE;
802 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
803 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
804 }
806 /* save a timer */
807 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
808 {
809 uint64_t expire_time;
811 if (qemu_timer_pending(ts)) {
812 expire_time = ts->expire_time;
813 } else {
814 expire_time = -1;
815 }
816 qemu_put_be64(f, expire_time);
817 }
819 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
820 {
821 uint64_t expire_time;
823 expire_time = qemu_get_be64(f);
824 if (expire_time != -1) {
825 qemu_mod_timer(ts, expire_time);
826 } else {
827 qemu_del_timer(ts);
828 }
829 }
831 #ifdef CONFIG_DM
832 static void timer_save(QEMUFile *f, void *opaque)
833 {
834 }
836 static int timer_load(QEMUFile *f, void *opaque, int version_id)
837 {
838 return 0;
839 }
840 #else /* !CONFIG_DM */
841 static void timer_save(QEMUFile *f, void *opaque)
842 {
843 if (cpu_ticks_enabled) {
844 hw_error("cannot save state if virtual timers are running");
845 }
846 qemu_put_be64s(f, &cpu_ticks_offset);
847 qemu_put_be64s(f, &ticks_per_sec);
848 }
850 static int timer_load(QEMUFile *f, void *opaque, int version_id)
851 {
852 if (version_id != 1)
853 return -EINVAL;
854 if (cpu_ticks_enabled) {
855 return -EINVAL;
856 }
857 qemu_get_be64s(f, &cpu_ticks_offset);
858 qemu_get_be64s(f, &ticks_per_sec);
859 return 0;
860 }
862 #ifdef _WIN32
863 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
864 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
865 #else
866 static void host_alarm_handler(int host_signum)
867 #endif
868 {
869 #if 0
870 #define DISP_FREQ 1000
871 {
872 static int64_t delta_min = INT64_MAX;
873 static int64_t delta_max, delta_cum, last_clock, delta, ti;
874 static int count;
875 ti = qemu_get_clock(vm_clock);
876 if (last_clock != 0) {
877 delta = ti - last_clock;
878 if (delta < delta_min)
879 delta_min = delta;
880 if (delta > delta_max)
881 delta_max = delta;
882 delta_cum += delta;
883 if (++count == DISP_FREQ) {
884 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
885 muldiv64(delta_min, 1000000, ticks_per_sec),
886 muldiv64(delta_max, 1000000, ticks_per_sec),
887 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
888 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
889 count = 0;
890 delta_min = INT64_MAX;
891 delta_max = 0;
892 delta_cum = 0;
893 }
894 }
895 last_clock = ti;
896 }
897 #endif
898 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
899 qemu_get_clock(vm_clock)) ||
900 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
901 qemu_get_clock(rt_clock))) {
902 #ifdef _WIN32
903 SetEvent(host_alarm);
904 #endif
905 CPUState *env = cpu_single_env;
906 if (env) {
907 /* stop the currently executing cpu because a timer occured */
908 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
909 #ifdef USE_KQEMU
910 if (env->kqemu_enabled) {
911 kqemu_cpu_interrupt(env);
912 }
913 #endif
914 }
915 }
916 }
918 #ifndef _WIN32
920 #if defined(__linux__)
922 #define RTC_FREQ 1024
924 static int rtc_fd;
926 static int start_rtc_timer(void)
927 {
928 rtc_fd = open("/dev/rtc", O_RDONLY);
929 if (rtc_fd < 0)
930 return -1;
931 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
932 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
933 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
934 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
935 goto fail;
936 }
937 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
938 fail:
939 close(rtc_fd);
940 return -1;
941 }
942 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
943 return 0;
944 }
946 #else
948 static int start_rtc_timer(void)
949 {
950 return -1;
951 }
953 #endif /* !defined(__linux__) */
955 #endif /* !defined(_WIN32) */
957 #endif /* !CONFIG_DM */
959 static void init_timer_alarm(void)
960 {
961 #ifdef _WIN32
962 {
963 int count=0;
964 TIMECAPS tc;
966 ZeroMemory(&tc, sizeof(TIMECAPS));
967 timeGetDevCaps(&tc, sizeof(TIMECAPS));
968 if (period < tc.wPeriodMin)
969 period = tc.wPeriodMin;
970 timeBeginPeriod(period);
971 timerID = timeSetEvent(1, // interval (ms)
972 period, // resolution
973 host_alarm_handler, // function
974 (DWORD)&count, // user parameter
975 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
976 if( !timerID ) {
977 perror("failed timer alarm");
978 exit(1);
979 }
980 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
981 if (!host_alarm) {
982 perror("failed CreateEvent");
983 exit(1);
984 }
985 qemu_add_wait_object(host_alarm, NULL, NULL);
986 }
987 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
988 #else
989 {
990 #ifndef CONFIG_DM
991 struct sigaction act;
992 struct itimerval itv;
993 #endif
995 /* get times() syscall frequency */
996 timer_freq = sysconf(_SC_CLK_TCK);
998 #ifndef CONFIG_DM
999 /* timer signal */
1000 sigfillset(&act.sa_mask);
1001 act.sa_flags = 0;
1002 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1003 act.sa_flags |= SA_ONSTACK;
1004 #endif
1005 act.sa_handler = host_alarm_handler;
1006 sigaction(SIGALRM, &act, NULL);
1008 itv.it_interval.tv_sec = 0;
1009 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1010 itv.it_value.tv_sec = 0;
1011 itv.it_value.tv_usec = 10 * 1000;
1012 setitimer(ITIMER_REAL, &itv, NULL);
1013 /* we probe the tick duration of the kernel to inform the user if
1014 the emulated kernel requested a too high timer frequency */
1015 getitimer(ITIMER_REAL, &itv);
1017 #if defined(__linux__)
1018 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1019 have timers with 1 ms resolution. The correct solution will
1020 be to use the POSIX real time timers available in recent
1021 2.6 kernels */
1022 if (itv.it_interval.tv_usec > 1000 || 1) {
1023 /* try to use /dev/rtc to have a faster timer */
1024 if (start_rtc_timer() < 0)
1025 goto use_itimer;
1026 /* disable itimer */
1027 itv.it_interval.tv_sec = 0;
1028 itv.it_interval.tv_usec = 0;
1029 itv.it_value.tv_sec = 0;
1030 itv.it_value.tv_usec = 0;
1031 setitimer(ITIMER_REAL, &itv, NULL);
1033 /* use the RTC */
1034 sigaction(SIGIO, &act, NULL);
1035 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1036 fcntl(rtc_fd, F_SETOWN, getpid());
1037 } else
1038 #endif /* defined(__linux__) */
1040 use_itimer:
1041 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1042 PIT_FREQ) / 1000000;
1044 #endif /* CONFIG_DM */
1046 #endif
1049 void quit_timers(void)
1051 #ifdef _WIN32
1052 timeKillEvent(timerID);
1053 timeEndPeriod(period);
1054 if (host_alarm) {
1055 CloseHandle(host_alarm);
1056 host_alarm = NULL;
1058 #endif
1061 /***********************************************************/
1062 /* character device */
1064 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1066 return s->chr_write(s, buf, len);
1069 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1071 if (!s->chr_ioctl)
1072 return -ENOTSUP;
1073 return s->chr_ioctl(s, cmd, arg);
1076 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1078 char buf[4096];
1079 va_list ap;
1080 va_start(ap, fmt);
1081 vsnprintf(buf, sizeof(buf), fmt, ap);
1082 qemu_chr_write(s, buf, strlen(buf));
1083 va_end(ap);
1086 void qemu_chr_send_event(CharDriverState *s, int event)
1088 if (s->chr_send_event)
1089 s->chr_send_event(s, event);
1092 void qemu_chr_add_read_handler(CharDriverState *s,
1093 IOCanRWHandler *fd_can_read,
1094 IOReadHandler *fd_read, void *opaque)
1096 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1099 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1101 s->chr_event = chr_event;
1104 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1106 return len;
1109 static void null_chr_add_read_handler(CharDriverState *chr,
1110 IOCanRWHandler *fd_can_read,
1111 IOReadHandler *fd_read, void *opaque)
1115 CharDriverState *qemu_chr_open_null(void)
1117 CharDriverState *chr;
1119 chr = qemu_mallocz(sizeof(CharDriverState));
1120 if (!chr)
1121 return NULL;
1122 chr->chr_write = null_chr_write;
1123 chr->chr_add_read_handler = null_chr_add_read_handler;
1124 return chr;
1127 #ifdef _WIN32
1129 static void socket_cleanup(void)
1131 WSACleanup();
1134 static int socket_init(void)
1136 WSADATA Data;
1137 int ret, err;
1139 ret = WSAStartup(MAKEWORD(2,2), &Data);
1140 if (ret != 0) {
1141 err = WSAGetLastError();
1142 fprintf(stderr, "WSAStartup: %d\n", err);
1143 return -1;
1145 atexit(socket_cleanup);
1146 return 0;
1149 static int send_all(int fd, const uint8_t *buf, int len1)
1151 int ret, len;
1153 len = len1;
1154 while (len > 0) {
1155 ret = send(fd, buf, len, 0);
1156 if (ret < 0) {
1157 int errno;
1158 errno = WSAGetLastError();
1159 if (errno != WSAEWOULDBLOCK) {
1160 return -1;
1162 } else if (ret == 0) {
1163 break;
1164 } else {
1165 buf += ret;
1166 len -= ret;
1169 return len1 - len;
1172 void socket_set_nonblock(int fd)
1174 unsigned long opt = 1;
1175 ioctlsocket(fd, FIONBIO, &opt);
1178 #else
1180 static int unix_write(int fd, const uint8_t *buf, int len1)
1182 int ret, sel_ret, len;
1183 int max_fd;
1184 fd_set writefds;
1185 struct timeval timeout;
1187 max_fd = fd;
1189 len = len1;
1190 while (len > 0) {
1191 FD_ZERO(&writefds);
1192 FD_SET(fd, &writefds);
1193 timeout.tv_sec = 0;
1194 timeout.tv_usec = 0;
1195 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1196 if (sel_ret <= 0) {
1197 /* Timeout or select error */
1198 return -1;
1199 } else {
1200 ret = write(fd, buf, len);
1201 if (ret < 0) {
1202 if (errno != EINTR && errno != EAGAIN)
1203 return -1;
1204 } else if (ret == 0) {
1205 break;
1206 } else {
1207 buf += ret;
1208 len -= ret;
1212 return len1 - len;
1215 static inline int send_all(int fd, const uint8_t *buf, int len1)
1217 return unix_write(fd, buf, len1);
1220 void socket_set_nonblock(int fd)
1222 fcntl(fd, F_SETFL, O_NONBLOCK);
1224 #endif /* !_WIN32 */
1226 #ifndef _WIN32
1228 typedef struct {
1229 int fd_in, fd_out;
1230 IOCanRWHandler *fd_can_read;
1231 IOReadHandler *fd_read;
1232 void *fd_opaque;
1233 int max_size;
1234 } FDCharDriver;
1236 #define STDIO_MAX_CLIENTS 2
1238 static int stdio_nb_clients;
1239 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1241 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1243 FDCharDriver *s = chr->opaque;
1244 return unix_write(s->fd_out, buf, len);
1247 static int fd_chr_read_poll(void *opaque)
1249 CharDriverState *chr = opaque;
1250 FDCharDriver *s = chr->opaque;
1252 s->max_size = s->fd_can_read(s->fd_opaque);
1253 return s->max_size;
1256 static void fd_chr_read(void *opaque)
1258 CharDriverState *chr = opaque;
1259 FDCharDriver *s = chr->opaque;
1260 int size, len;
1261 uint8_t buf[1024];
1263 len = sizeof(buf);
1264 if (len > s->max_size)
1265 len = s->max_size;
1266 if (len == 0)
1267 return;
1268 size = read(s->fd_in, buf, len);
1269 if (size > 0) {
1270 s->fd_read(s->fd_opaque, buf, size);
1274 static void fd_chr_add_read_handler(CharDriverState *chr,
1275 IOCanRWHandler *fd_can_read,
1276 IOReadHandler *fd_read, void *opaque)
1278 FDCharDriver *s = chr->opaque;
1280 if (s->fd_in >= 0) {
1281 s->fd_can_read = fd_can_read;
1282 s->fd_read = fd_read;
1283 s->fd_opaque = opaque;
1284 if (nographic && s->fd_in == 0) {
1285 } else {
1286 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1287 fd_chr_read, NULL, chr);
1292 /* open a character device to a unix fd */
1293 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1295 CharDriverState *chr;
1296 FDCharDriver *s;
1298 chr = qemu_mallocz(sizeof(CharDriverState));
1299 if (!chr)
1300 return NULL;
1301 s = qemu_mallocz(sizeof(FDCharDriver));
1302 if (!s) {
1303 free(chr);
1304 return NULL;
1306 s->fd_in = fd_in;
1307 s->fd_out = fd_out;
1308 chr->opaque = s;
1309 chr->chr_write = fd_chr_write;
1310 chr->chr_add_read_handler = fd_chr_add_read_handler;
1311 return chr;
1314 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1316 int fd_out;
1318 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1319 if (fd_out < 0)
1320 return NULL;
1321 return qemu_chr_open_fd(-1, fd_out);
1324 CharDriverState *qemu_chr_open_pipe(const char *filename)
1326 int fd;
1328 fd = open(filename, O_RDWR | O_BINARY);
1329 if (fd < 0)
1330 return NULL;
1331 return qemu_chr_open_fd(fd, fd);
1335 /* for STDIO, we handle the case where several clients use it
1336 (nographic mode) */
1338 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1340 #define TERM_FIFO_MAX_SIZE 1
1342 static int term_got_escape, client_index;
1343 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1344 static int term_fifo_size;
1345 static int term_timestamps;
1346 static int64_t term_timestamps_start;
1348 void term_print_help(void)
1350 printf("\n"
1351 "C-a h print this help\n"
1352 "C-a x exit emulator\n"
1353 "C-a s save disk data back to file (if -snapshot)\n"
1354 "C-a b send break (magic sysrq)\n"
1355 "C-a t toggle console timestamps\n"
1356 "C-a c switch between console and monitor\n"
1357 "C-a C-a send C-a\n"
1358 );
1361 /* called when a char is received */
1362 static void stdio_received_byte(int ch)
1364 if (term_got_escape) {
1365 term_got_escape = 0;
1366 switch(ch) {
1367 case 'h':
1368 term_print_help();
1369 break;
1370 case 'x':
1371 exit(0);
1372 break;
1373 case 's':
1375 int i;
1376 for (i = 0; i < MAX_DISKS; i++) {
1377 if (bs_table[i])
1378 bdrv_commit(bs_table[i]);
1381 break;
1382 case 'b':
1383 if (client_index < stdio_nb_clients) {
1384 CharDriverState *chr;
1385 FDCharDriver *s;
1387 chr = stdio_clients[client_index];
1388 s = chr->opaque;
1389 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1391 break;
1392 case 'c':
1393 client_index++;
1394 if (client_index >= stdio_nb_clients)
1395 client_index = 0;
1396 if (client_index == 0) {
1397 /* send a new line in the monitor to get the prompt */
1398 ch = '\r';
1399 goto send_char;
1401 break;
1402 case 't':
1403 term_timestamps = !term_timestamps;
1404 term_timestamps_start = -1;
1405 break;
1406 case TERM_ESCAPE:
1407 goto send_char;
1409 } else if (ch == TERM_ESCAPE) {
1410 term_got_escape = 1;
1411 } else {
1412 send_char:
1413 if (client_index < stdio_nb_clients) {
1414 uint8_t buf[1];
1415 CharDriverState *chr;
1416 FDCharDriver *s;
1418 chr = stdio_clients[client_index];
1419 s = chr->opaque;
1420 if (s->fd_can_read(s->fd_opaque) > 0) {
1421 buf[0] = ch;
1422 s->fd_read(s->fd_opaque, buf, 1);
1423 } else if (term_fifo_size == 0) {
1424 term_fifo[term_fifo_size++] = ch;
1430 static int stdio_read_poll(void *opaque)
1432 CharDriverState *chr;
1433 FDCharDriver *s;
1435 if (client_index < stdio_nb_clients) {
1436 chr = stdio_clients[client_index];
1437 s = chr->opaque;
1438 /* try to flush the queue if needed */
1439 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1440 s->fd_read(s->fd_opaque, term_fifo, 1);
1441 term_fifo_size = 0;
1443 /* see if we can absorb more chars */
1444 if (term_fifo_size == 0)
1445 return 1;
1446 else
1447 return 0;
1448 } else {
1449 return 1;
1453 static void stdio_read(void *opaque)
1455 int size;
1456 uint8_t buf[1];
1458 size = read(0, buf, 1);
1459 if (size > 0)
1460 stdio_received_byte(buf[0]);
1463 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1465 FDCharDriver *s = chr->opaque;
1466 if (!term_timestamps) {
1467 return unix_write(s->fd_out, buf, len);
1468 } else {
1469 int i;
1470 char buf1[64];
1472 for(i = 0; i < len; i++) {
1473 unix_write(s->fd_out, buf + i, 1);
1474 if (buf[i] == '\n') {
1475 int64_t ti;
1476 int secs;
1478 ti = get_clock();
1479 if (term_timestamps_start == -1)
1480 term_timestamps_start = ti;
1481 ti -= term_timestamps_start;
1482 secs = ti / 1000000000;
1483 snprintf(buf1, sizeof(buf1),
1484 "[%02d:%02d:%02d.%03d] ",
1485 secs / 3600,
1486 (secs / 60) % 60,
1487 secs % 60,
1488 (int)((ti / 1000000) % 1000));
1489 unix_write(s->fd_out, buf1, strlen(buf1));
1492 return len;
1496 /* init terminal so that we can grab keys */
1497 static struct termios oldtty;
1498 static int old_fd0_flags;
1500 static void term_exit(void)
1502 tcsetattr (0, TCSANOW, &oldtty);
1503 fcntl(0, F_SETFL, old_fd0_flags);
1506 static void term_init(void)
1508 struct termios tty;
1510 tcgetattr (0, &tty);
1511 oldtty = tty;
1512 old_fd0_flags = fcntl(0, F_GETFL);
1514 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1515 |INLCR|IGNCR|ICRNL|IXON);
1516 tty.c_oflag |= OPOST;
1517 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1518 /* if graphical mode, we allow Ctrl-C handling */
1519 if (nographic)
1520 tty.c_lflag &= ~ISIG;
1521 tty.c_cflag &= ~(CSIZE|PARENB);
1522 tty.c_cflag |= CS8;
1523 tty.c_cc[VMIN] = 1;
1524 tty.c_cc[VTIME] = 0;
1526 tcsetattr (0, TCSANOW, &tty);
1528 atexit(term_exit);
1530 fcntl(0, F_SETFL, O_NONBLOCK);
1533 CharDriverState *qemu_chr_open_stdio(void)
1535 CharDriverState *chr;
1537 if (nographic) {
1538 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1539 return NULL;
1540 chr = qemu_chr_open_fd(0, 1);
1541 chr->chr_write = stdio_write;
1542 if (stdio_nb_clients == 0)
1543 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1544 client_index = stdio_nb_clients;
1545 } else {
1546 if (stdio_nb_clients != 0)
1547 return NULL;
1548 chr = qemu_chr_open_fd(0, 1);
1550 stdio_clients[stdio_nb_clients++] = chr;
1551 if (stdio_nb_clients == 1) {
1552 /* set the terminal in raw mode */
1553 term_init();
1555 return chr;
1558 int store_console_dev(int domid, char *pts)
1560 int xc_handle;
1561 struct xs_handle *xs;
1562 char *path;
1564 xs = xs_daemon_open();
1565 if (xs == NULL) {
1566 fprintf(logfile, "Could not contact XenStore\n");
1567 return -1;
1570 xc_handle = xc_interface_open();
1571 if (xc_handle == -1) {
1572 fprintf(logfile, "xc_interface_open() error\n");
1573 return -1;
1576 path = xs_get_domain_path(xs, domid);
1577 if (path == NULL) {
1578 fprintf(logfile, "xs_get_domain_path() error\n");
1579 return -1;
1581 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1582 if (path == NULL) {
1583 fprintf(logfile, "realloc error\n");
1584 return -1;
1586 strcat(path, "/console/tty");
1587 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1588 fprintf(logfile, "xs_write for console fail");
1589 return -1;
1592 free(path);
1593 xs_daemon_close(xs);
1594 close(xc_handle);
1596 return 0;
1599 #if defined(__linux__)
1600 CharDriverState *qemu_chr_open_pty(void)
1602 struct termios tty;
1603 int master_fd, slave_fd;
1605 /* Not satisfying */
1606 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1607 return NULL;
1610 /* Set raw attributes on the pty. */
1611 cfmakeraw(&tty);
1612 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1614 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1615 store_console_dev(domid, ptsname(master_fd));
1617 return qemu_chr_open_fd(master_fd, master_fd);
1620 static void tty_serial_init(int fd, int speed,
1621 int parity, int data_bits, int stop_bits)
1623 struct termios tty;
1624 speed_t spd;
1626 #if 0
1627 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1628 speed, parity, data_bits, stop_bits);
1629 #endif
1630 tcgetattr (fd, &tty);
1632 switch(speed) {
1633 case 50:
1634 spd = B50;
1635 break;
1636 case 75:
1637 spd = B75;
1638 break;
1639 case 300:
1640 spd = B300;
1641 break;
1642 case 600:
1643 spd = B600;
1644 break;
1645 case 1200:
1646 spd = B1200;
1647 break;
1648 case 2400:
1649 spd = B2400;
1650 break;
1651 case 4800:
1652 spd = B4800;
1653 break;
1654 case 9600:
1655 spd = B9600;
1656 break;
1657 case 19200:
1658 spd = B19200;
1659 break;
1660 case 38400:
1661 spd = B38400;
1662 break;
1663 case 57600:
1664 spd = B57600;
1665 break;
1666 default:
1667 case 115200:
1668 spd = B115200;
1669 break;
1672 cfsetispeed(&tty, spd);
1673 cfsetospeed(&tty, spd);
1675 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1676 |INLCR|IGNCR|ICRNL|IXON);
1677 tty.c_oflag |= OPOST;
1678 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1679 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1680 switch(data_bits) {
1681 default:
1682 case 8:
1683 tty.c_cflag |= CS8;
1684 break;
1685 case 7:
1686 tty.c_cflag |= CS7;
1687 break;
1688 case 6:
1689 tty.c_cflag |= CS6;
1690 break;
1691 case 5:
1692 tty.c_cflag |= CS5;
1693 break;
1695 switch(parity) {
1696 default:
1697 case 'N':
1698 break;
1699 case 'E':
1700 tty.c_cflag |= PARENB;
1701 break;
1702 case 'O':
1703 tty.c_cflag |= PARENB | PARODD;
1704 break;
1707 tcsetattr (fd, TCSANOW, &tty);
1710 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1712 FDCharDriver *s = chr->opaque;
1714 switch(cmd) {
1715 case CHR_IOCTL_SERIAL_SET_PARAMS:
1717 QEMUSerialSetParams *ssp = arg;
1718 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1719 ssp->data_bits, ssp->stop_bits);
1721 break;
1722 case CHR_IOCTL_SERIAL_SET_BREAK:
1724 int enable = *(int *)arg;
1725 if (enable)
1726 tcsendbreak(s->fd_in, 1);
1728 break;
1729 default:
1730 return -ENOTSUP;
1732 return 0;
1735 CharDriverState *qemu_chr_open_tty(const char *filename)
1737 CharDriverState *chr;
1738 int fd;
1740 fd = open(filename, O_RDWR | O_NONBLOCK);
1741 if (fd < 0)
1742 return NULL;
1743 fcntl(fd, F_SETFL, O_NONBLOCK);
1744 tty_serial_init(fd, 115200, 'N', 8, 1);
1745 chr = qemu_chr_open_fd(fd, fd);
1746 if (!chr)
1747 return NULL;
1748 chr->chr_ioctl = tty_serial_ioctl;
1749 return chr;
1752 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1754 int fd = (int)chr->opaque;
1755 uint8_t b;
1757 switch(cmd) {
1758 case CHR_IOCTL_PP_READ_DATA:
1759 if (ioctl(fd, PPRDATA, &b) < 0)
1760 return -ENOTSUP;
1761 *(uint8_t *)arg = b;
1762 break;
1763 case CHR_IOCTL_PP_WRITE_DATA:
1764 b = *(uint8_t *)arg;
1765 if (ioctl(fd, PPWDATA, &b) < 0)
1766 return -ENOTSUP;
1767 break;
1768 case CHR_IOCTL_PP_READ_CONTROL:
1769 if (ioctl(fd, PPRCONTROL, &b) < 0)
1770 return -ENOTSUP;
1771 *(uint8_t *)arg = b;
1772 break;
1773 case CHR_IOCTL_PP_WRITE_CONTROL:
1774 b = *(uint8_t *)arg;
1775 if (ioctl(fd, PPWCONTROL, &b) < 0)
1776 return -ENOTSUP;
1777 break;
1778 case CHR_IOCTL_PP_READ_STATUS:
1779 if (ioctl(fd, PPRSTATUS, &b) < 0)
1780 return -ENOTSUP;
1781 *(uint8_t *)arg = b;
1782 break;
1783 default:
1784 return -ENOTSUP;
1786 return 0;
1789 CharDriverState *qemu_chr_open_pp(const char *filename)
1791 CharDriverState *chr;
1792 int fd;
1794 fd = open(filename, O_RDWR);
1795 if (fd < 0)
1796 return NULL;
1798 if (ioctl(fd, PPCLAIM) < 0) {
1799 close(fd);
1800 return NULL;
1803 chr = qemu_mallocz(sizeof(CharDriverState));
1804 if (!chr) {
1805 close(fd);
1806 return NULL;
1808 chr->opaque = (void *)fd;
1809 chr->chr_write = null_chr_write;
1810 chr->chr_add_read_handler = null_chr_add_read_handler;
1811 chr->chr_ioctl = pp_ioctl;
1812 return chr;
1815 #else
1816 CharDriverState *qemu_chr_open_pty(void)
1818 return NULL;
1820 #endif
1822 #endif /* !defined(_WIN32) */
1824 #ifdef _WIN32
1825 typedef struct {
1826 IOCanRWHandler *fd_can_read;
1827 IOReadHandler *fd_read;
1828 void *win_opaque;
1829 int max_size;
1830 HANDLE hcom, hrecv, hsend;
1831 OVERLAPPED orecv, osend;
1832 BOOL fpipe;
1833 DWORD len;
1834 } WinCharState;
1836 #define NSENDBUF 2048
1837 #define NRECVBUF 2048
1838 #define MAXCONNECT 1
1839 #define NTIMEOUT 5000
1841 static int win_chr_poll(void *opaque);
1842 static int win_chr_pipe_poll(void *opaque);
1844 static void win_chr_close2(WinCharState *s)
1846 if (s->hsend) {
1847 CloseHandle(s->hsend);
1848 s->hsend = NULL;
1850 if (s->hrecv) {
1851 CloseHandle(s->hrecv);
1852 s->hrecv = NULL;
1854 if (s->hcom) {
1855 CloseHandle(s->hcom);
1856 s->hcom = NULL;
1858 if (s->fpipe)
1859 qemu_del_polling_cb(win_chr_pipe_poll, s);
1860 else
1861 qemu_del_polling_cb(win_chr_poll, s);
1864 static void win_chr_close(CharDriverState *chr)
1866 WinCharState *s = chr->opaque;
1867 win_chr_close2(s);
1870 static int win_chr_init(WinCharState *s, const char *filename)
1872 COMMCONFIG comcfg;
1873 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1874 COMSTAT comstat;
1875 DWORD size;
1876 DWORD err;
1878 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1879 if (!s->hsend) {
1880 fprintf(stderr, "Failed CreateEvent\n");
1881 goto fail;
1883 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1884 if (!s->hrecv) {
1885 fprintf(stderr, "Failed CreateEvent\n");
1886 goto fail;
1889 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1890 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1891 if (s->hcom == INVALID_HANDLE_VALUE) {
1892 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1893 s->hcom = NULL;
1894 goto fail;
1897 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1898 fprintf(stderr, "Failed SetupComm\n");
1899 goto fail;
1902 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1903 size = sizeof(COMMCONFIG);
1904 GetDefaultCommConfig(filename, &comcfg, &size);
1905 comcfg.dcb.DCBlength = sizeof(DCB);
1906 CommConfigDialog(filename, NULL, &comcfg);
1908 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1909 fprintf(stderr, "Failed SetCommState\n");
1910 goto fail;
1913 if (!SetCommMask(s->hcom, EV_ERR)) {
1914 fprintf(stderr, "Failed SetCommMask\n");
1915 goto fail;
1918 cto.ReadIntervalTimeout = MAXDWORD;
1919 if (!SetCommTimeouts(s->hcom, &cto)) {
1920 fprintf(stderr, "Failed SetCommTimeouts\n");
1921 goto fail;
1924 if (!ClearCommError(s->hcom, &err, &comstat)) {
1925 fprintf(stderr, "Failed ClearCommError\n");
1926 goto fail;
1928 qemu_add_polling_cb(win_chr_poll, s);
1929 return 0;
1931 fail:
1932 win_chr_close2(s);
1933 return -1;
1936 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1938 WinCharState *s = chr->opaque;
1939 DWORD len, ret, size, err;
1941 len = len1;
1942 ZeroMemory(&s->osend, sizeof(s->osend));
1943 s->osend.hEvent = s->hsend;
1944 while (len > 0) {
1945 if (s->hsend)
1946 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1947 else
1948 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1949 if (!ret) {
1950 err = GetLastError();
1951 if (err == ERROR_IO_PENDING) {
1952 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1953 if (ret) {
1954 buf += size;
1955 len -= size;
1956 } else {
1957 break;
1959 } else {
1960 break;
1962 } else {
1963 buf += size;
1964 len -= size;
1967 return len1 - len;
1970 static int win_chr_read_poll(WinCharState *s)
1972 s->max_size = s->fd_can_read(s->win_opaque);
1973 return s->max_size;
1976 static void win_chr_readfile(WinCharState *s)
1978 int ret, err;
1979 uint8_t buf[1024];
1980 DWORD size;
1982 ZeroMemory(&s->orecv, sizeof(s->orecv));
1983 s->orecv.hEvent = s->hrecv;
1984 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1985 if (!ret) {
1986 err = GetLastError();
1987 if (err == ERROR_IO_PENDING) {
1988 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1992 if (size > 0) {
1993 s->fd_read(s->win_opaque, buf, size);
1997 static void win_chr_read(WinCharState *s)
1999 if (s->len > s->max_size)
2000 s->len = s->max_size;
2001 if (s->len == 0)
2002 return;
2004 win_chr_readfile(s);
2007 static int win_chr_poll(void *opaque)
2009 WinCharState *s = opaque;
2010 COMSTAT status;
2011 DWORD comerr;
2013 ClearCommError(s->hcom, &comerr, &status);
2014 if (status.cbInQue > 0) {
2015 s->len = status.cbInQue;
2016 win_chr_read_poll(s);
2017 win_chr_read(s);
2018 return 1;
2020 return 0;
2023 static void win_chr_add_read_handler(CharDriverState *chr,
2024 IOCanRWHandler *fd_can_read,
2025 IOReadHandler *fd_read, void *opaque)
2027 WinCharState *s = chr->opaque;
2029 s->fd_can_read = fd_can_read;
2030 s->fd_read = fd_read;
2031 s->win_opaque = opaque;
2034 CharDriverState *qemu_chr_open_win(const char *filename)
2036 CharDriverState *chr;
2037 WinCharState *s;
2039 chr = qemu_mallocz(sizeof(CharDriverState));
2040 if (!chr)
2041 return NULL;
2042 s = qemu_mallocz(sizeof(WinCharState));
2043 if (!s) {
2044 free(chr);
2045 return NULL;
2047 chr->opaque = s;
2048 chr->chr_write = win_chr_write;
2049 chr->chr_add_read_handler = win_chr_add_read_handler;
2050 chr->chr_close = win_chr_close;
2052 if (win_chr_init(s, filename) < 0) {
2053 free(s);
2054 free(chr);
2055 return NULL;
2057 return chr;
2060 static int win_chr_pipe_poll(void *opaque)
2062 WinCharState *s = opaque;
2063 DWORD size;
2065 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2066 if (size > 0) {
2067 s->len = size;
2068 win_chr_read_poll(s);
2069 win_chr_read(s);
2070 return 1;
2072 return 0;
2075 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2077 OVERLAPPED ov;
2078 int ret;
2079 DWORD size;
2080 char openname[256];
2082 s->fpipe = TRUE;
2084 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2085 if (!s->hsend) {
2086 fprintf(stderr, "Failed CreateEvent\n");
2087 goto fail;
2089 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2090 if (!s->hrecv) {
2091 fprintf(stderr, "Failed CreateEvent\n");
2092 goto fail;
2095 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2096 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2097 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2098 PIPE_WAIT,
2099 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2100 if (s->hcom == INVALID_HANDLE_VALUE) {
2101 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2102 s->hcom = NULL;
2103 goto fail;
2106 ZeroMemory(&ov, sizeof(ov));
2107 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2108 ret = ConnectNamedPipe(s->hcom, &ov);
2109 if (ret) {
2110 fprintf(stderr, "Failed ConnectNamedPipe\n");
2111 goto fail;
2114 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2115 if (!ret) {
2116 fprintf(stderr, "Failed GetOverlappedResult\n");
2117 if (ov.hEvent) {
2118 CloseHandle(ov.hEvent);
2119 ov.hEvent = NULL;
2121 goto fail;
2124 if (ov.hEvent) {
2125 CloseHandle(ov.hEvent);
2126 ov.hEvent = NULL;
2128 qemu_add_polling_cb(win_chr_pipe_poll, s);
2129 return 0;
2131 fail:
2132 win_chr_close2(s);
2133 return -1;
2137 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2139 CharDriverState *chr;
2140 WinCharState *s;
2142 chr = qemu_mallocz(sizeof(CharDriverState));
2143 if (!chr)
2144 return NULL;
2145 s = qemu_mallocz(sizeof(WinCharState));
2146 if (!s) {
2147 free(chr);
2148 return NULL;
2150 chr->opaque = s;
2151 chr->chr_write = win_chr_write;
2152 chr->chr_add_read_handler = win_chr_add_read_handler;
2153 chr->chr_close = win_chr_close;
2155 if (win_chr_pipe_init(s, filename) < 0) {
2156 free(s);
2157 free(chr);
2158 return NULL;
2160 return chr;
2163 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2165 CharDriverState *chr;
2166 WinCharState *s;
2168 chr = qemu_mallocz(sizeof(CharDriverState));
2169 if (!chr)
2170 return NULL;
2171 s = qemu_mallocz(sizeof(WinCharState));
2172 if (!s) {
2173 free(chr);
2174 return NULL;
2176 s->hcom = fd_out;
2177 chr->opaque = s;
2178 chr->chr_write = win_chr_write;
2179 chr->chr_add_read_handler = win_chr_add_read_handler;
2180 return chr;
2183 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2185 HANDLE fd_out;
2187 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2188 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2189 if (fd_out == INVALID_HANDLE_VALUE)
2190 return NULL;
2192 return qemu_chr_open_win_file(fd_out);
2194 #endif
2196 /***********************************************************/
2197 /* UDP Net console */
2199 typedef struct {
2200 IOCanRWHandler *fd_can_read;
2201 IOReadHandler *fd_read;
2202 void *fd_opaque;
2203 int fd;
2204 struct sockaddr_in daddr;
2205 char buf[1024];
2206 int bufcnt;
2207 int bufptr;
2208 int max_size;
2209 } NetCharDriver;
2211 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2213 NetCharDriver *s = chr->opaque;
2215 return sendto(s->fd, buf, len, 0,
2216 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2219 static int udp_chr_read_poll(void *opaque)
2221 CharDriverState *chr = opaque;
2222 NetCharDriver *s = chr->opaque;
2224 s->max_size = s->fd_can_read(s->fd_opaque);
2226 /* If there were any stray characters in the queue process them
2227 * first
2228 */
2229 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2230 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2231 s->bufptr++;
2232 s->max_size = s->fd_can_read(s->fd_opaque);
2234 return s->max_size;
2237 static void udp_chr_read(void *opaque)
2239 CharDriverState *chr = opaque;
2240 NetCharDriver *s = chr->opaque;
2242 if (s->max_size == 0)
2243 return;
2244 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2245 s->bufptr = s->bufcnt;
2246 if (s->bufcnt <= 0)
2247 return;
2249 s->bufptr = 0;
2250 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2251 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2252 s->bufptr++;
2253 s->max_size = s->fd_can_read(s->fd_opaque);
2257 static void udp_chr_add_read_handler(CharDriverState *chr,
2258 IOCanRWHandler *fd_can_read,
2259 IOReadHandler *fd_read, void *opaque)
2261 NetCharDriver *s = chr->opaque;
2263 if (s->fd >= 0) {
2264 s->fd_can_read = fd_can_read;
2265 s->fd_read = fd_read;
2266 s->fd_opaque = opaque;
2267 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2268 udp_chr_read, NULL, chr);
2272 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2273 int parse_host_src_port(struct sockaddr_in *haddr,
2274 struct sockaddr_in *saddr,
2275 const char *str);
2277 CharDriverState *qemu_chr_open_udp(const char *def)
2279 CharDriverState *chr = NULL;
2280 NetCharDriver *s = NULL;
2281 int fd = -1;
2282 struct sockaddr_in saddr;
2284 chr = qemu_mallocz(sizeof(CharDriverState));
2285 if (!chr)
2286 goto return_err;
2287 s = qemu_mallocz(sizeof(NetCharDriver));
2288 if (!s)
2289 goto return_err;
2291 fd = socket(PF_INET, SOCK_DGRAM, 0);
2292 if (fd < 0) {
2293 perror("socket(PF_INET, SOCK_DGRAM)");
2294 goto return_err;
2297 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2298 printf("Could not parse: %s\n", def);
2299 goto return_err;
2302 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2304 perror("bind");
2305 goto return_err;
2308 s->fd = fd;
2309 s->bufcnt = 0;
2310 s->bufptr = 0;
2311 chr->opaque = s;
2312 chr->chr_write = udp_chr_write;
2313 chr->chr_add_read_handler = udp_chr_add_read_handler;
2314 return chr;
2316 return_err:
2317 if (chr)
2318 free(chr);
2319 if (s)
2320 free(s);
2321 if (fd >= 0)
2322 closesocket(fd);
2323 return NULL;
2326 /***********************************************************/
2327 /* TCP Net console */
2329 typedef struct {
2330 IOCanRWHandler *fd_can_read;
2331 IOReadHandler *fd_read;
2332 void *fd_opaque;
2333 int fd, listen_fd;
2334 int connected;
2335 int max_size;
2336 int do_telnetopt;
2337 } TCPCharDriver;
2339 static void tcp_chr_accept(void *opaque);
2341 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2343 TCPCharDriver *s = chr->opaque;
2344 if (s->connected) {
2345 return send_all(s->fd, buf, len);
2346 } else {
2347 /* XXX: indicate an error ? */
2348 return len;
2352 static int tcp_chr_read_poll(void *opaque)
2354 CharDriverState *chr = opaque;
2355 TCPCharDriver *s = chr->opaque;
2356 if (!s->connected)
2357 return 0;
2358 s->max_size = s->fd_can_read(s->fd_opaque);
2359 return s->max_size;
2362 #define IAC 255
2363 #define IAC_BREAK 243
2364 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2365 TCPCharDriver *s,
2366 char *buf, int *size)
2368 /* Handle any telnet client's basic IAC options to satisfy char by
2369 * char mode with no echo. All IAC options will be removed from
2370 * the buf and the do_telnetopt variable will be used to track the
2371 * state of the width of the IAC information.
2373 * IAC commands come in sets of 3 bytes with the exception of the
2374 * "IAC BREAK" command and the double IAC.
2375 */
2377 int i;
2378 int j = 0;
2380 for (i = 0; i < *size; i++) {
2381 if (s->do_telnetopt > 1) {
2382 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2383 /* Double IAC means send an IAC */
2384 if (j != i)
2385 buf[j] = buf[i];
2386 j++;
2387 s->do_telnetopt = 1;
2388 } else {
2389 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2390 /* Handle IAC break commands by sending a serial break */
2391 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2392 s->do_telnetopt++;
2394 s->do_telnetopt++;
2396 if (s->do_telnetopt >= 4) {
2397 s->do_telnetopt = 1;
2399 } else {
2400 if ((unsigned char)buf[i] == IAC) {
2401 s->do_telnetopt = 2;
2402 } else {
2403 if (j != i)
2404 buf[j] = buf[i];
2405 j++;
2409 *size = j;
2412 static void tcp_chr_read(void *opaque)
2414 CharDriverState *chr = opaque;
2415 TCPCharDriver *s = chr->opaque;
2416 uint8_t buf[1024];
2417 int len, size;
2419 if (!s->connected || s->max_size <= 0)
2420 return;
2421 len = sizeof(buf);
2422 if (len > s->max_size)
2423 len = s->max_size;
2424 size = recv(s->fd, buf, len, 0);
2425 if (size == 0) {
2426 /* connection closed */
2427 s->connected = 0;
2428 if (s->listen_fd >= 0) {
2429 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2431 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2432 closesocket(s->fd);
2433 s->fd = -1;
2434 } else if (size > 0) {
2435 if (s->do_telnetopt)
2436 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2437 if (size > 0)
2438 s->fd_read(s->fd_opaque, buf, size);
2442 static void tcp_chr_add_read_handler(CharDriverState *chr,
2443 IOCanRWHandler *fd_can_read,
2444 IOReadHandler *fd_read, void *opaque)
2446 TCPCharDriver *s = chr->opaque;
2448 s->fd_can_read = fd_can_read;
2449 s->fd_read = fd_read;
2450 s->fd_opaque = opaque;
2453 static void tcp_chr_connect(void *opaque)
2455 CharDriverState *chr = opaque;
2456 TCPCharDriver *s = chr->opaque;
2458 s->connected = 1;
2459 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2460 tcp_chr_read, NULL, chr);
2463 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2464 static void tcp_chr_telnet_init(int fd)
2466 char buf[3];
2467 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2468 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2469 send(fd, (char *)buf, 3, 0);
2470 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2471 send(fd, (char *)buf, 3, 0);
2472 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2473 send(fd, (char *)buf, 3, 0);
2474 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2475 send(fd, (char *)buf, 3, 0);
2478 static void tcp_chr_accept(void *opaque)
2480 CharDriverState *chr = opaque;
2481 TCPCharDriver *s = chr->opaque;
2482 struct sockaddr_in saddr;
2483 socklen_t len;
2484 int fd;
2486 for(;;) {
2487 len = sizeof(saddr);
2488 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2489 if (fd < 0 && errno != EINTR) {
2490 return;
2491 } else if (fd >= 0) {
2492 if (s->do_telnetopt)
2493 tcp_chr_telnet_init(fd);
2494 break;
2497 socket_set_nonblock(fd);
2498 s->fd = fd;
2499 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2500 tcp_chr_connect(chr);
2503 static void tcp_chr_close(CharDriverState *chr)
2505 TCPCharDriver *s = chr->opaque;
2506 if (s->fd >= 0)
2507 closesocket(s->fd);
2508 if (s->listen_fd >= 0)
2509 closesocket(s->listen_fd);
2510 qemu_free(s);
2513 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2514 int is_telnet)
2516 CharDriverState *chr = NULL;
2517 TCPCharDriver *s = NULL;
2518 int fd = -1, ret, err, val;
2519 int is_listen = 0;
2520 int is_waitconnect = 1;
2521 const char *ptr;
2522 struct sockaddr_in saddr;
2524 if (parse_host_port(&saddr, host_str) < 0)
2525 goto fail;
2527 ptr = host_str;
2528 while((ptr = strchr(ptr,','))) {
2529 ptr++;
2530 if (!strncmp(ptr,"server",6)) {
2531 is_listen = 1;
2532 } else if (!strncmp(ptr,"nowait",6)) {
2533 is_waitconnect = 0;
2534 } else {
2535 printf("Unknown option: %s\n", ptr);
2536 goto fail;
2539 if (!is_listen)
2540 is_waitconnect = 0;
2542 chr = qemu_mallocz(sizeof(CharDriverState));
2543 if (!chr)
2544 goto fail;
2545 s = qemu_mallocz(sizeof(TCPCharDriver));
2546 if (!s)
2547 goto fail;
2549 fd = socket(PF_INET, SOCK_STREAM, 0);
2550 if (fd < 0)
2551 goto fail;
2553 if (!is_waitconnect)
2554 socket_set_nonblock(fd);
2556 s->connected = 0;
2557 s->fd = -1;
2558 s->listen_fd = -1;
2559 if (is_listen) {
2560 /* allow fast reuse */
2561 val = 1;
2562 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2564 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2565 if (ret < 0)
2566 goto fail;
2567 ret = listen(fd, 0);
2568 if (ret < 0)
2569 goto fail;
2570 s->listen_fd = fd;
2571 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2572 if (is_telnet)
2573 s->do_telnetopt = 1;
2574 } else {
2575 for(;;) {
2576 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2577 if (ret < 0) {
2578 err = socket_error();
2579 if (err == EINTR || err == EWOULDBLOCK) {
2580 } else if (err == EINPROGRESS) {
2581 break;
2582 } else {
2583 goto fail;
2585 } else {
2586 s->connected = 1;
2587 break;
2590 s->fd = fd;
2591 if (s->connected)
2592 tcp_chr_connect(chr);
2593 else
2594 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2597 chr->opaque = s;
2598 chr->chr_write = tcp_chr_write;
2599 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2600 chr->chr_close = tcp_chr_close;
2601 if (is_listen && is_waitconnect) {
2602 printf("QEMU waiting for connection on: %s\n", host_str);
2603 tcp_chr_accept(chr);
2604 socket_set_nonblock(s->listen_fd);
2607 return chr;
2608 fail:
2609 if (fd >= 0)
2610 closesocket(fd);
2611 qemu_free(s);
2612 qemu_free(chr);
2613 return NULL;
2616 CharDriverState *qemu_chr_open(const char *filename)
2618 const char *p;
2620 if (!strcmp(filename, "vc")) {
2621 return text_console_init(&display_state);
2622 } else if (!strcmp(filename, "null")) {
2623 return qemu_chr_open_null();
2624 } else
2625 if (strstart(filename, "tcp:", &p)) {
2626 return qemu_chr_open_tcp(p, 0);
2627 } else
2628 if (strstart(filename, "telnet:", &p)) {
2629 return qemu_chr_open_tcp(p, 1);
2630 } else
2631 if (strstart(filename, "udp:", &p)) {
2632 return qemu_chr_open_udp(p);
2633 } else
2634 #ifndef _WIN32
2635 if (strstart(filename, "file:", &p)) {
2636 return qemu_chr_open_file_out(p);
2637 } else if (strstart(filename, "pipe:", &p)) {
2638 return qemu_chr_open_pipe(p);
2639 } else if (!strcmp(filename, "pty")) {
2640 return qemu_chr_open_pty();
2641 } else if (!strcmp(filename, "stdio")) {
2642 return qemu_chr_open_stdio();
2643 } else
2644 #endif
2645 #if defined(__linux__)
2646 if (strstart(filename, "/dev/parport", NULL)) {
2647 return qemu_chr_open_pp(filename);
2648 } else
2649 if (strstart(filename, "/dev/", NULL)) {
2650 return qemu_chr_open_tty(filename);
2651 } else
2652 #endif
2653 #ifdef _WIN32
2654 if (strstart(filename, "COM", NULL)) {
2655 return qemu_chr_open_win(filename);
2656 } else
2657 if (strstart(filename, "pipe:", &p)) {
2658 return qemu_chr_open_win_pipe(p);
2659 } else
2660 if (strstart(filename, "file:", &p)) {
2661 return qemu_chr_open_win_file_out(p);
2663 #endif
2665 return NULL;
2669 void qemu_chr_close(CharDriverState *chr)
2671 if (chr->chr_close)
2672 chr->chr_close(chr);
2675 /***********************************************************/
2676 /* network device redirectors */
2678 void hex_dump(FILE *f, const uint8_t *buf, int size)
2680 int len, i, j, c;
2682 for(i=0;i<size;i+=16) {
2683 len = size - i;
2684 if (len > 16)
2685 len = 16;
2686 fprintf(f, "%08x ", i);
2687 for(j=0;j<16;j++) {
2688 if (j < len)
2689 fprintf(f, " %02x", buf[i+j]);
2690 else
2691 fprintf(f, " ");
2693 fprintf(f, " ");
2694 for(j=0;j<len;j++) {
2695 c = buf[i+j];
2696 if (c < ' ' || c > '~')
2697 c = '.';
2698 fprintf(f, "%c", c);
2700 fprintf(f, "\n");
2704 static int parse_macaddr(uint8_t *macaddr, const char *p)
2706 int i;
2707 for(i = 0; i < 6; i++) {
2708 macaddr[i] = strtol(p, (char **)&p, 16);
2709 if (i == 5) {
2710 if (*p != '\0')
2711 return -1;
2712 } else {
2713 if (*p != ':')
2714 return -1;
2715 p++;
2718 return 0;
2721 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2723 const char *p, *p1;
2724 int len;
2725 p = *pp;
2726 p1 = strchr(p, sep);
2727 if (!p1)
2728 return -1;
2729 len = p1 - p;
2730 p1++;
2731 if (buf_size > 0) {
2732 if (len > buf_size - 1)
2733 len = buf_size - 1;
2734 memcpy(buf, p, len);
2735 buf[len] = '\0';
2737 *pp = p1;
2738 return 0;
2741 int parse_host_src_port(struct sockaddr_in *haddr,
2742 struct sockaddr_in *saddr,
2743 const char *input_str)
2745 char *str = strdup(input_str);
2746 char *host_str = str;
2747 char *src_str;
2748 char *ptr;
2750 /*
2751 * Chop off any extra arguments at the end of the string which
2752 * would start with a comma, then fill in the src port information
2753 * if it was provided else use the "any address" and "any port".
2754 */
2755 if ((ptr = strchr(str,',')))
2756 *ptr = '\0';
2758 if ((src_str = strchr(input_str,'@'))) {
2759 *src_str = '\0';
2760 src_str++;
2763 if (parse_host_port(haddr, host_str) < 0)
2764 goto fail;
2766 if (!src_str || *src_str == '\0')
2767 src_str = ":0";
2769 if (parse_host_port(saddr, src_str) < 0)
2770 goto fail;
2772 free(str);
2773 return(0);
2775 fail:
2776 free(str);
2777 return -1;
2780 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2782 char buf[512];
2783 struct hostent *he;
2784 const char *p, *r;
2785 int port;
2787 p = str;
2788 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2789 return -1;
2790 saddr->sin_family = AF_INET;
2791 if (buf[0] == '\0') {
2792 saddr->sin_addr.s_addr = 0;
2793 } else {
2794 if (isdigit(buf[0])) {
2795 if (!inet_aton(buf, &saddr->sin_addr))
2796 return -1;
2797 } else {
2798 if ((he = gethostbyname(buf)) == NULL)
2799 return - 1;
2800 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2803 port = strtol(p, (char **)&r, 0);
2804 if (r == p)
2805 return -1;
2806 saddr->sin_port = htons(port);
2807 return 0;
2810 /* find or alloc a new VLAN */
2811 VLANState *qemu_find_vlan(int id)
2813 VLANState **pvlan, *vlan;
2814 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2815 if (vlan->id == id)
2816 return vlan;
2818 vlan = qemu_mallocz(sizeof(VLANState));
2819 if (!vlan)
2820 return NULL;
2821 vlan->id = id;
2822 vlan->next = NULL;
2823 pvlan = &first_vlan;
2824 while (*pvlan != NULL)
2825 pvlan = &(*pvlan)->next;
2826 *pvlan = vlan;
2827 return vlan;
2830 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2831 IOReadHandler *fd_read,
2832 IOCanRWHandler *fd_can_read,
2833 void *opaque)
2835 VLANClientState *vc, **pvc;
2836 vc = qemu_mallocz(sizeof(VLANClientState));
2837 if (!vc)
2838 return NULL;
2839 vc->fd_read = fd_read;
2840 vc->fd_can_read = fd_can_read;
2841 vc->opaque = opaque;
2842 vc->vlan = vlan;
2844 vc->next = NULL;
2845 pvc = &vlan->first_client;
2846 while (*pvc != NULL)
2847 pvc = &(*pvc)->next;
2848 *pvc = vc;
2849 return vc;
2852 int qemu_can_send_packet(VLANClientState *vc1)
2854 VLANState *vlan = vc1->vlan;
2855 VLANClientState *vc;
2857 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2858 if (vc != vc1) {
2859 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2860 return 0;
2863 return 1;
2866 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2868 VLANState *vlan = vc1->vlan;
2869 VLANClientState *vc;
2871 #if 0
2872 printf("vlan %d send:\n", vlan->id);
2873 hex_dump(stdout, buf, size);
2874 #endif
2875 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2876 if (vc != vc1) {
2877 vc->fd_read(vc->opaque, buf, size);
2882 #if defined(CONFIG_SLIRP)
2884 /* slirp network adapter */
2886 static int slirp_inited;
2887 static VLANClientState *slirp_vc;
2889 int slirp_can_output(void)
2891 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2894 void slirp_output(const uint8_t *pkt, int pkt_len)
2896 #if 0
2897 printf("slirp output:\n");
2898 hex_dump(stdout, pkt, pkt_len);
2899 #endif
2900 if (!slirp_vc)
2901 return;
2902 qemu_send_packet(slirp_vc, pkt, pkt_len);
2905 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2907 #if 0
2908 printf("slirp input:\n");
2909 hex_dump(stdout, buf, size);
2910 #endif
2911 slirp_input(buf, size);
2914 static int net_slirp_init(VLANState *vlan)
2916 if (!slirp_inited) {
2917 slirp_inited = 1;
2918 slirp_init();
2920 slirp_vc = qemu_new_vlan_client(vlan,
2921 slirp_receive, NULL, NULL);
2922 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2923 return 0;
2926 static void net_slirp_redir(const char *redir_str)
2928 int is_udp;
2929 char buf[256], *r;
2930 const char *p;
2931 struct in_addr guest_addr;
2932 int host_port, guest_port;
2934 if (!slirp_inited) {
2935 slirp_inited = 1;
2936 slirp_init();
2939 p = redir_str;
2940 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2941 goto fail;
2942 if (!strcmp(buf, "tcp")) {
2943 is_udp = 0;
2944 } else if (!strcmp(buf, "udp")) {
2945 is_udp = 1;
2946 } else {
2947 goto fail;
2950 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2951 goto fail;
2952 host_port = strtol(buf, &r, 0);
2953 if (r == buf)
2954 goto fail;
2956 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2957 goto fail;
2958 if (buf[0] == '\0') {
2959 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2961 if (!inet_aton(buf, &guest_addr))
2962 goto fail;
2964 guest_port = strtol(p, &r, 0);
2965 if (r == p)
2966 goto fail;
2968 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2969 fprintf(stderr, "qemu: could not set up redirection\n");
2970 exit(1);
2972 return;
2973 fail:
2974 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2975 exit(1);
2978 #ifndef _WIN32
2980 char smb_dir[1024];
2982 static void smb_exit(void)
2984 DIR *d;
2985 struct dirent *de;
2986 char filename[1024];
2988 /* erase all the files in the directory */
2989 d = opendir(smb_dir);
2990 for(;;) {
2991 de = readdir(d);
2992 if (!de)
2993 break;
2994 if (strcmp(de->d_name, ".") != 0 &&
2995 strcmp(de->d_name, "..") != 0) {
2996 snprintf(filename, sizeof(filename), "%s/%s",
2997 smb_dir, de->d_name);
2998 unlink(filename);
3001 closedir(d);
3002 rmdir(smb_dir);
3005 /* automatic user mode samba server configuration */
3006 void net_slirp_smb(const char *exported_dir)
3008 char smb_conf[1024];
3009 char smb_cmdline[1024];
3010 FILE *f;
3012 if (!slirp_inited) {
3013 slirp_inited = 1;
3014 slirp_init();
3017 /* XXX: better tmp dir construction */
3018 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3019 if (mkdir(smb_dir, 0700) < 0) {
3020 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3021 exit(1);
3023 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3025 f = fopen(smb_conf, "w");
3026 if (!f) {
3027 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3028 exit(1);
3030 fprintf(f,
3031 "[global]\n"
3032 "private dir=%s\n"
3033 "smb ports=0\n"
3034 "socket address=127.0.0.1\n"
3035 "pid directory=%s\n"
3036 "lock directory=%s\n"
3037 "log file=%s/log.smbd\n"
3038 "smb passwd file=%s/smbpasswd\n"
3039 "security = share\n"
3040 "[qemu]\n"
3041 "path=%s\n"
3042 "read only=no\n"
3043 "guest ok=yes\n",
3044 smb_dir,
3045 smb_dir,
3046 smb_dir,
3047 smb_dir,
3048 smb_dir,
3049 exported_dir
3050 );
3051 fclose(f);
3052 atexit(smb_exit);
3054 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3055 smb_conf);
3057 slirp_add_exec(0, smb_cmdline, 4, 139);
3060 #endif /* !defined(_WIN32) */
3062 #endif /* CONFIG_SLIRP */
3064 #if !defined(_WIN32)
3066 typedef struct TAPState {
3067 VLANClientState *vc;
3068 int fd;
3069 } TAPState;
3071 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3073 TAPState *s = opaque;
3074 int ret;
3075 for(;;) {
3076 ret = write(s->fd, buf, size);
3077 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3078 } else {
3079 break;
3084 static void tap_send(void *opaque)
3086 TAPState *s = opaque;
3087 uint8_t buf[4096];
3088 int size;
3090 size = read(s->fd, buf, sizeof(buf));
3091 if (size > 0) {
3092 qemu_send_packet(s->vc, buf, size);
3096 /* fd support */
3098 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3100 TAPState *s;
3102 s = qemu_mallocz(sizeof(TAPState));
3103 if (!s)
3104 return NULL;
3105 s->fd = fd;
3106 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3107 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3108 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3109 return s;
3112 #ifdef _BSD
3113 static int tap_open(char *ifname, int ifname_size)
3115 int fd;
3116 char *dev;
3117 struct stat s;
3119 fd = open("/dev/tap", O_RDWR);
3120 if (fd < 0) {
3121 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3122 return -1;
3125 fstat(fd, &s);
3126 dev = devname(s.st_rdev, S_IFCHR);
3127 pstrcpy(ifname, ifname_size, dev);
3129 fcntl(fd, F_SETFL, O_NONBLOCK);
3130 return fd;
3132 #elif defined(__sun__)
3133 static int tap_open(char *ifname, int ifname_size)
3135 fprintf(stderr, "warning: tap_open not yet implemented\n");
3136 return -1;
3138 #else
3139 static int tap_open(char *ifname, int ifname_size)
3141 struct ifreq ifr;
3142 int fd, ret;
3144 fd = open("/dev/net/tun", O_RDWR);
3145 if (fd < 0) {
3146 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3147 return -1;
3149 memset(&ifr, 0, sizeof(ifr));
3150 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3151 if (ifname[0] != '\0')
3152 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3153 else
3154 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3155 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3156 if (ret != 0) {
3157 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3158 close(fd);
3159 return -1;
3161 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3162 fcntl(fd, F_SETFL, O_NONBLOCK);
3163 return fd;
3165 #endif
3167 static int net_tap_init(VLANState *vlan, const char *ifname1,
3168 const char *setup_script, const char *bridge)
3170 TAPState *s;
3171 int pid, status, fd;
3172 char *args[4];
3173 char **parg;
3174 char ifname[128];
3176 if (ifname1 != NULL)
3177 pstrcpy(ifname, sizeof(ifname), ifname1);
3178 else
3179 ifname[0] = '\0';
3180 fd = tap_open(ifname, sizeof(ifname));
3181 if (fd < 0)
3182 return -1;
3184 if (!setup_script)
3185 setup_script = "";
3186 if (setup_script[0] != '\0') {
3187 /* try to launch network init script */
3188 pid = fork();
3189 if (pid >= 0) {
3190 if (pid == 0) {
3191 parg = args;
3192 *parg++ = (char *)setup_script;
3193 *parg++ = ifname;
3194 *parg++ = (char *)bridge;
3195 *parg++ = NULL;
3196 execv(setup_script, args);
3197 _exit(1);
3199 while (waitpid(pid, &status, 0) != pid);
3200 if (!WIFEXITED(status) ||
3201 WEXITSTATUS(status) != 0) {
3202 fprintf(stderr, "%s: could not launch network script\n",
3203 setup_script);
3204 return -1;
3208 s = net_tap_fd_init(vlan, fd);
3209 if (!s)
3210 return -1;
3211 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3212 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3213 return 0;
3216 #endif /* !_WIN32 */
3218 /* network connection */
3219 typedef struct NetSocketState {
3220 VLANClientState *vc;
3221 int fd;
3222 int state; /* 0 = getting length, 1 = getting data */
3223 int index;
3224 int packet_len;
3225 uint8_t buf[4096];
3226 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3227 } NetSocketState;
3229 typedef struct NetSocketListenState {
3230 VLANState *vlan;
3231 int fd;
3232 } NetSocketListenState;
3234 /* XXX: we consider we can send the whole packet without blocking */
3235 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3237 NetSocketState *s = opaque;
3238 uint32_t len;
3239 len = htonl(size);
3241 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3242 send_all(s->fd, buf, size);
3245 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3247 NetSocketState *s = opaque;
3248 sendto(s->fd, buf, size, 0,
3249 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3252 static void net_socket_send(void *opaque)
3254 NetSocketState *s = opaque;
3255 int l, size, err;
3256 uint8_t buf1[4096];
3257 const uint8_t *buf;
3259 size = recv(s->fd, buf1, sizeof(buf1), 0);
3260 if (size < 0) {
3261 err = socket_error();
3262 if (err != EWOULDBLOCK)
3263 goto eoc;
3264 } else if (size == 0) {
3265 /* end of connection */
3266 eoc:
3267 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3268 closesocket(s->fd);
3269 return;
3271 buf = buf1;
3272 while (size > 0) {
3273 /* reassemble a packet from the network */
3274 switch(s->state) {
3275 case 0:
3276 l = 4 - s->index;
3277 if (l > size)
3278 l = size;
3279 memcpy(s->buf + s->index, buf, l);
3280 buf += l;
3281 size -= l;
3282 s->index += l;
3283 if (s->index == 4) {
3284 /* got length */
3285 s->packet_len = ntohl(*(uint32_t *)s->buf);
3286 s->index = 0;
3287 s->state = 1;
3289 break;
3290 case 1:
3291 l = s->packet_len - s->index;
3292 if (l > size)
3293 l = size;
3294 memcpy(s->buf + s->index, buf, l);
3295 s->index += l;
3296 buf += l;
3297 size -= l;
3298 if (s->index >= s->packet_len) {
3299 qemu_send_packet(s->vc, s->buf, s->packet_len);
3300 s->index = 0;
3301 s->state = 0;
3303 break;
3308 static void net_socket_send_dgram(void *opaque)
3310 NetSocketState *s = opaque;
3311 int size;
3313 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3314 if (size < 0)
3315 return;
3316 if (size == 0) {
3317 /* end of connection */
3318 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3319 return;
3321 qemu_send_packet(s->vc, s->buf, size);
3324 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3326 struct ip_mreq imr;
3327 int fd;
3328 int val, ret;
3329 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3330 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3331 inet_ntoa(mcastaddr->sin_addr),
3332 (int)ntohl(mcastaddr->sin_addr.s_addr));
3333 return -1;
3336 fd = socket(PF_INET, SOCK_DGRAM, 0);
3337 if (fd < 0) {
3338 perror("socket(PF_INET, SOCK_DGRAM)");
3339 return -1;
3342 val = 1;
3343 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3344 (const char *)&val, sizeof(val));
3345 if (ret < 0) {
3346 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3347 goto fail;
3350 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3351 if (ret < 0) {
3352 perror("bind");
3353 goto fail;
3356 /* Add host to multicast group */
3357 imr.imr_multiaddr = mcastaddr->sin_addr;
3358 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3360 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3361 (const char *)&imr, sizeof(struct ip_mreq));
3362 if (ret < 0) {
3363 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3364 goto fail;
3367 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3368 val = 1;
3369 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3370 (const char *)&val, sizeof(val));
3371 if (ret < 0) {
3372 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3373 goto fail;
3376 socket_set_nonblock(fd);
3377 return fd;
3378 fail:
3379 if (fd >= 0)
3380 closesocket(fd);
3381 return -1;
3384 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3385 int is_connected)
3387 struct sockaddr_in saddr;
3388 int newfd;
3389 socklen_t saddr_len;
3390 NetSocketState *s;
3392 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3393 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3394 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3395 */
3397 if (is_connected) {
3398 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3399 /* must be bound */
3400 if (saddr.sin_addr.s_addr==0) {
3401 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3402 fd);
3403 return NULL;
3405 /* clone dgram socket */
3406 newfd = net_socket_mcast_create(&saddr);
3407 if (newfd < 0) {
3408 /* error already reported by net_socket_mcast_create() */
3409 close(fd);
3410 return NULL;
3412 /* clone newfd to fd, close newfd */
3413 dup2(newfd, fd);
3414 close(newfd);
3416 } else {
3417 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3418 fd, strerror(errno));
3419 return NULL;
3423 s = qemu_mallocz(sizeof(NetSocketState));
3424 if (!s)
3425 return NULL;
3426 s->fd = fd;
3428 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3429 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3431 /* mcast: save bound address as dst */
3432 if (is_connected) s->dgram_dst=saddr;
3434 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3435 "socket: fd=%d (%s mcast=%s:%d)",
3436 fd, is_connected? "cloned" : "",
3437 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3438 return s;
3441 static void net_socket_connect(void *opaque)
3443 NetSocketState *s = opaque;
3444 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3447 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3448 int is_connected)
3450 NetSocketState *s;
3451 s = qemu_mallocz(sizeof(NetSocketState));
3452 if (!s)
3453 return NULL;
3454 s->fd = fd;
3455 s->vc = qemu_new_vlan_client(vlan,
3456 net_socket_receive, NULL, s);
3457 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3458 "socket: fd=%d", fd);
3459 if (is_connected) {
3460 net_socket_connect(s);
3461 } else {
3462 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3464 return s;
3467 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3468 int is_connected)
3470 int so_type=-1, optlen=sizeof(so_type);
3472 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3473 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3474 return NULL;
3476 switch(so_type) {
3477 case SOCK_DGRAM:
3478 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3479 case SOCK_STREAM:
3480 return net_socket_fd_init_stream(vlan, fd, is_connected);
3481 default:
3482 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3483 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3484 return net_socket_fd_init_stream(vlan, fd, is_connected);
3486 return NULL;
3489 static void net_socket_accept(void *opaque)
3491 NetSocketListenState *s = opaque;
3492 NetSocketState *s1;
3493 struct sockaddr_in saddr;
3494 socklen_t len;
3495 int fd;
3497 for(;;) {
3498 len = sizeof(saddr);
3499 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3500 if (fd < 0 && errno != EINTR) {
3501 return;
3502 } else if (fd >= 0) {
3503 break;
3506 s1 = net_socket_fd_init(s->vlan, fd, 1);
3507 if (!s1) {
3508 closesocket(fd);
3509 } else {
3510 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3511 "socket: connection from %s:%d",
3512 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3516 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3518 NetSocketListenState *s;
3519 int fd, val, ret;
3520 struct sockaddr_in saddr;
3522 if (parse_host_port(&saddr, host_str) < 0)
3523 return -1;
3525 s = qemu_mallocz(sizeof(NetSocketListenState));
3526 if (!s)
3527 return -1;
3529 fd = socket(PF_INET, SOCK_STREAM, 0);
3530 if (fd < 0) {
3531 perror("socket");
3532 return -1;
3534 socket_set_nonblock(fd);
3536 /* allow fast reuse */
3537 val = 1;
3538 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3540 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3541 if (ret < 0) {
3542 perror("bind");
3543 return -1;
3545 ret = listen(fd, 0);
3546 if (ret < 0) {
3547 perror("listen");
3548 return -1;
3550 s->vlan = vlan;
3551 s->fd = fd;
3552 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3553 return 0;
3556 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3558 NetSocketState *s;
3559 int fd, connected, ret, err;
3560 struct sockaddr_in saddr;
3562 if (parse_host_port(&saddr, host_str) < 0)
3563 return -1;
3565 fd = socket(PF_INET, SOCK_STREAM, 0);
3566 if (fd < 0) {
3567 perror("socket");
3568 return -1;
3570 socket_set_nonblock(fd);
3572 connected = 0;
3573 for(;;) {
3574 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3575 if (ret < 0) {
3576 err = socket_error();
3577 if (err == EINTR || err == EWOULDBLOCK) {
3578 } else if (err == EINPROGRESS) {
3579 break;
3580 } else {
3581 perror("connect");
3582 closesocket(fd);
3583 return -1;
3585 } else {
3586 connected = 1;
3587 break;
3590 s = net_socket_fd_init(vlan, fd, connected);
3591 if (!s)
3592 return -1;
3593 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3594 "socket: connect to %s:%d",
3595 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3596 return 0;
3599 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3601 NetSocketState *s;
3602 int fd;
3603 struct sockaddr_in saddr;
3605 if (parse_host_port(&saddr, host_str) < 0)
3606 return -1;
3609 fd = net_socket_mcast_create(&saddr);
3610 if (fd < 0)
3611 return -1;
3613 s = net_socket_fd_init(vlan, fd, 0);
3614 if (!s)
3615 return -1;
3617 s->dgram_dst = saddr;
3619 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3620 "socket: mcast=%s:%d",
3621 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3622 return 0;
3626 static int get_param_value(char *buf, int buf_size,
3627 const char *tag, const char *str)
3629 const char *p;
3630 char *q;
3631 char option[128];
3633 p = str;
3634 for(;;) {
3635 q = option;
3636 while (*p != '\0' && *p != '=') {
3637 if ((q - option) < sizeof(option) - 1)
3638 *q++ = *p;
3639 p++;
3641 *q = '\0';
3642 if (*p != '=')
3643 break;
3644 p++;
3645 if (!strcmp(tag, option)) {
3646 q = buf;
3647 while (*p != '\0' && *p != ',') {
3648 if ((q - buf) < buf_size - 1)
3649 *q++ = *p;
3650 p++;
3652 *q = '\0';
3653 return q - buf;
3654 } else {
3655 while (*p != '\0' && *p != ',') {
3656 p++;
3659 if (*p != ',')
3660 break;
3661 p++;
3663 return 0;
3666 int net_client_init(const char *str)
3668 const char *p;
3669 char *q;
3670 char device[64];
3671 char buf[1024];
3672 int vlan_id, ret;
3673 VLANState *vlan;
3675 p = str;
3676 q = device;
3677 while (*p != '\0' && *p != ',') {
3678 if ((q - device) < sizeof(device) - 1)
3679 *q++ = *p;
3680 p++;
3682 *q = '\0';
3683 if (*p == ',')
3684 p++;
3685 vlan_id = 0;
3686 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3687 vlan_id = strtol(buf, NULL, 0);
3689 vlan = qemu_find_vlan(vlan_id);
3690 if (!vlan) {
3691 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3692 return -1;
3694 if (!strcmp(device, "nic")) {
3695 NICInfo *nd;
3696 uint8_t *macaddr;
3698 if (nb_nics >= MAX_NICS) {
3699 fprintf(stderr, "Too Many NICs\n");
3700 return -1;
3702 nd = &nd_table[nb_nics];
3703 macaddr = nd->macaddr;
3704 macaddr[0] = 0x52;
3705 macaddr[1] = 0x54;
3706 macaddr[2] = 0x00;
3707 macaddr[3] = 0x12;
3708 macaddr[4] = 0x34;
3709 macaddr[5] = 0x56 + nb_nics;
3711 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3712 if (parse_macaddr(macaddr, buf) < 0) {
3713 fprintf(stderr, "invalid syntax for ethernet address\n");
3714 return -1;
3717 if (get_param_value(buf, sizeof(buf), "model", p)) {
3718 nd->model = strdup(buf);
3720 nd->vlan = vlan;
3721 nb_nics++;
3722 ret = 0;
3723 } else
3724 if (!strcmp(device, "none")) {
3725 /* does nothing. It is needed to signal that no network cards
3726 are wanted */
3727 ret = 0;
3728 } else
3729 #ifdef CONFIG_SLIRP
3730 if (!strcmp(device, "user")) {
3731 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3732 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3734 ret = net_slirp_init(vlan);
3735 } else
3736 #endif
3737 #ifdef _WIN32
3738 if (!strcmp(device, "tap")) {
3739 char ifname[64];
3740 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3741 fprintf(stderr, "tap: no interface name\n");
3742 return -1;
3744 ret = tap_win32_init(vlan, ifname);
3745 } else
3746 #else
3747 if (!strcmp(device, "tap")) {
3748 char ifname[64];
3749 char setup_script[1024];
3750 char bridge[16];
3751 int fd;
3752 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3753 fd = strtol(buf, NULL, 0);
3754 ret = -1;
3755 if (net_tap_fd_init(vlan, fd))
3756 ret = 0;
3757 } else {
3758 ifname[0] = '\0';
3759 get_param_value(ifname, sizeof(ifname), "ifname", p);
3760 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3761 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3763 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3764 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3766 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3768 } else
3769 #endif
3770 if (!strcmp(device, "socket")) {
3771 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3772 int fd;
3773 fd = strtol(buf, NULL, 0);
3774 ret = -1;
3775 if (net_socket_fd_init(vlan, fd, 1))
3776 ret = 0;
3777 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3778 ret = net_socket_listen_init(vlan, buf);
3779 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3780 ret = net_socket_connect_init(vlan, buf);
3781 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3782 ret = net_socket_mcast_init(vlan, buf);
3783 } else {
3784 fprintf(stderr, "Unknown socket options: %s\n", p);
3785 return -1;
3787 } else
3789 fprintf(stderr, "Unknown network device: %s\n", device);
3790 return -1;
3792 if (ret < 0) {
3793 fprintf(stderr, "Could not initialize device '%s'\n", device);
3796 return ret;
3799 void do_info_network(void)
3801 VLANState *vlan;
3802 VLANClientState *vc;
3804 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3805 term_printf("VLAN %d devices:\n", vlan->id);
3806 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3807 term_printf(" %s\n", vc->info_str);
3811 /***********************************************************/
3812 /* USB devices */
3814 static USBPort *used_usb_ports;
3815 static USBPort *free_usb_ports;
3817 /* ??? Maybe change this to register a hub to keep track of the topology. */
3818 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3819 usb_attachfn attach)
3821 port->opaque = opaque;
3822 port->index = index;
3823 port->attach = attach;
3824 port->next = free_usb_ports;
3825 free_usb_ports = port;
3828 static int usb_device_add(const char *devname)
3830 const char *p;
3831 USBDevice *dev;
3832 USBPort *port;
3834 if (!free_usb_ports)
3835 return -1;
3837 if (strstart(devname, "host:", &p)) {
3838 dev = usb_host_device_open(p);
3839 } else if (!strcmp(devname, "mouse")) {
3840 dev = usb_mouse_init();
3841 } else if (!strcmp(devname, "tablet")) {
3842 dev = usb_tablet_init();
3843 } else if (strstart(devname, "disk:", &p)) {
3844 dev = usb_msd_init(p);
3845 } else {
3846 return -1;
3848 if (!dev)
3849 return -1;
3851 /* Find a USB port to add the device to. */
3852 port = free_usb_ports;
3853 if (!port->next) {
3854 USBDevice *hub;
3856 /* Create a new hub and chain it on. */
3857 free_usb_ports = NULL;
3858 port->next = used_usb_ports;
3859 used_usb_ports = port;
3861 hub = usb_hub_init(VM_USB_HUB_SIZE);
3862 usb_attach(port, hub);
3863 port = free_usb_ports;
3866 free_usb_ports = port->next;
3867 port->next = used_usb_ports;
3868 used_usb_ports = port;
3869 usb_attach(port, dev);
3870 return 0;
3873 static int usb_device_del(const char *devname)
3875 USBPort *port;
3876 USBPort **lastp;
3877 USBDevice *dev;
3878 int bus_num, addr;
3879 const char *p;
3881 if (!used_usb_ports)
3882 return -1;
3884 p = strchr(devname, '.');
3885 if (!p)
3886 return -1;
3887 bus_num = strtoul(devname, NULL, 0);
3888 addr = strtoul(p + 1, NULL, 0);
3889 if (bus_num != 0)
3890 return -1;
3892 lastp = &used_usb_ports;
3893 port = used_usb_ports;
3894 while (port && port->dev->addr != addr) {
3895 lastp = &port->next;
3896 port = port->next;
3899 if (!port)
3900 return -1;
3902 dev = port->dev;
3903 *lastp = port->next;
3904 usb_attach(port, NULL);
3905 dev->handle_destroy(dev);
3906 port->next = free_usb_ports;
3907 free_usb_ports = port;
3908 return 0;
3911 void do_usb_add(const char *devname)
3913 int ret;
3914 ret = usb_device_add(devname);
3915 if (ret < 0)
3916 term_printf("Could not add USB device '%s'\n", devname);
3919 void do_usb_del(const char *devname)
3921 int ret;
3922 ret = usb_device_del(devname);
3923 if (ret < 0)
3924 term_printf("Could not remove USB device '%s'\n", devname);
3927 void usb_info(void)
3929 USBDevice *dev;
3930 USBPort *port;
3931 const char *speed_str;
3933 if (!usb_enabled) {
3934 term_printf("USB support not enabled\n");
3935 return;
3938 for (port = used_usb_ports; port; port = port->next) {
3939 dev = port->dev;
3940 if (!dev)
3941 continue;
3942 switch(dev->speed) {
3943 case USB_SPEED_LOW:
3944 speed_str = "1.5";
3945 break;
3946 case USB_SPEED_FULL:
3947 speed_str = "12";
3948 break;
3949 case USB_SPEED_HIGH:
3950 speed_str = "480";
3951 break;
3952 default:
3953 speed_str = "?";
3954 break;
3956 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3957 0, dev->addr, speed_str, dev->devname);
3961 /***********************************************************/
3962 /* pid file */
3964 static char *pid_filename;
3966 /* Remove PID file. Called on normal exit */
3968 static void remove_pidfile(void)
3970 unlink (pid_filename);
3973 static void create_pidfile(const char *filename)
3975 struct stat pidstat;
3976 FILE *f;
3978 /* Try to write our PID to the named file */
3979 if (stat(filename, &pidstat) < 0) {
3980 if (errno == ENOENT) {
3981 if ((f = fopen (filename, "w")) == NULL) {
3982 perror("Opening pidfile");
3983 exit(1);
3985 fprintf(f, "%d\n", getpid());
3986 fclose(f);
3987 pid_filename = qemu_strdup(filename);
3988 if (!pid_filename) {
3989 fprintf(stderr, "Could not save PID filename");
3990 exit(1);
3992 atexit(remove_pidfile);
3994 } else {
3995 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3996 filename);
3997 exit(1);
4001 /***********************************************************/
4002 /* dumb display */
4004 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4008 static void dumb_resize(DisplayState *ds, int w, int h)
4012 static void dumb_refresh(DisplayState *ds)
4014 vga_hw_update();
4017 void dumb_display_init(DisplayState *ds)
4019 ds->data = NULL;
4020 ds->linesize = 0;
4021 ds->depth = 0;
4022 ds->dpy_update = dumb_update;
4023 ds->dpy_resize = dumb_resize;
4024 ds->dpy_refresh = dumb_refresh;
4027 /***********************************************************/
4028 /* I/O handling */
4030 #define MAX_IO_HANDLERS 64
4032 typedef struct IOHandlerRecord {
4033 int fd;
4034 IOCanRWHandler *fd_read_poll;
4035 IOHandler *fd_read;
4036 IOHandler *fd_write;
4037 void *opaque;
4038 /* temporary data */
4039 struct pollfd *ufd;
4040 struct IOHandlerRecord *next;
4041 } IOHandlerRecord;
4043 static IOHandlerRecord *first_io_handler;
4045 /* XXX: fd_read_poll should be suppressed, but an API change is
4046 necessary in the character devices to suppress fd_can_read(). */
4047 int qemu_set_fd_handler2(int fd,
4048 IOCanRWHandler *fd_read_poll,
4049 IOHandler *fd_read,
4050 IOHandler *fd_write,
4051 void *opaque)
4053 IOHandlerRecord **pioh, *ioh;
4055 if (!fd_read && !fd_write) {
4056 pioh = &first_io_handler;
4057 for(;;) {
4058 ioh = *pioh;
4059 if (ioh == NULL)
4060 break;
4061 if (ioh->fd == fd) {
4062 *pioh = ioh->next;
4063 qemu_free(ioh);
4064 break;
4066 pioh = &ioh->next;
4068 } else {
4069 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4070 if (ioh->fd == fd)
4071 goto found;
4073 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4074 if (!ioh)
4075 return -1;
4076 ioh->next = first_io_handler;
4077 first_io_handler = ioh;
4078 found:
4079 ioh->fd = fd;
4080 ioh->fd_read_poll = fd_read_poll;
4081 ioh->fd_read = fd_read;
4082 ioh->fd_write = fd_write;
4083 ioh->opaque = opaque;
4085 return 0;
4088 int qemu_set_fd_handler(int fd,
4089 IOHandler *fd_read,
4090 IOHandler *fd_write,
4091 void *opaque)
4093 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4096 /***********************************************************/
4097 /* Polling handling */
4099 typedef struct PollingEntry {
4100 PollingFunc *func;
4101 void *opaque;
4102 struct PollingEntry *next;
4103 } PollingEntry;
4105 static PollingEntry *first_polling_entry;
4107 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4109 PollingEntry **ppe, *pe;
4110 pe = qemu_mallocz(sizeof(PollingEntry));
4111 if (!pe)
4112 return -1;
4113 pe->func = func;
4114 pe->opaque = opaque;
4115 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4116 *ppe = pe;
4117 return 0;
4120 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4122 PollingEntry **ppe, *pe;
4123 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4124 pe = *ppe;
4125 if (pe->func == func && pe->opaque == opaque) {
4126 *ppe = pe->next;
4127 qemu_free(pe);
4128 break;
4133 #ifdef _WIN32
4134 /***********************************************************/
4135 /* Wait objects support */
4136 typedef struct WaitObjects {
4137 int num;
4138 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4139 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4140 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4141 } WaitObjects;
4143 static WaitObjects wait_objects = {0};
4145 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4147 WaitObjects *w = &wait_objects;
4149 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4150 return -1;
4151 w->events[w->num] = handle;
4152 w->func[w->num] = func;
4153 w->opaque[w->num] = opaque;
4154 w->num++;
4155 return 0;
4158 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4160 int i, found;
4161 WaitObjects *w = &wait_objects;
4163 found = 0;
4164 for (i = 0; i < w->num; i++) {
4165 if (w->events[i] == handle)
4166 found = 1;
4167 if (found) {
4168 w->events[i] = w->events[i + 1];
4169 w->func[i] = w->func[i + 1];
4170 w->opaque[i] = w->opaque[i + 1];
4173 if (found)
4174 w->num--;
4176 #endif
4178 /***********************************************************/
4179 /* savevm/loadvm support */
4181 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4183 fwrite(buf, 1, size, f);
4186 void qemu_put_byte(QEMUFile *f, int v)
4188 fputc(v, f);
4191 void qemu_put_be16(QEMUFile *f, unsigned int v)
4193 qemu_put_byte(f, v >> 8);
4194 qemu_put_byte(f, v);
4197 void qemu_put_be32(QEMUFile *f, unsigned int v)
4199 qemu_put_byte(f, v >> 24);
4200 qemu_put_byte(f, v >> 16);
4201 qemu_put_byte(f, v >> 8);
4202 qemu_put_byte(f, v);
4205 void qemu_put_be64(QEMUFile *f, uint64_t v)
4207 qemu_put_be32(f, v >> 32);
4208 qemu_put_be32(f, v);
4211 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4213 return fread(buf, 1, size, f);
4216 int qemu_get_byte(QEMUFile *f)
4218 int v;
4219 v = fgetc(f);
4220 if (v == EOF)
4221 return 0;
4222 else
4223 return v;
4226 unsigned int qemu_get_be16(QEMUFile *f)
4228 unsigned int v;
4229 v = qemu_get_byte(f) << 8;
4230 v |= qemu_get_byte(f);
4231 return v;
4234 unsigned int qemu_get_be32(QEMUFile *f)
4236 unsigned int v;
4237 v = qemu_get_byte(f) << 24;
4238 v |= qemu_get_byte(f) << 16;
4239 v |= qemu_get_byte(f) << 8;
4240 v |= qemu_get_byte(f);
4241 return v;
4244 uint64_t qemu_get_be64(QEMUFile *f)
4246 uint64_t v;
4247 v = (uint64_t)qemu_get_be32(f) << 32;
4248 v |= qemu_get_be32(f);
4249 return v;
4252 int64_t qemu_ftell(QEMUFile *f)
4254 return ftell(f);
4257 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4259 if (fseek(f, pos, whence) < 0)
4260 return -1;
4261 return ftell(f);
4264 typedef struct SaveStateEntry {
4265 char idstr[256];
4266 int instance_id;
4267 int version_id;
4268 SaveStateHandler *save_state;
4269 LoadStateHandler *load_state;
4270 void *opaque;
4271 struct SaveStateEntry *next;
4272 } SaveStateEntry;
4274 static SaveStateEntry *first_se;
4276 int register_savevm(const char *idstr,
4277 int instance_id,
4278 int version_id,
4279 SaveStateHandler *save_state,
4280 LoadStateHandler *load_state,
4281 void *opaque)
4283 SaveStateEntry *se, **pse;
4285 se = qemu_malloc(sizeof(SaveStateEntry));
4286 if (!se)
4287 return -1;
4288 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4289 se->instance_id = instance_id;
4290 se->version_id = version_id;
4291 se->save_state = save_state;
4292 se->load_state = load_state;
4293 se->opaque = opaque;
4294 se->next = NULL;
4296 /* add at the end of list */
4297 pse = &first_se;
4298 while (*pse != NULL)
4299 pse = &(*pse)->next;
4300 *pse = se;
4301 return 0;
4304 #define QEMU_VM_FILE_MAGIC 0x5145564d
4305 #define QEMU_VM_FILE_VERSION 0x00000001
4307 int qemu_savevm(const char *filename)
4309 SaveStateEntry *se;
4310 QEMUFile *f;
4311 int len, len_pos, cur_pos, saved_vm_running, ret;
4313 saved_vm_running = vm_running;
4314 vm_stop(0);
4316 f = fopen(filename, "wb");
4317 if (!f) {
4318 ret = -1;
4319 goto the_end;
4322 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4323 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4325 for(se = first_se; se != NULL; se = se->next) {
4326 /* ID string */
4327 len = strlen(se->idstr);
4328 qemu_put_byte(f, len);
4329 qemu_put_buffer(f, se->idstr, len);
4331 qemu_put_be32(f, se->instance_id);
4332 qemu_put_be32(f, se->version_id);
4334 /* record size: filled later */
4335 len_pos = ftell(f);
4336 qemu_put_be32(f, 0);
4338 se->save_state(f, se->opaque);
4340 /* fill record size */
4341 cur_pos = ftell(f);
4342 len = ftell(f) - len_pos - 4;
4343 fseek(f, len_pos, SEEK_SET);
4344 qemu_put_be32(f, len);
4345 fseek(f, cur_pos, SEEK_SET);
4348 fclose(f);
4349 ret = 0;
4350 the_end:
4351 if (saved_vm_running)
4352 vm_start();
4353 return ret;
4356 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4358 SaveStateEntry *se;
4360 for(se = first_se; se != NULL; se = se->next) {
4361 if (!strcmp(se->idstr, idstr) &&
4362 instance_id == se->instance_id)
4363 return se;
4365 return NULL;
4368 int qemu_loadvm(const char *filename)
4370 SaveStateEntry *se;
4371 QEMUFile *f;
4372 int len, cur_pos, ret, instance_id, record_len, version_id;
4373 int saved_vm_running;
4374 unsigned int v;
4375 char idstr[256];
4377 saved_vm_running = vm_running;
4378 vm_stop(0);
4380 f = fopen(filename, "rb");
4381 if (!f) {
4382 ret = -1;
4383 goto the_end;
4386 v = qemu_get_be32(f);
4387 if (v != QEMU_VM_FILE_MAGIC)
4388 goto fail;
4389 v = qemu_get_be32(f);
4390 if (v != QEMU_VM_FILE_VERSION) {
4391 fail:
4392 fclose(f);
4393 ret = -1;
4394 goto the_end;
4396 for(;;) {
4397 len = qemu_get_byte(f);
4398 if (feof(f))
4399 break;
4400 qemu_get_buffer(f, idstr, len);
4401 idstr[len] = '\0';
4402 instance_id = qemu_get_be32(f);
4403 version_id = qemu_get_be32(f);
4404 record_len = qemu_get_be32(f);
4405 #if 0
4406 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4407 idstr, instance_id, version_id, record_len);
4408 #endif
4409 cur_pos = ftell(f);
4410 se = find_se(idstr, instance_id);
4411 if (!se) {
4412 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4413 instance_id, idstr);
4414 } else {
4415 ret = se->load_state(f, se->opaque, version_id);
4416 if (ret < 0) {
4417 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4418 instance_id, idstr);
4421 /* always seek to exact end of record */
4422 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4424 fclose(f);
4425 ret = 0;
4426 the_end:
4427 if (saved_vm_running)
4428 vm_start();
4429 return ret;
4432 #ifndef CONFIG_DM
4433 /***********************************************************/
4434 /* cpu save/restore */
4436 #if defined(TARGET_I386)
4438 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4440 qemu_put_be32(f, dt->selector);
4441 qemu_put_betl(f, dt->base);
4442 qemu_put_be32(f, dt->limit);
4443 qemu_put_be32(f, dt->flags);
4446 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4448 dt->selector = qemu_get_be32(f);
4449 dt->base = qemu_get_betl(f);
4450 dt->limit = qemu_get_be32(f);
4451 dt->flags = qemu_get_be32(f);
4454 void cpu_save(QEMUFile *f, void *opaque)
4456 CPUState *env = opaque;
4457 uint16_t fptag, fpus, fpuc, fpregs_format;
4458 uint32_t hflags;
4459 int i;
4461 for(i = 0; i < CPU_NB_REGS; i++)
4462 qemu_put_betls(f, &env->regs[i]);
4463 qemu_put_betls(f, &env->eip);
4464 qemu_put_betls(f, &env->eflags);
4465 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4466 qemu_put_be32s(f, &hflags);
4468 /* FPU */
4469 fpuc = env->fpuc;
4470 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4471 fptag = 0;
4472 for(i = 0; i < 8; i++) {
4473 fptag |= ((!env->fptags[i]) << i);
4476 qemu_put_be16s(f, &fpuc);
4477 qemu_put_be16s(f, &fpus);
4478 qemu_put_be16s(f, &fptag);
4480 #ifdef USE_X86LDOUBLE
4481 fpregs_format = 0;
4482 #else
4483 fpregs_format = 1;
4484 #endif
4485 qemu_put_be16s(f, &fpregs_format);
4487 for(i = 0; i < 8; i++) {
4488 #ifdef USE_X86LDOUBLE
4490 uint64_t mant;
4491 uint16_t exp;
4492 /* we save the real CPU data (in case of MMX usage only 'mant'
4493 contains the MMX register */
4494 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4495 qemu_put_be64(f, mant);
4496 qemu_put_be16(f, exp);
4498 #else
4499 /* if we use doubles for float emulation, we save the doubles to
4500 avoid losing information in case of MMX usage. It can give
4501 problems if the image is restored on a CPU where long
4502 doubles are used instead. */
4503 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4504 #endif
4507 for(i = 0; i < 6; i++)
4508 cpu_put_seg(f, &env->segs[i]);
4509 cpu_put_seg(f, &env->ldt);
4510 cpu_put_seg(f, &env->tr);
4511 cpu_put_seg(f, &env->gdt);
4512 cpu_put_seg(f, &env->idt);
4514 qemu_put_be32s(f, &env->sysenter_cs);
4515 qemu_put_be32s(f, &env->sysenter_esp);
4516 qemu_put_be32s(f, &env->sysenter_eip);
4518 qemu_put_betls(f, &env->cr[0]);
4519 qemu_put_betls(f, &env->cr[2]);
4520 qemu_put_betls(f, &env->cr[3]);
4521 qemu_put_betls(f, &env->cr[4]);
4523 for(i = 0; i < 8; i++)
4524 qemu_put_betls(f, &env->dr[i]);
4526 /* MMU */
4527 qemu_put_be32s(f, &env->a20_mask);
4529 /* XMM */
4530 qemu_put_be32s(f, &env->mxcsr);
4531 for(i = 0; i < CPU_NB_REGS; i++) {
4532 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4533 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4536 #ifdef TARGET_X86_64
4537 qemu_put_be64s(f, &env->efer);
4538 qemu_put_be64s(f, &env->star);
4539 qemu_put_be64s(f, &env->lstar);
4540 qemu_put_be64s(f, &env->cstar);
4541 qemu_put_be64s(f, &env->fmask);
4542 qemu_put_be64s(f, &env->kernelgsbase);
4543 #endif
4546 #ifdef USE_X86LDOUBLE
4547 /* XXX: add that in a FPU generic layer */
4548 union x86_longdouble {
4549 uint64_t mant;
4550 uint16_t exp;
4551 };
4553 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4554 #define EXPBIAS1 1023
4555 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4556 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4558 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4560 int e;
4561 /* mantissa */
4562 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4563 /* exponent + sign */
4564 e = EXPD1(temp) - EXPBIAS1 + 16383;
4565 e |= SIGND1(temp) >> 16;
4566 p->exp = e;
4568 #endif
4570 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4572 CPUState *env = opaque;
4573 int i, guess_mmx;
4574 uint32_t hflags;
4575 uint16_t fpus, fpuc, fptag, fpregs_format;
4577 if (version_id != 3)
4578 return -EINVAL;
4579 for(i = 0; i < CPU_NB_REGS; i++)
4580 qemu_get_betls(f, &env->regs[i]);
4581 qemu_get_betls(f, &env->eip);
4582 qemu_get_betls(f, &env->eflags);
4583 qemu_get_be32s(f, &hflags);
4585 qemu_get_be16s(f, &fpuc);
4586 qemu_get_be16s(f, &fpus);
4587 qemu_get_be16s(f, &fptag);
4588 qemu_get_be16s(f, &fpregs_format);
4590 /* NOTE: we cannot always restore the FPU state if the image come
4591 from a host with a different 'USE_X86LDOUBLE' define. We guess
4592 if we are in an MMX state to restore correctly in that case. */
4593 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4594 for(i = 0; i < 8; i++) {
4595 uint64_t mant;
4596 uint16_t exp;
4598 switch(fpregs_format) {
4599 case 0:
4600 mant = qemu_get_be64(f);
4601 exp = qemu_get_be16(f);
4602 #ifdef USE_X86LDOUBLE
4603 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4604 #else
4605 /* difficult case */
4606 if (guess_mmx)
4607 env->fpregs[i].mmx.MMX_Q(0) = mant;
4608 else
4609 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4610 #endif
4611 break;
4612 case 1:
4613 mant = qemu_get_be64(f);
4614 #ifdef USE_X86LDOUBLE
4616 union x86_longdouble *p;
4617 /* difficult case */
4618 p = (void *)&env->fpregs[i];
4619 if (guess_mmx) {
4620 p->mant = mant;
4621 p->exp = 0xffff;
4622 } else {
4623 fp64_to_fp80(p, mant);
4626 #else
4627 env->fpregs[i].mmx.MMX_Q(0) = mant;
4628 #endif
4629 break;
4630 default:
4631 return -EINVAL;
4635 env->fpuc = fpuc;
4636 /* XXX: restore FPU round state */
4637 env->fpstt = (fpus >> 11) & 7;
4638 env->fpus = fpus & ~0x3800;
4639 fptag ^= 0xff;
4640 for(i = 0; i < 8; i++) {
4641 env->fptags[i] = (fptag >> i) & 1;
4644 for(i = 0; i < 6; i++)
4645 cpu_get_seg(f, &env->segs[i]);
4646 cpu_get_seg(f, &env->ldt);
4647 cpu_get_seg(f, &env->tr);
4648 cpu_get_seg(f, &env->gdt);
4649 cpu_get_seg(f, &env->idt);
4651 qemu_get_be32s(f, &env->sysenter_cs);
4652 qemu_get_be32s(f, &env->sysenter_esp);
4653 qemu_get_be32s(f, &env->sysenter_eip);
4655 qemu_get_betls(f, &env->cr[0]);
4656 qemu_get_betls(f, &env->cr[2]);
4657 qemu_get_betls(f, &env->cr[3]);
4658 qemu_get_betls(f, &env->cr[4]);
4660 for(i = 0; i < 8; i++)
4661 qemu_get_betls(f, &env->dr[i]);
4663 /* MMU */
4664 qemu_get_be32s(f, &env->a20_mask);
4666 qemu_get_be32s(f, &env->mxcsr);
4667 for(i = 0; i < CPU_NB_REGS; i++) {
4668 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4669 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4672 #ifdef TARGET_X86_64
4673 qemu_get_be64s(f, &env->efer);
4674 qemu_get_be64s(f, &env->star);
4675 qemu_get_be64s(f, &env->lstar);
4676 qemu_get_be64s(f, &env->cstar);
4677 qemu_get_be64s(f, &env->fmask);
4678 qemu_get_be64s(f, &env->kernelgsbase);
4679 #endif
4681 /* XXX: compute hflags from scratch, except for CPL and IIF */
4682 env->hflags = hflags;
4683 tlb_flush(env, 1);
4684 return 0;
4687 #elif defined(TARGET_PPC)
4688 void cpu_save(QEMUFile *f, void *opaque)
4692 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4694 return 0;
4697 #elif defined(TARGET_MIPS)
4698 void cpu_save(QEMUFile *f, void *opaque)
4702 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4704 return 0;
4707 #elif defined(TARGET_SPARC)
4708 void cpu_save(QEMUFile *f, void *opaque)
4710 CPUState *env = opaque;
4711 int i;
4712 uint32_t tmp;
4714 for(i = 0; i < 8; i++)
4715 qemu_put_betls(f, &env->gregs[i]);
4716 for(i = 0; i < NWINDOWS * 16; i++)
4717 qemu_put_betls(f, &env->regbase[i]);
4719 /* FPU */
4720 for(i = 0; i < TARGET_FPREGS; i++) {
4721 union {
4722 float32 f;
4723 uint32_t i;
4724 } u;
4725 u.f = env->fpr[i];
4726 qemu_put_be32(f, u.i);
4729 qemu_put_betls(f, &env->pc);
4730 qemu_put_betls(f, &env->npc);
4731 qemu_put_betls(f, &env->y);
4732 tmp = GET_PSR(env);
4733 qemu_put_be32(f, tmp);
4734 qemu_put_betls(f, &env->fsr);
4735 qemu_put_betls(f, &env->tbr);
4736 #ifndef TARGET_SPARC64
4737 qemu_put_be32s(f, &env->wim);
4738 /* MMU */
4739 for(i = 0; i < 16; i++)
4740 qemu_put_be32s(f, &env->mmuregs[i]);
4741 #endif
4744 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4746 CPUState *env = opaque;
4747 int i;
4748 uint32_t tmp;
4750 for(i = 0; i < 8; i++)
4751 qemu_get_betls(f, &env->gregs[i]);
4752 for(i = 0; i < NWINDOWS * 16; i++)
4753 qemu_get_betls(f, &env->regbase[i]);
4755 /* FPU */
4756 for(i = 0; i < TARGET_FPREGS; i++) {
4757 union {
4758 float32 f;
4759 uint32_t i;
4760 } u;
4761 u.i = qemu_get_be32(f);
4762 env->fpr[i] = u.f;
4765 qemu_get_betls(f, &env->pc);
4766 qemu_get_betls(f, &env->npc);
4767 qemu_get_betls(f, &env->y);
4768 tmp = qemu_get_be32(f);
4769 env->cwp = 0; /* needed to ensure that the wrapping registers are
4770 correctly updated */
4771 PUT_PSR(env, tmp);
4772 qemu_get_betls(f, &env->fsr);
4773 qemu_get_betls(f, &env->tbr);
4774 #ifndef TARGET_SPARC64
4775 qemu_get_be32s(f, &env->wim);
4776 /* MMU */
4777 for(i = 0; i < 16; i++)
4778 qemu_get_be32s(f, &env->mmuregs[i]);
4779 #endif
4780 tlb_flush(env, 1);
4781 return 0;
4784 #elif defined(TARGET_ARM)
4786 /* ??? Need to implement these. */
4787 void cpu_save(QEMUFile *f, void *opaque)
4791 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4793 return 0;
4796 #else
4798 #warning No CPU save/restore functions
4800 #endif
4802 /***********************************************************/
4803 /* ram save/restore */
4805 /* we just avoid storing empty pages */
4806 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4808 int i, v;
4810 v = buf[0];
4811 for(i = 1; i < len; i++) {
4812 if (buf[i] != v)
4813 goto normal_save;
4815 qemu_put_byte(f, 1);
4816 qemu_put_byte(f, v);
4817 return;
4818 normal_save:
4819 qemu_put_byte(f, 0);
4820 qemu_put_buffer(f, buf, len);
4823 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4825 int v;
4827 v = qemu_get_byte(f);
4828 switch(v) {
4829 case 0:
4830 if (qemu_get_buffer(f, buf, len) != len)
4831 return -EIO;
4832 break;
4833 case 1:
4834 v = qemu_get_byte(f);
4835 memset(buf, v, len);
4836 break;
4837 default:
4838 return -EINVAL;
4840 return 0;
4843 static void ram_save(QEMUFile *f, void *opaque)
4845 int i;
4846 qemu_put_be32(f, phys_ram_size);
4847 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4848 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4852 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4854 int i, ret;
4856 if (version_id != 1)
4857 return -EINVAL;
4858 if (qemu_get_be32(f) != phys_ram_size)
4859 return -EINVAL;
4860 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4861 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4862 if (ret)
4863 return ret;
4865 return 0;
4867 #else /* CONFIG_DM */
4868 void cpu_save(QEMUFile *f, void *opaque)
4872 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4874 return 0;
4877 static void ram_save(QEMUFile *f, void *opaque)
4881 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4883 return 0;
4885 #endif /* CONFIG_DM */
4887 /***********************************************************/
4888 /* machine registration */
4890 QEMUMachine *first_machine = NULL;
4892 int qemu_register_machine(QEMUMachine *m)
4894 QEMUMachine **pm;
4895 pm = &first_machine;
4896 while (*pm != NULL)
4897 pm = &(*pm)->next;
4898 m->next = NULL;
4899 *pm = m;
4900 return 0;
4903 QEMUMachine *find_machine(const char *name)
4905 QEMUMachine *m;
4907 for(m = first_machine; m != NULL; m = m->next) {
4908 if (!strcmp(m->name, name))
4909 return m;
4911 return NULL;
4914 /***********************************************************/
4915 /* main execution loop */
4917 void gui_update(void *opaque)
4919 display_state.dpy_refresh(&display_state);
4920 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4923 struct vm_change_state_entry {
4924 VMChangeStateHandler *cb;
4925 void *opaque;
4926 LIST_ENTRY (vm_change_state_entry) entries;
4927 };
4929 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4931 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4932 void *opaque)
4934 VMChangeStateEntry *e;
4936 e = qemu_mallocz(sizeof (*e));
4937 if (!e)
4938 return NULL;
4940 e->cb = cb;
4941 e->opaque = opaque;
4942 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4943 return e;
4946 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4948 LIST_REMOVE (e, entries);
4949 qemu_free (e);
4952 static void vm_state_notify(int running)
4954 VMChangeStateEntry *e;
4956 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4957 e->cb(e->opaque, running);
4961 /* XXX: support several handlers */
4962 static VMStopHandler *vm_stop_cb;
4963 static void *vm_stop_opaque;
4965 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4967 vm_stop_cb = cb;
4968 vm_stop_opaque = opaque;
4969 return 0;
4972 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4974 vm_stop_cb = NULL;
4977 void vm_start(void)
4979 if (!vm_running) {
4980 cpu_enable_ticks();
4981 vm_running = 1;
4982 vm_state_notify(1);
4986 void vm_stop(int reason)
4988 if (vm_running) {
4989 cpu_disable_ticks();
4990 vm_running = 0;
4991 if (reason != 0) {
4992 if (vm_stop_cb) {
4993 vm_stop_cb(vm_stop_opaque, reason);
4996 vm_state_notify(0);
5000 /* reset/shutdown handler */
5002 typedef struct QEMUResetEntry {
5003 QEMUResetHandler *func;
5004 void *opaque;
5005 struct QEMUResetEntry *next;
5006 } QEMUResetEntry;
5008 static QEMUResetEntry *first_reset_entry;
5009 int reset_requested;
5010 int shutdown_requested;
5011 static int powerdown_requested;
5013 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5015 QEMUResetEntry **pre, *re;
5017 pre = &first_reset_entry;
5018 while (*pre != NULL)
5019 pre = &(*pre)->next;
5020 re = qemu_mallocz(sizeof(QEMUResetEntry));
5021 re->func = func;
5022 re->opaque = opaque;
5023 re->next = NULL;
5024 *pre = re;
5027 void qemu_system_reset(void)
5029 QEMUResetEntry *re;
5031 /* reset all devices */
5032 for(re = first_reset_entry; re != NULL; re = re->next) {
5033 re->func(re->opaque);
5037 void qemu_system_reset_request(void)
5039 reset_requested = 1;
5040 if (cpu_single_env)
5041 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5044 void qemu_system_shutdown_request(void)
5046 shutdown_requested = 1;
5047 if (cpu_single_env)
5048 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5051 void qemu_system_powerdown_request(void)
5053 powerdown_requested = 1;
5054 if (cpu_single_env)
5055 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5058 void main_loop_wait(int timeout)
5060 IOHandlerRecord *ioh, *ioh_next;
5061 fd_set rfds, wfds, xfds;
5062 int ret, nfds;
5063 struct timeval tv;
5064 PollingEntry *pe;
5067 /* XXX: need to suppress polling by better using win32 events */
5068 ret = 0;
5069 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5070 ret |= pe->func(pe->opaque);
5072 #ifdef _WIN32
5073 if (ret == 0 && timeout > 0) {
5074 int err;
5075 WaitObjects *w = &wait_objects;
5077 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5078 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5079 if (w->func[ret - WAIT_OBJECT_0])
5080 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5081 } else if (ret == WAIT_TIMEOUT) {
5082 } else {
5083 err = GetLastError();
5084 fprintf(stderr, "Wait error %d %d\n", ret, err);
5087 #endif
5088 /* poll any events */
5089 /* XXX: separate device handlers from system ones */
5090 nfds = -1;
5091 FD_ZERO(&rfds);
5092 FD_ZERO(&wfds);
5093 FD_ZERO(&xfds);
5094 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5095 if (ioh->fd_read &&
5096 (!ioh->fd_read_poll ||
5097 ioh->fd_read_poll(ioh->opaque) != 0)) {
5098 FD_SET(ioh->fd, &rfds);
5099 if (ioh->fd > nfds)
5100 nfds = ioh->fd;
5102 if (ioh->fd_write) {
5103 FD_SET(ioh->fd, &wfds);
5104 if (ioh->fd > nfds)
5105 nfds = ioh->fd;
5109 tv.tv_sec = 0;
5110 #ifdef _WIN32
5111 tv.tv_usec = 0;
5112 #else
5113 tv.tv_usec = timeout * 1000;
5114 #endif
5115 #if defined(CONFIG_SLIRP)
5116 if (slirp_inited) {
5117 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5119 #endif
5120 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5121 if (ret > 0) {
5122 /* XXX: better handling of removal */
5123 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5124 ioh_next = ioh->next;
5125 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
5126 ioh->fd_read(ioh->opaque);
5128 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
5129 ioh->fd_write(ioh->opaque);
5133 #if defined(CONFIG_SLIRP)
5134 if (slirp_inited) {
5135 if (ret < 0) {
5136 FD_ZERO(&rfds);
5137 FD_ZERO(&wfds);
5138 FD_ZERO(&xfds);
5140 slirp_select_poll(&rfds, &wfds, &xfds);
5142 #endif
5143 #ifdef _WIN32
5144 tap_win32_poll();
5145 #endif
5147 if (vm_running) {
5148 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5149 qemu_get_clock(vm_clock));
5150 /* run dma transfers, if any */
5151 DMA_run();
5154 /* real time timers */
5155 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5156 qemu_get_clock(rt_clock));
5159 #ifndef CONFIG_DM
5160 static CPUState *cur_cpu;
5162 int main_loop(void)
5164 int ret, timeout;
5165 #ifdef CONFIG_PROFILER
5166 int64_t ti;
5167 #endif
5168 CPUState *env;
5170 cur_cpu = first_cpu;
5171 for(;;) {
5172 if (vm_running) {
5174 env = cur_cpu;
5175 for(;;) {
5176 /* get next cpu */
5177 env = env->next_cpu;
5178 if (!env)
5179 env = first_cpu;
5180 #ifdef CONFIG_PROFILER
5181 ti = profile_getclock();
5182 #endif
5183 ret = cpu_exec(env);
5184 #ifdef CONFIG_PROFILER
5185 qemu_time += profile_getclock() - ti;
5186 #endif
5187 if (ret != EXCP_HALTED)
5188 break;
5189 /* all CPUs are halted ? */
5190 if (env == cur_cpu) {
5191 ret = EXCP_HLT;
5192 break;
5195 cur_cpu = env;
5197 if (shutdown_requested) {
5198 ret = EXCP_INTERRUPT;
5199 break;
5201 if (reset_requested) {
5202 reset_requested = 0;
5203 qemu_system_reset();
5204 ret = EXCP_INTERRUPT;
5206 if (powerdown_requested) {
5207 powerdown_requested = 0;
5208 qemu_system_powerdown();
5209 ret = EXCP_INTERRUPT;
5211 if (ret == EXCP_DEBUG) {
5212 vm_stop(EXCP_DEBUG);
5214 /* if hlt instruction, we wait until the next IRQ */
5215 /* XXX: use timeout computed from timers */
5216 if (ret == EXCP_HLT)
5217 timeout = 10;
5218 else
5219 timeout = 0;
5220 } else {
5221 timeout = 10;
5223 #ifdef CONFIG_PROFILER
5224 ti = profile_getclock();
5225 #endif
5226 main_loop_wait(timeout);
5227 #ifdef CONFIG_PROFILER
5228 dev_time += profile_getclock() - ti;
5229 #endif
5231 cpu_disable_ticks();
5232 return ret;
5234 #endif /* !CONFIG_DM */
5236 void help(void)
5238 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5239 "usage: %s [options] [disk_image]\n"
5240 "\n"
5241 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5242 "\n"
5243 "Standard options:\n"
5244 "-M machine select emulated machine (-M ? for list)\n"
5245 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5246 #ifndef CONFIG_DM
5247 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5248 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5249 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5250 #endif /* !CONFIG_DM */
5251 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5252 "-snapshot write to temporary files instead of disk image files\n"
5253 #ifdef TARGET_I386
5254 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5255 #endif
5256 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5257 "-smp n set the number of CPUs to 'n' [default=1]\n"
5258 "-nographic disable graphical output and redirect serial I/Os to console\n"
5259 "-vcpus set CPU number of guest platform\n"
5260 #ifndef _WIN32
5261 "-k language use keyboard layout (for example \"fr\" for French)\n"
5262 #endif
5263 #ifdef HAS_AUDIO
5264 "-audio-help print list of audio drivers and their options\n"
5265 "-soundhw c1,... enable audio support\n"
5266 " and only specified sound cards (comma separated list)\n"
5267 " use -soundhw ? to get the list of supported cards\n"
5268 " use -soundhw all to enable all of them\n"
5269 #endif
5270 "-localtime set the real time clock to local time [default=utc]\n"
5271 "-full-screen start in full screen\n"
5272 #ifdef TARGET_I386
5273 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5274 #endif
5275 "-usb enable the USB driver (will be the default soon)\n"
5276 "-usbdevice name add the host or guest USB device 'name'\n"
5277 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5278 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5279 #endif
5280 "\n"
5281 "Network options:\n"
5282 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5283 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5284 #ifdef CONFIG_SLIRP
5285 "-net user[,vlan=n][,hostname=host]\n"
5286 " connect the user mode network stack to VLAN 'n' and send\n"
5287 " hostname 'host' to DHCP clients\n"
5288 #endif
5289 #ifdef _WIN32
5290 "-net tap[,vlan=n],ifname=name\n"
5291 " connect the host TAP network interface to VLAN 'n'\n"
5292 #else
5293 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
5294 " connect the host TAP network interface to VLAN 'n' and use\n"
5295 " the network script 'file' (default=%s);\n"
5296 " use 'fd=h' to connect to an already opened TAP interface\n"
5297 #endif
5298 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5299 " connect the vlan 'n' to another VLAN using a socket connection\n"
5300 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5301 " connect the vlan 'n' to multicast maddr and port\n"
5302 "-net none use it alone to have zero network devices; if no -net option\n"
5303 " is provided, the default is '-net nic -net user'\n"
5304 "\n"
5305 #ifdef CONFIG_SLIRP
5306 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5307 #ifndef _WIN32
5308 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5309 #endif
5310 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5311 " redirect TCP or UDP connections from host to guest [-net user]\n"
5312 #endif
5313 "\n"
5314 "Linux boot specific:\n"
5315 "-kernel bzImage use 'bzImage' as kernel image\n"
5316 "-append cmdline use 'cmdline' as kernel command line\n"
5317 "-initrd file use 'file' as initial ram disk\n"
5318 "\n"
5319 "Debug/Expert options:\n"
5320 "-monitor dev redirect the monitor to char device 'dev'\n"
5321 "-serial dev redirect the serial port to char device 'dev'\n"
5322 "-parallel dev redirect the parallel port to char device 'dev'\n"
5323 "-pidfile file Write PID to 'file'\n"
5324 "-S freeze CPU at startup (use 'c' to start execution)\n"
5325 "-s wait gdb connection to port %d\n"
5326 "-p port change gdb connection port\n"
5327 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
5328 "-d domain domain that we're serving\n"
5329 "-domain-name domain name that we're serving\n"
5330 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5331 " translation (t=none or lba) (usually qemu can guess them)\n"
5332 "-L path set the directory for the BIOS and VGA BIOS\n"
5333 #ifdef USE_KQEMU
5334 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5335 "-no-kqemu disable KQEMU kernel module usage\n"
5336 #endif
5337 #ifdef USE_CODE_COPY
5338 "-no-code-copy disable code copy acceleration\n"
5339 #endif
5340 #ifdef TARGET_I386
5341 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5342 " (default is CL-GD5446 PCI VGA)\n"
5343 "-no-acpi disable ACPI\n"
5344 #endif
5345 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5346 "-vnc display start a VNC server on display\n"
5347 "-vncviewer start a vncviewer process for this domain\n"
5348 "-vncunused bind the VNC server to an unused port\n"
5349 "-timeoffset time offset (in seconds) from local time\n"
5350 "-acpi disable or enable ACPI of HVM domain \n"
5351 "\n"
5352 "During emulation, the following keys are useful:\n"
5353 "ctrl-alt-f toggle full screen\n"
5354 "ctrl-alt-n switch to virtual console 'n'\n"
5355 "ctrl-alt toggle mouse and keyboard grab\n"
5356 "\n"
5357 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5359 "qemu",
5360 DEFAULT_RAM_SIZE,
5361 #ifndef _WIN32
5362 DEFAULT_NETWORK_SCRIPT,
5363 #endif
5364 DEFAULT_GDBSTUB_PORT,
5365 "/tmp/qemu.log");
5366 exit(1);
5369 #define HAS_ARG 0x0001
5371 enum {
5372 QEMU_OPTION_h,
5374 QEMU_OPTION_M,
5375 QEMU_OPTION_fda,
5376 QEMU_OPTION_fdb,
5377 #ifndef CONFIG_DM
5378 QEMU_OPTION_hda,
5379 QEMU_OPTION_hdb,
5380 QEMU_OPTION_hdc,
5381 QEMU_OPTION_hdd,
5382 QEMU_OPTION_cdrom,
5383 #endif /* !CONFIG_DM */
5384 QEMU_OPTION_boot,
5385 QEMU_OPTION_snapshot,
5386 #ifdef TARGET_I386
5387 QEMU_OPTION_no_fd_bootchk,
5388 #endif
5389 QEMU_OPTION_m,
5390 QEMU_OPTION_nographic,
5391 #ifdef HAS_AUDIO
5392 QEMU_OPTION_audio_help,
5393 QEMU_OPTION_soundhw,
5394 #endif
5396 QEMU_OPTION_net,
5397 QEMU_OPTION_tftp,
5398 QEMU_OPTION_smb,
5399 QEMU_OPTION_redir,
5401 QEMU_OPTION_kernel,
5402 QEMU_OPTION_append,
5403 QEMU_OPTION_initrd,
5405 QEMU_OPTION_S,
5406 QEMU_OPTION_s,
5407 QEMU_OPTION_p,
5408 QEMU_OPTION_l,
5409 QEMU_OPTION_hdachs,
5410 QEMU_OPTION_L,
5411 #ifdef USE_CODE_COPY
5412 QEMU_OPTION_no_code_copy,
5413 #endif
5414 QEMU_OPTION_k,
5415 QEMU_OPTION_localtime,
5416 QEMU_OPTION_cirrusvga,
5417 QEMU_OPTION_g,
5418 QEMU_OPTION_std_vga,
5419 QEMU_OPTION_monitor,
5420 QEMU_OPTION_domainname,
5421 QEMU_OPTION_serial,
5422 QEMU_OPTION_parallel,
5423 QEMU_OPTION_loadvm,
5424 QEMU_OPTION_full_screen,
5425 QEMU_OPTION_pidfile,
5426 QEMU_OPTION_no_kqemu,
5427 QEMU_OPTION_kernel_kqemu,
5428 QEMU_OPTION_win2k_hack,
5429 QEMU_OPTION_usb,
5430 QEMU_OPTION_usbdevice,
5431 QEMU_OPTION_smp,
5432 QEMU_OPTION_vnc,
5433 QEMU_OPTION_no_acpi,
5435 QEMU_OPTION_d,
5436 QEMU_OPTION_vcpus,
5437 QEMU_OPTION_timeoffset,
5438 QEMU_OPTION_acpi,
5439 QEMU_OPTION_vncviewer,
5440 QEMU_OPTION_vncunused,
5441 };
5443 typedef struct QEMUOption {
5444 const char *name;
5445 int flags;
5446 int index;
5447 } QEMUOption;
5449 const QEMUOption qemu_options[] = {
5450 { "h", 0, QEMU_OPTION_h },
5452 { "M", HAS_ARG, QEMU_OPTION_M },
5453 { "fda", HAS_ARG, QEMU_OPTION_fda },
5454 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5455 #ifndef CONFIG_DM
5456 { "hda", HAS_ARG, QEMU_OPTION_hda },
5457 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5458 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5459 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5460 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5461 #endif /* !CONFIG_DM */
5462 { "boot", HAS_ARG, QEMU_OPTION_boot },
5463 { "snapshot", 0, QEMU_OPTION_snapshot },
5464 #ifdef TARGET_I386
5465 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5466 #endif
5467 { "m", HAS_ARG, QEMU_OPTION_m },
5468 { "nographic", 0, QEMU_OPTION_nographic },
5469 { "k", HAS_ARG, QEMU_OPTION_k },
5470 #ifdef HAS_AUDIO
5471 { "audio-help", 0, QEMU_OPTION_audio_help },
5472 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5473 #endif
5475 { "net", HAS_ARG, QEMU_OPTION_net},
5476 #ifdef CONFIG_SLIRP
5477 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5478 #ifndef _WIN32
5479 { "smb", HAS_ARG, QEMU_OPTION_smb },
5480 #endif
5481 { "redir", HAS_ARG, QEMU_OPTION_redir },
5482 #endif
5484 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5485 { "append", HAS_ARG, QEMU_OPTION_append },
5486 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5488 { "S", 0, QEMU_OPTION_S },
5489 { "s", 0, QEMU_OPTION_s },
5490 { "p", HAS_ARG, QEMU_OPTION_p },
5491 { "l", HAS_ARG, QEMU_OPTION_l },
5492 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5493 { "L", HAS_ARG, QEMU_OPTION_L },
5494 #ifdef USE_CODE_COPY
5495 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5496 #endif
5497 #ifdef USE_KQEMU
5498 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5499 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5500 #endif
5501 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5502 { "g", 1, QEMU_OPTION_g },
5503 #endif
5504 { "localtime", 0, QEMU_OPTION_localtime },
5505 { "std-vga", 0, QEMU_OPTION_std_vga },
5506 { "monitor", 1, QEMU_OPTION_monitor },
5507 { "domain-name", 1, QEMU_OPTION_domainname },
5508 { "serial", 1, QEMU_OPTION_serial },
5509 { "parallel", 1, QEMU_OPTION_parallel },
5510 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5511 { "full-screen", 0, QEMU_OPTION_full_screen },
5512 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5513 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5514 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5515 { "smp", HAS_ARG, QEMU_OPTION_smp },
5516 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5517 { "vncviewer", 0, QEMU_OPTION_vncviewer },
5518 { "vncunused", 0, QEMU_OPTION_vncunused },
5520 /* temporary options */
5521 { "usb", 0, QEMU_OPTION_usb },
5522 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5523 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5525 { "d", HAS_ARG, QEMU_OPTION_d },
5526 { "vcpus", 1, QEMU_OPTION_vcpus },
5527 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
5528 { "acpi", 0, QEMU_OPTION_acpi },
5529 { NULL },
5530 };
5532 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5534 /* this stack is only used during signal handling */
5535 #define SIGNAL_STACK_SIZE 32768
5537 static uint8_t *signal_stack;
5539 #endif
5541 /* password input */
5543 static BlockDriverState *get_bdrv(int index)
5545 BlockDriverState *bs;
5547 if (index < 4) {
5548 bs = bs_table[index];
5549 } else if (index < 6) {
5550 bs = fd_table[index - 4];
5551 } else {
5552 bs = NULL;
5554 return bs;
5557 static void read_passwords(void)
5559 BlockDriverState *bs;
5560 int i, j;
5561 char password[256];
5563 for(i = 0; i < 6; i++) {
5564 bs = get_bdrv(i);
5565 if (bs && bdrv_is_encrypted(bs)) {
5566 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5567 for(j = 0; j < 3; j++) {
5568 monitor_readline("Password: ",
5569 1, password, sizeof(password));
5570 if (bdrv_set_key(bs, password) == 0)
5571 break;
5572 term_printf("invalid password\n");
5578 /* XXX: currently we cannot use simultaneously different CPUs */
5579 void register_machines(void)
5581 #if defined(TARGET_I386)
5582 qemu_register_machine(&pc_machine);
5583 qemu_register_machine(&isapc_machine);
5584 #elif defined(TARGET_PPC)
5585 qemu_register_machine(&heathrow_machine);
5586 qemu_register_machine(&core99_machine);
5587 qemu_register_machine(&prep_machine);
5588 #elif defined(TARGET_MIPS)
5589 qemu_register_machine(&mips_machine);
5590 #elif defined(TARGET_SPARC)
5591 #ifdef TARGET_SPARC64
5592 qemu_register_machine(&sun4u_machine);
5593 #else
5594 qemu_register_machine(&sun4m_machine);
5595 #endif
5596 #elif defined(TARGET_ARM)
5597 qemu_register_machine(&integratorcp926_machine);
5598 qemu_register_machine(&integratorcp1026_machine);
5599 qemu_register_machine(&versatilepb_machine);
5600 qemu_register_machine(&versatileab_machine);
5601 #elif defined(TARGET_SH4)
5602 qemu_register_machine(&shix_machine);
5603 #else
5604 #error unsupported CPU
5605 #endif
5608 #ifdef HAS_AUDIO
5609 struct soundhw soundhw[] = {
5610 #ifndef CONFIG_DM
5611 #ifdef TARGET_I386
5613 "pcspk",
5614 "PC speaker",
5615 0,
5616 1,
5617 { .init_isa = pcspk_audio_init }
5618 },
5619 #endif
5620 #endif /* !CONFIG_DM */
5622 "sb16",
5623 "Creative Sound Blaster 16",
5624 0,
5625 1,
5626 { .init_isa = SB16_init }
5627 },
5629 #ifdef CONFIG_ADLIB
5631 "adlib",
5632 #ifdef HAS_YMF262
5633 "Yamaha YMF262 (OPL3)",
5634 #else
5635 "Yamaha YM3812 (OPL2)",
5636 #endif
5637 0,
5638 1,
5639 { .init_isa = Adlib_init }
5640 },
5641 #endif
5643 #ifdef CONFIG_GUS
5645 "gus",
5646 "Gravis Ultrasound GF1",
5647 0,
5648 1,
5649 { .init_isa = GUS_init }
5650 },
5651 #endif
5654 "es1370",
5655 "ENSONIQ AudioPCI ES1370",
5656 0,
5657 0,
5658 { .init_pci = es1370_init }
5659 },
5661 { NULL, NULL, 0, 0, { NULL } }
5662 };
5664 static void select_soundhw (const char *optarg)
5666 struct soundhw *c;
5668 if (*optarg == '?') {
5669 show_valid_cards:
5671 printf ("Valid sound card names (comma separated):\n");
5672 for (c = soundhw; c->name; ++c) {
5673 printf ("%-11s %s\n", c->name, c->descr);
5675 printf ("\n-soundhw all will enable all of the above\n");
5676 exit (*optarg != '?');
5678 else {
5679 size_t l;
5680 const char *p;
5681 char *e;
5682 int bad_card = 0;
5684 if (!strcmp (optarg, "all")) {
5685 for (c = soundhw; c->name; ++c) {
5686 c->enabled = 1;
5688 return;
5691 p = optarg;
5692 while (*p) {
5693 e = strchr (p, ',');
5694 l = !e ? strlen (p) : (size_t) (e - p);
5696 for (c = soundhw; c->name; ++c) {
5697 if (!strncmp (c->name, p, l)) {
5698 c->enabled = 1;
5699 break;
5703 if (!c->name) {
5704 if (l > 80) {
5705 fprintf (stderr,
5706 "Unknown sound card name (too big to show)\n");
5708 else {
5709 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5710 (int) l, p);
5712 bad_card = 1;
5714 p += l + (e != NULL);
5717 if (bad_card)
5718 goto show_valid_cards;
5721 #endif
5723 #ifdef _WIN32
5724 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5726 exit(STATUS_CONTROL_C_EXIT);
5727 return TRUE;
5729 #endif
5731 #define MAX_NET_CLIENTS 32
5733 #include <xg_private.h>
5735 /* FIXME Flush the shadow page */
5736 int unset_mm_mapping(int xc_handle, uint32_t domid,
5737 unsigned long nr_pages, unsigned int address_bits,
5738 xen_pfn_t *extent_start)
5740 int err = 0;
5741 xc_dominfo_t info;
5743 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5744 nr_pages, 0, extent_start);
5745 if (err)
5746 fprintf(stderr, "Failed to decrease physmap\n");
5748 xc_domain_getinfo(xc_handle, domid, 1, &info);
5750 if ((info.nr_pages - nr_pages) <= 0) {
5751 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5752 err = -1;
5755 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5756 PAGE_SIZE/1024) != 0) {
5757 fprintf(logfile, "set maxmem returned error %d\n", errno);
5758 err = -1;
5761 return err;
5764 int set_mm_mapping(int xc_handle, uint32_t domid,
5765 unsigned long nr_pages, unsigned int address_bits,
5766 xen_pfn_t *extent_start)
5768 #if 0
5769 int i;
5770 #endif
5771 xc_dominfo_t info;
5772 int err = 0;
5774 xc_domain_getinfo(xc_handle, domid, 1, &info);
5776 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5777 nr_pages * PAGE_SIZE/1024) != 0) {
5778 fprintf(logfile, "set maxmem returned error %d\n", errno);
5779 return -1;
5782 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5783 address_bits, extent_start);
5784 if (err) {
5785 fprintf(stderr, "Failed to populate physmap\n");
5786 return -1;
5789 err = xc_domain_translate_gpfn_list(xc_handle, domid, nr_pages,
5790 extent_start, extent_start);
5791 if (err) {
5792 fprintf(stderr, "Failed to translate gpfn list\n");
5793 return -1;
5796 #if 0 /* Generates lots of log file output - turn on for debugging */
5797 for (i = 0; i < nr_pages; i++)
5798 fprintf(stderr, "set_map result i %x result %lx\n", i,
5799 extent_start[i]);
5800 #endif
5802 return 0;
5805 int main(int argc, char **argv)
5807 #ifdef CONFIG_GDBSTUB
5808 int use_gdbstub, gdbstub_port;
5809 #endif
5810 int i;
5811 #ifndef CONFIG_DM
5812 int cdrom_index;
5813 #endif /* !CONFIG_DM */
5814 int snapshot, linux_boot;
5815 const char *initrd_filename;
5816 #ifndef CONFIG_DM
5817 const char *hd_filename[MAX_DISKS];
5818 #endif /* !CONFIG_DM */
5819 const char *fd_filename[MAX_FD];
5820 const char *kernel_filename, *kernel_cmdline;
5821 DisplayState *ds = &display_state;
5822 int cyls, heads, secs, translation;
5823 int start_emulation = 1;
5824 char net_clients[MAX_NET_CLIENTS][256];
5825 int nb_net_clients;
5826 int optind;
5827 const char *r, *optarg;
5828 CharDriverState *monitor_hd;
5829 char monitor_device[128];
5830 char serial_devices[MAX_SERIAL_PORTS][128];
5831 int serial_device_index;
5832 char parallel_devices[MAX_PARALLEL_PORTS][128];
5833 int parallel_device_index;
5834 const char *loadvm = NULL;
5835 QEMUMachine *machine;
5836 char usb_devices[MAX_USB_CMDLINE][128];
5837 int usb_devices_index;
5838 unsigned long nr_pages;
5839 xen_pfn_t *page_array;
5840 extern void *shared_page;
5841 extern void *buffered_io_page;
5843 char qemu_dm_logfilename[64];
5845 LIST_INIT (&vm_change_state_head);
5846 #ifndef _WIN32
5848 struct sigaction act;
5849 sigfillset(&act.sa_mask);
5850 act.sa_flags = 0;
5851 act.sa_handler = SIG_IGN;
5852 sigaction(SIGPIPE, &act, NULL);
5854 #else
5855 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5856 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5857 QEMU to run on a single CPU */
5859 HANDLE h;
5860 DWORD mask, smask;
5861 int i;
5862 h = GetCurrentProcess();
5863 if (GetProcessAffinityMask(h, &mask, &smask)) {
5864 for(i = 0; i < 32; i++) {
5865 if (mask & (1 << i))
5866 break;
5868 if (i != 32) {
5869 mask = 1 << i;
5870 SetProcessAffinityMask(h, mask);
5874 #endif
5876 register_machines();
5877 machine = first_machine;
5878 initrd_filename = NULL;
5879 for(i = 0; i < MAX_FD; i++)
5880 fd_filename[i] = NULL;
5881 #ifndef CONFIG_DM
5882 for(i = 0; i < MAX_DISKS; i++)
5883 hd_filename[i] = NULL;
5884 #endif /* !CONFIG_DM */
5885 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5886 vga_ram_size = VGA_RAM_SIZE;
5887 bios_size = BIOS_SIZE;
5888 #ifdef CONFIG_GDBSTUB
5889 use_gdbstub = 0;
5890 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5891 #endif
5892 snapshot = 0;
5893 nographic = 0;
5894 vncviewer = 0;
5895 vncunused = 0;
5896 kernel_filename = NULL;
5897 kernel_cmdline = "";
5898 #ifndef CONFIG_DM
5899 #ifdef TARGET_PPC
5900 cdrom_index = 1;
5901 #else
5902 cdrom_index = 2;
5903 #endif
5904 #endif /* !CONFIG_DM */
5905 cyls = heads = secs = 0;
5906 translation = BIOS_ATA_TRANSLATION_AUTO;
5907 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5909 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5910 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5911 serial_devices[i][0] = '\0';
5912 serial_device_index = 0;
5914 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5915 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5916 parallel_devices[i][0] = '\0';
5917 parallel_device_index = 0;
5919 usb_devices_index = 0;
5921 nb_net_clients = 0;
5923 nb_nics = 0;
5924 /* default mac address of the first network interface */
5926 /* init debug */
5927 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
5928 cpu_set_log_filename(qemu_dm_logfilename);
5929 cpu_set_log(0);
5931 optind = 1;
5932 for(;;) {
5933 if (optind >= argc)
5934 break;
5935 r = argv[optind];
5936 if (r[0] != '-') {
5937 #ifndef CONFIG_DM
5938 hd_filename[0] = argv[optind++];
5939 #else
5940 help();
5941 #endif /* !CONFIG_DM */
5942 } else {
5943 const QEMUOption *popt;
5945 optind++;
5946 popt = qemu_options;
5947 for(;;) {
5948 if (!popt->name) {
5949 fprintf(stderr, "%s: invalid option -- '%s'\n",
5950 argv[0], r);
5951 exit(1);
5953 if (!strcmp(popt->name, r + 1))
5954 break;
5955 popt++;
5957 if (popt->flags & HAS_ARG) {
5958 if (optind >= argc) {
5959 fprintf(stderr, "%s: option '%s' requires an argument\n",
5960 argv[0], r);
5961 exit(1);
5963 optarg = argv[optind++];
5964 } else {
5965 optarg = NULL;
5968 switch(popt->index) {
5969 case QEMU_OPTION_M:
5970 machine = find_machine(optarg);
5971 if (!machine) {
5972 QEMUMachine *m;
5973 printf("Supported machines are:\n");
5974 for(m = first_machine; m != NULL; m = m->next) {
5975 printf("%-10s %s%s\n",
5976 m->name, m->desc,
5977 m == first_machine ? " (default)" : "");
5979 exit(1);
5981 break;
5982 case QEMU_OPTION_initrd:
5983 initrd_filename = optarg;
5984 break;
5985 #ifndef CONFIG_DM
5986 case QEMU_OPTION_hda:
5987 case QEMU_OPTION_hdb:
5988 case QEMU_OPTION_hdc:
5989 case QEMU_OPTION_hdd:
5991 int hd_index;
5992 hd_index = popt->index - QEMU_OPTION_hda;
5993 hd_filename[hd_index] = optarg;
5994 if (hd_index == cdrom_index)
5995 cdrom_index = -1;
5997 break;
5998 #endif /* !CONFIG_DM */
5999 case QEMU_OPTION_snapshot:
6000 snapshot = 1;
6001 break;
6002 case QEMU_OPTION_hdachs:
6004 const char *p;
6005 p = optarg;
6006 cyls = strtol(p, (char **)&p, 0);
6007 if (cyls < 1 || cyls > 16383)
6008 goto chs_fail;
6009 if (*p != ',')
6010 goto chs_fail;
6011 p++;
6012 heads = strtol(p, (char **)&p, 0);
6013 if (heads < 1 || heads > 16)
6014 goto chs_fail;
6015 if (*p != ',')
6016 goto chs_fail;
6017 p++;
6018 secs = strtol(p, (char **)&p, 0);
6019 if (secs < 1 || secs > 63)
6020 goto chs_fail;
6021 if (*p == ',') {
6022 p++;
6023 if (!strcmp(p, "none"))
6024 translation = BIOS_ATA_TRANSLATION_NONE;
6025 else if (!strcmp(p, "lba"))
6026 translation = BIOS_ATA_TRANSLATION_LBA;
6027 else if (!strcmp(p, "auto"))
6028 translation = BIOS_ATA_TRANSLATION_AUTO;
6029 else
6030 goto chs_fail;
6031 } else if (*p != '\0') {
6032 chs_fail:
6033 fprintf(stderr, "qemu: invalid physical CHS format\n");
6034 exit(1);
6037 break;
6038 case QEMU_OPTION_nographic:
6039 if(!strcmp(monitor_device, "vc"))
6040 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6041 if(!strcmp(serial_devices[0], "vc"))
6042 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
6043 "null");
6044 nographic = 1;
6045 break;
6046 case QEMU_OPTION_kernel:
6047 kernel_filename = optarg;
6048 break;
6049 case QEMU_OPTION_append:
6050 kernel_cmdline = optarg;
6051 break;
6052 #ifndef CONFIG_DM
6053 case QEMU_OPTION_cdrom:
6054 if (cdrom_index >= 0) {
6055 hd_filename[cdrom_index] = optarg;
6057 break;
6058 #endif /* !CONFIG_DM */
6059 case QEMU_OPTION_boot:
6060 boot_device = optarg[0];
6061 if (boot_device != 'a' &&
6062 #ifdef TARGET_SPARC
6063 // Network boot
6064 boot_device != 'n' &&
6065 #endif
6066 boot_device != 'c' && boot_device != 'd') {
6067 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6068 exit(1);
6070 break;
6071 case QEMU_OPTION_fda:
6072 fd_filename[0] = optarg;
6073 break;
6074 case QEMU_OPTION_fdb:
6075 fd_filename[1] = optarg;
6076 break;
6077 #ifdef TARGET_I386
6078 case QEMU_OPTION_no_fd_bootchk:
6079 fd_bootchk = 0;
6080 break;
6081 #endif
6082 #ifdef USE_CODE_COPY
6083 case QEMU_OPTION_no_code_copy:
6084 code_copy_enabled = 0;
6085 break;
6086 #endif
6087 case QEMU_OPTION_net:
6088 if (nb_net_clients >= MAX_NET_CLIENTS) {
6089 fprintf(stderr, "qemu: too many network clients\n");
6090 exit(1);
6092 pstrcpy(net_clients[nb_net_clients],
6093 sizeof(net_clients[0]),
6094 optarg);
6095 nb_net_clients++;
6096 break;
6097 #ifdef CONFIG_SLIRP
6098 case QEMU_OPTION_tftp:
6099 tftp_prefix = optarg;
6100 break;
6101 #ifndef _WIN32
6102 case QEMU_OPTION_smb:
6103 net_slirp_smb(optarg);
6104 break;
6105 #endif
6106 case QEMU_OPTION_redir:
6107 net_slirp_redir(optarg);
6108 break;
6109 #endif
6110 #ifdef HAS_AUDIO
6111 case QEMU_OPTION_audio_help:
6112 AUD_help ();
6113 exit (0);
6114 break;
6115 case QEMU_OPTION_soundhw:
6116 select_soundhw (optarg);
6117 break;
6118 #endif
6119 case QEMU_OPTION_h:
6120 help();
6121 break;
6122 case QEMU_OPTION_m:
6123 ram_size = atol(optarg) * 1024 * 1024;
6124 if (ram_size <= 0)
6125 help();
6126 #ifndef CONFIG_DM
6127 if (ram_size > PHYS_RAM_MAX_SIZE) {
6128 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6129 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6130 exit(1);
6132 #endif /* !CONFIG_DM */
6133 break;
6134 case QEMU_OPTION_l:
6136 int mask;
6137 CPULogItem *item;
6139 mask = cpu_str_to_log_mask(optarg);
6140 if (!mask) {
6141 printf("Log items (comma separated):\n");
6142 for(item = cpu_log_items; item->mask != 0; item++) {
6143 printf("%-10s %s\n", item->name, item->help);
6145 exit(1);
6147 cpu_set_log(mask);
6149 break;
6150 #ifdef CONFIG_GDBSTUB
6151 case QEMU_OPTION_s:
6152 use_gdbstub = 1;
6153 break;
6154 case QEMU_OPTION_p:
6155 gdbstub_port = atoi(optarg);
6156 break;
6157 #endif
6158 case QEMU_OPTION_L:
6159 bios_dir = optarg;
6160 break;
6161 case QEMU_OPTION_S:
6162 start_emulation = 0;
6163 break;
6164 case QEMU_OPTION_k:
6165 keyboard_layout = optarg;
6166 break;
6167 case QEMU_OPTION_localtime:
6168 rtc_utc = 0;
6169 break;
6170 case QEMU_OPTION_cirrusvga:
6171 cirrus_vga_enabled = 1;
6172 break;
6173 case QEMU_OPTION_std_vga:
6174 cirrus_vga_enabled = 0;
6175 break;
6176 case QEMU_OPTION_g:
6178 const char *p;
6179 int w, h, depth;
6180 p = optarg;
6181 w = strtol(p, (char **)&p, 10);
6182 if (w <= 0) {
6183 graphic_error:
6184 fprintf(stderr, "qemu: invalid resolution or depth\n");
6185 exit(1);
6187 if (*p != 'x')
6188 goto graphic_error;
6189 p++;
6190 h = strtol(p, (char **)&p, 10);
6191 if (h <= 0)
6192 goto graphic_error;
6193 if (*p == 'x') {
6194 p++;
6195 depth = strtol(p, (char **)&p, 10);
6196 if (depth != 8 && depth != 15 && depth != 16 &&
6197 depth != 24 && depth != 32)
6198 goto graphic_error;
6199 } else if (*p == '\0') {
6200 depth = graphic_depth;
6201 } else {
6202 goto graphic_error;
6205 graphic_width = w;
6206 graphic_height = h;
6207 graphic_depth = depth;
6209 break;
6210 case QEMU_OPTION_monitor:
6211 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6212 break;
6213 case QEMU_OPTION_serial:
6214 if (serial_device_index >= MAX_SERIAL_PORTS) {
6215 fprintf(stderr, "qemu: too many serial ports\n");
6216 exit(1);
6218 pstrcpy(serial_devices[serial_device_index],
6219 sizeof(serial_devices[0]), optarg);
6220 serial_device_index++;
6221 break;
6222 case QEMU_OPTION_parallel:
6223 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6224 fprintf(stderr, "qemu: too many parallel ports\n");
6225 exit(1);
6227 pstrcpy(parallel_devices[parallel_device_index],
6228 sizeof(parallel_devices[0]), optarg);
6229 parallel_device_index++;
6230 break;
6231 case QEMU_OPTION_loadvm:
6232 loadvm = optarg;
6233 break;
6234 case QEMU_OPTION_full_screen:
6235 full_screen = 1;
6236 break;
6237 case QEMU_OPTION_pidfile:
6238 create_pidfile(optarg);
6239 break;
6240 #ifdef TARGET_I386
6241 case QEMU_OPTION_win2k_hack:
6242 win2k_install_hack = 1;
6243 break;
6244 #endif
6245 #ifdef USE_KQEMU
6246 case QEMU_OPTION_no_kqemu:
6247 kqemu_allowed = 0;
6248 break;
6249 case QEMU_OPTION_kernel_kqemu:
6250 kqemu_allowed = 2;
6251 break;
6252 #endif
6253 case QEMU_OPTION_usb:
6254 usb_enabled = 1;
6255 break;
6256 case QEMU_OPTION_usbdevice:
6257 usb_enabled = 1;
6258 if (usb_devices_index >= MAX_USB_CMDLINE) {
6259 fprintf(stderr, "Too many USB devices\n");
6260 exit(1);
6262 pstrcpy(usb_devices[usb_devices_index],
6263 sizeof(usb_devices[usb_devices_index]),
6264 optarg);
6265 usb_devices_index++;
6266 break;
6267 case QEMU_OPTION_smp:
6268 smp_cpus = atoi(optarg);
6269 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6270 fprintf(stderr, "Invalid number of CPUs\n");
6271 exit(1);
6273 break;
6274 case QEMU_OPTION_vnc:
6275 vnc_display = atoi(optarg);
6276 if (vnc_display < 0) {
6277 fprintf(stderr, "Invalid VNC display\n");
6278 exit(1);
6280 break;
6281 case QEMU_OPTION_no_acpi:
6282 acpi_enabled = 0;
6283 break;
6284 case QEMU_OPTION_domainname:
6285 strncat(domain_name, optarg, sizeof(domain_name) - 20);
6286 break;
6287 case QEMU_OPTION_d:
6288 domid = atoi(optarg);
6289 fprintf(logfile, "domid: %d\n", domid);
6290 break;
6291 case QEMU_OPTION_vcpus:
6292 vcpus = atoi(optarg);
6293 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
6294 break;
6295 case QEMU_OPTION_timeoffset:
6296 timeoffset = strtol(optarg, NULL, 0);
6297 break;
6298 case QEMU_OPTION_acpi:
6299 acpi_enabled = 1;
6300 break;
6301 case QEMU_OPTION_vncviewer:
6302 vncviewer++;
6303 break;
6304 case QEMU_OPTION_vncunused:
6305 vncunused++;
6306 if (vnc_display == -1)
6307 vnc_display = -2;
6308 break;
6313 #ifdef CONFIG_DM
6314 bdrv_init();
6315 xenstore_parse_domain_config(domid);
6316 #endif /* CONFIG_DM */
6318 #ifdef USE_KQEMU
6319 if (smp_cpus > 1)
6320 kqemu_allowed = 0;
6321 #endif
6322 linux_boot = (kernel_filename != NULL);
6324 #ifndef CONFIG_DM
6325 if (!linux_boot &&
6326 hd_filename[0] == '\0' &&
6327 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6328 fd_filename[0] == '\0')
6329 help();
6331 /* boot to cd by default if no hard disk */
6332 if (hd_filename[0] == '\0' && boot_device == 'c') {
6333 if (fd_filename[0] != '\0')
6334 boot_device = 'a';
6335 else
6336 boot_device = 'd';
6338 #endif /* !CONFIG_DM */
6340 setvbuf(stdout, NULL, _IOLBF, 0);
6342 init_timers();
6343 init_timer_alarm();
6345 #ifdef _WIN32
6346 socket_init();
6347 #endif
6349 #ifndef CONFIG_DM
6350 /* init network clients */
6351 if (nb_net_clients == 0) {
6352 /* if no clients, we use a default config */
6353 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6354 "nic");
6355 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6356 "user");
6357 nb_net_clients = 2;
6359 #endif /* !CONFIG_DM */
6361 for(i = 0;i < nb_net_clients; i++) {
6362 if (net_client_init(net_clients[i]) < 0)
6363 exit(1);
6366 /* init the memory */
6367 phys_ram_size = ram_size + vga_ram_size + bios_size;
6369 #if defined (__ia64__)
6370 if (ram_size > MMIO_START)
6371 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
6372 #endif
6374 #ifdef CONFIG_DM
6376 nr_pages = ram_size/PAGE_SIZE;
6377 xc_handle = xc_interface_open();
6379 page_array = (xen_pfn_t *)malloc(nr_pages * sizeof(xen_pfn_t));
6380 if (page_array == NULL) {
6381 fprintf(logfile, "malloc returned error %d\n", errno);
6382 exit(-1);
6385 #if defined(__i386__) || defined(__x86_64__)
6386 if (xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages) {
6387 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
6388 exit(-1);
6391 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6392 PROT_READ|PROT_WRITE, page_array,
6393 nr_pages - 3);
6394 if (phys_ram_base == 0) {
6395 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6396 exit(-1);
6399 /* not yet add for IA64 */
6400 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6401 PROT_READ|PROT_WRITE,
6402 page_array[nr_pages - 3]);
6404 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6405 PROT_READ|PROT_WRITE,
6406 page_array[nr_pages - 1]);
6408 fprintf(logfile, "shared page at pfn:%lx, mfn: %"PRIx64"\n", nr_pages - 1,
6409 (uint64_t)(page_array[nr_pages - 1]));
6411 free(page_array);
6413 #elif defined(__ia64__)
6415 if (xc_ia64_get_pfn_list(xc_handle, domid, page_array,
6416 IO_PAGE_START >> PAGE_SHIFT, 1) != 1) {
6417 fprintf(logfile, "xc_ia64_get_pfn_list 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[0]);
6425 fprintf(logfile, "shared page at pfn:%lx, mfn: %016lx\n",
6426 IO_PAGE_START >> PAGE_SHIFT, page_array[0]);
6428 if (xc_ia64_get_pfn_list(xc_handle, domid,
6429 page_array, 0, nr_pages) != nr_pages) {
6430 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
6431 exit(-1);
6434 if (ram_size > MMIO_START) {
6435 for (i = 0 ; i < MEM_G >> PAGE_SHIFT; i++)
6436 page_array[MMIO_START >> PAGE_SHIFT + i] =
6437 page_array[IO_PAGE_START >> PAGE_SHIFT + 1];
6440 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6441 PROT_READ|PROT_WRITE,
6442 page_array, nr_pages);
6443 if (phys_ram_base == 0) {
6444 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6445 exit(-1);
6447 #endif
6448 #else /* !CONFIG_DM */
6450 phys_ram_base = qemu_vmalloc(phys_ram_size);
6451 if (!phys_ram_base) {
6452 fprintf(stderr, "Could not allocate physical memory\n");
6453 exit(1);
6456 #endif /* !CONFIG_DM */
6458 #ifndef CONFIG_DM
6459 /* we always create the cdrom drive, even if no disk is there */
6460 bdrv_init();
6461 if (cdrom_index >= 0) {
6462 bs_table[cdrom_index] = bdrv_new("cdrom");
6463 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6466 /* open the virtual block devices */
6467 for(i = 0; i < MAX_DISKS; i++) {
6468 if (hd_filename[i]) {
6469 if (!bs_table[i]) {
6470 char buf[64];
6471 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6472 bs_table[i] = bdrv_new(buf);
6474 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6475 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6476 hd_filename[i]);
6477 exit(1);
6479 if (i == 0 && cyls != 0) {
6480 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6481 bdrv_set_translation_hint(bs_table[i], translation);
6485 #endif /* !CONFIG_DM */
6487 /* we always create at least one floppy disk */
6488 fd_table[0] = bdrv_new("fda");
6489 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6491 for(i = 0; i < MAX_FD; i++) {
6492 if (fd_filename[i]) {
6493 if (!fd_table[i]) {
6494 char buf[64];
6495 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6496 fd_table[i] = bdrv_new(buf);
6497 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6499 if (fd_filename[i] != '\0') {
6500 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6501 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6502 fd_filename[i]);
6503 exit(1);
6509 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6510 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6512 init_ioports();
6514 /* terminal init */
6515 if (nographic) {
6516 dumb_display_init(ds);
6517 } else if (vnc_display != -1) {
6518 vnc_display = vnc_display_init(ds, vnc_display, vncunused);
6519 if (vncviewer)
6520 vnc_start_viewer(vnc_display);
6521 xenstore_write_vncport(vnc_display);
6522 } else {
6523 #if defined(CONFIG_SDL)
6524 sdl_display_init(ds, full_screen);
6525 #elif defined(CONFIG_COCOA)
6526 cocoa_display_init(ds, full_screen);
6527 #else
6528 dumb_display_init(ds);
6529 #endif
6532 monitor_hd = qemu_chr_open(monitor_device);
6533 if (!monitor_hd) {
6534 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6535 exit(1);
6537 monitor_init(monitor_hd, !nographic);
6539 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6540 if (serial_devices[i][0] != '\0') {
6541 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6542 if (!serial_hds[i]) {
6543 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6544 serial_devices[i]);
6545 exit(1);
6547 if (!strcmp(serial_devices[i], "vc"))
6548 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6552 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6553 if (parallel_devices[i][0] != '\0') {
6554 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6555 if (!parallel_hds[i]) {
6556 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6557 parallel_devices[i]);
6558 exit(1);
6560 if (!strcmp(parallel_devices[i], "vc"))
6561 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6565 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6567 machine->init(ram_size, vga_ram_size, boot_device,
6568 ds, fd_filename, snapshot,
6569 kernel_filename, kernel_cmdline, initrd_filename,
6570 timeoffset);
6572 /* init USB devices */
6573 if (usb_enabled) {
6574 for(i = 0; i < usb_devices_index; i++) {
6575 if (usb_device_add(usb_devices[i]) < 0) {
6576 fprintf(stderr, "Warning: could not add USB device %s\n",
6577 usb_devices[i]);
6582 if (vnc_display == -1) {
6583 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6584 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6587 #ifdef CONFIG_GDBSTUB
6588 if (use_gdbstub) {
6589 if (gdbserver_start(gdbstub_port) < 0) {
6590 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6591 gdbstub_port);
6592 exit(1);
6593 } else {
6594 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6596 } else
6597 #endif
6598 if (loadvm)
6599 qemu_loadvm(loadvm);
6602 /* XXX: simplify init */
6603 read_passwords();
6604 if (start_emulation) {
6605 vm_start();
6608 main_loop();
6609 quit_timers();
6610 return 0;