ia64/xen-unstable

view tools/ioemu/vl.c @ 11734:6a8ae4c34abe

[IOEMU] When vncunused is specified, allocate a port from 5900
rather than 5898.
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
author kaf24@firebug.cl.cam.ac.uk
date Wed Oct 04 09:43:45 2006 +0100 (2006-10-04)
parents 7fca81d456b2
children a95dfbc8dca8
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 char *boot_device = NULL;
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 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
729 {
730 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
731 qemu_mod_timer(ts, expire_time);
732 }
734 /* modify the current timer so that it will be fired when current_time
735 >= expire_time. The corresponding callback will be called. */
736 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
737 {
738 QEMUTimer **pt, *t;
740 qemu_del_timer(ts);
742 /* add the timer in the sorted list */
743 /* NOTE: this code must be signal safe because
744 qemu_timer_expired() can be called from a signal. */
745 pt = &active_timers[ts->clock->type];
746 for(;;) {
747 t = *pt;
748 if (!t)
749 break;
750 if (t->expire_time > expire_time)
751 break;
752 pt = &t->next;
753 }
754 ts->expire_time = expire_time;
755 ts->next = *pt;
756 *pt = ts;
757 }
759 int qemu_timer_pending(QEMUTimer *ts)
760 {
761 QEMUTimer *t;
762 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
763 if (t == ts)
764 return 1;
765 }
766 return 0;
767 }
769 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
770 {
771 if (!timer_head)
772 return 0;
773 return (timer_head->expire_time <= current_time);
774 }
776 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
777 {
778 QEMUTimer *ts;
780 for(;;) {
781 ts = *ptimer_head;
782 if (!ts || ts->expire_time > current_time)
783 break;
784 /* remove timer from the list before calling the callback */
785 *ptimer_head = ts->next;
786 ts->next = NULL;
788 /* run the callback (the timer list can be modified) */
789 ts->cb(ts->opaque);
790 }
791 }
793 int64_t qemu_get_clock(QEMUClock *clock)
794 {
795 switch(clock->type) {
796 case QEMU_TIMER_REALTIME:
797 return get_clock() / 1000000;
798 default:
799 case QEMU_TIMER_VIRTUAL:
800 return cpu_get_clock();
801 }
802 }
804 static void init_timers(void)
805 {
806 init_get_clock();
807 ticks_per_sec = QEMU_TIMER_BASE;
808 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
809 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
810 }
812 /* save a timer */
813 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
814 {
815 uint64_t expire_time;
817 if (qemu_timer_pending(ts)) {
818 expire_time = ts->expire_time;
819 } else {
820 expire_time = -1;
821 }
822 qemu_put_be64(f, expire_time);
823 }
825 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
826 {
827 uint64_t expire_time;
829 expire_time = qemu_get_be64(f);
830 if (expire_time != -1) {
831 qemu_mod_timer(ts, expire_time);
832 } else {
833 qemu_del_timer(ts);
834 }
835 }
837 #ifdef CONFIG_DM
838 static void timer_save(QEMUFile *f, void *opaque)
839 {
840 }
842 static int timer_load(QEMUFile *f, void *opaque, int version_id)
843 {
844 return 0;
845 }
846 #else /* !CONFIG_DM */
847 static void timer_save(QEMUFile *f, void *opaque)
848 {
849 if (cpu_ticks_enabled) {
850 hw_error("cannot save state if virtual timers are running");
851 }
852 qemu_put_be64s(f, &cpu_ticks_offset);
853 qemu_put_be64s(f, &ticks_per_sec);
854 }
856 static int timer_load(QEMUFile *f, void *opaque, int version_id)
857 {
858 if (version_id != 1)
859 return -EINVAL;
860 if (cpu_ticks_enabled) {
861 return -EINVAL;
862 }
863 qemu_get_be64s(f, &cpu_ticks_offset);
864 qemu_get_be64s(f, &ticks_per_sec);
865 return 0;
866 }
868 #ifdef _WIN32
869 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
870 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
871 #else
872 static void host_alarm_handler(int host_signum)
873 #endif
874 {
875 #if 0
876 #define DISP_FREQ 1000
877 {
878 static int64_t delta_min = INT64_MAX;
879 static int64_t delta_max, delta_cum, last_clock, delta, ti;
880 static int count;
881 ti = qemu_get_clock(vm_clock);
882 if (last_clock != 0) {
883 delta = ti - last_clock;
884 if (delta < delta_min)
885 delta_min = delta;
886 if (delta > delta_max)
887 delta_max = delta;
888 delta_cum += delta;
889 if (++count == DISP_FREQ) {
890 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
891 muldiv64(delta_min, 1000000, ticks_per_sec),
892 muldiv64(delta_max, 1000000, ticks_per_sec),
893 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
894 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
895 count = 0;
896 delta_min = INT64_MAX;
897 delta_max = 0;
898 delta_cum = 0;
899 }
900 }
901 last_clock = ti;
902 }
903 #endif
904 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
905 qemu_get_clock(vm_clock)) ||
906 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
907 qemu_get_clock(rt_clock))) {
908 #ifdef _WIN32
909 SetEvent(host_alarm);
910 #endif
911 CPUState *env = cpu_single_env;
912 if (env) {
913 /* stop the currently executing cpu because a timer occured */
914 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
915 #ifdef USE_KQEMU
916 if (env->kqemu_enabled) {
917 kqemu_cpu_interrupt(env);
918 }
919 #endif
920 }
921 }
922 }
924 #ifndef _WIN32
926 #if defined(__linux__)
928 #define RTC_FREQ 1024
930 static int rtc_fd;
932 static int start_rtc_timer(void)
933 {
934 rtc_fd = open("/dev/rtc", O_RDONLY);
935 if (rtc_fd < 0)
936 return -1;
937 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
938 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
939 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
940 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
941 goto fail;
942 }
943 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
944 fail:
945 close(rtc_fd);
946 return -1;
947 }
948 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
949 return 0;
950 }
952 #else
954 static int start_rtc_timer(void)
955 {
956 return -1;
957 }
959 #endif /* !defined(__linux__) */
961 #endif /* !defined(_WIN32) */
963 #endif /* !CONFIG_DM */
965 static void init_timer_alarm(void)
966 {
967 #ifdef _WIN32
968 {
969 int count=0;
970 TIMECAPS tc;
972 ZeroMemory(&tc, sizeof(TIMECAPS));
973 timeGetDevCaps(&tc, sizeof(TIMECAPS));
974 if (period < tc.wPeriodMin)
975 period = tc.wPeriodMin;
976 timeBeginPeriod(period);
977 timerID = timeSetEvent(1, // interval (ms)
978 period, // resolution
979 host_alarm_handler, // function
980 (DWORD)&count, // user parameter
981 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
982 if( !timerID ) {
983 perror("failed timer alarm");
984 exit(1);
985 }
986 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
987 if (!host_alarm) {
988 perror("failed CreateEvent");
989 exit(1);
990 }
991 qemu_add_wait_object(host_alarm, NULL, NULL);
992 }
993 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
994 #else
995 {
996 #ifndef CONFIG_DM
997 struct sigaction act;
998 struct itimerval itv;
999 #endif
1001 /* get times() syscall frequency */
1002 timer_freq = sysconf(_SC_CLK_TCK);
1004 #ifndef CONFIG_DM
1005 /* timer signal */
1006 sigfillset(&act.sa_mask);
1007 act.sa_flags = 0;
1008 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1009 act.sa_flags |= SA_ONSTACK;
1010 #endif
1011 act.sa_handler = host_alarm_handler;
1012 sigaction(SIGALRM, &act, NULL);
1014 itv.it_interval.tv_sec = 0;
1015 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1016 itv.it_value.tv_sec = 0;
1017 itv.it_value.tv_usec = 10 * 1000;
1018 setitimer(ITIMER_REAL, &itv, NULL);
1019 /* we probe the tick duration of the kernel to inform the user if
1020 the emulated kernel requested a too high timer frequency */
1021 getitimer(ITIMER_REAL, &itv);
1023 #if defined(__linux__)
1024 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1025 have timers with 1 ms resolution. The correct solution will
1026 be to use the POSIX real time timers available in recent
1027 2.6 kernels */
1028 if (itv.it_interval.tv_usec > 1000 || 1) {
1029 /* try to use /dev/rtc to have a faster timer */
1030 if (start_rtc_timer() < 0)
1031 goto use_itimer;
1032 /* disable itimer */
1033 itv.it_interval.tv_sec = 0;
1034 itv.it_interval.tv_usec = 0;
1035 itv.it_value.tv_sec = 0;
1036 itv.it_value.tv_usec = 0;
1037 setitimer(ITIMER_REAL, &itv, NULL);
1039 /* use the RTC */
1040 sigaction(SIGIO, &act, NULL);
1041 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1042 fcntl(rtc_fd, F_SETOWN, getpid());
1043 } else
1044 #endif /* defined(__linux__) */
1046 use_itimer:
1047 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1048 PIT_FREQ) / 1000000;
1050 #endif /* CONFIG_DM */
1052 #endif
1055 void quit_timers(void)
1057 #ifdef _WIN32
1058 timeKillEvent(timerID);
1059 timeEndPeriod(period);
1060 if (host_alarm) {
1061 CloseHandle(host_alarm);
1062 host_alarm = NULL;
1064 #endif
1067 /***********************************************************/
1068 /* character device */
1070 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1072 return s->chr_write(s, buf, len);
1075 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1077 if (!s->chr_ioctl)
1078 return -ENOTSUP;
1079 return s->chr_ioctl(s, cmd, arg);
1082 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1084 char buf[4096];
1085 va_list ap;
1086 va_start(ap, fmt);
1087 vsnprintf(buf, sizeof(buf), fmt, ap);
1088 qemu_chr_write(s, buf, strlen(buf));
1089 va_end(ap);
1092 void qemu_chr_send_event(CharDriverState *s, int event)
1094 if (s->chr_send_event)
1095 s->chr_send_event(s, event);
1098 void qemu_chr_add_read_handler(CharDriverState *s,
1099 IOCanRWHandler *fd_can_read,
1100 IOReadHandler *fd_read, void *opaque)
1102 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1105 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1107 s->chr_event = chr_event;
1110 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1112 return len;
1115 static void null_chr_add_read_handler(CharDriverState *chr,
1116 IOCanRWHandler *fd_can_read,
1117 IOReadHandler *fd_read, void *opaque)
1121 CharDriverState *qemu_chr_open_null(void)
1123 CharDriverState *chr;
1125 chr = qemu_mallocz(sizeof(CharDriverState));
1126 if (!chr)
1127 return NULL;
1128 chr->chr_write = null_chr_write;
1129 chr->chr_add_read_handler = null_chr_add_read_handler;
1130 return chr;
1133 #ifdef _WIN32
1135 static void socket_cleanup(void)
1137 WSACleanup();
1140 static int socket_init(void)
1142 WSADATA Data;
1143 int ret, err;
1145 ret = WSAStartup(MAKEWORD(2,2), &Data);
1146 if (ret != 0) {
1147 err = WSAGetLastError();
1148 fprintf(stderr, "WSAStartup: %d\n", err);
1149 return -1;
1151 atexit(socket_cleanup);
1152 return 0;
1155 static int send_all(int fd, const uint8_t *buf, int len1)
1157 int ret, len;
1159 len = len1;
1160 while (len > 0) {
1161 ret = send(fd, buf, len, 0);
1162 if (ret < 0) {
1163 int errno;
1164 errno = WSAGetLastError();
1165 if (errno != WSAEWOULDBLOCK) {
1166 return -1;
1168 } else if (ret == 0) {
1169 break;
1170 } else {
1171 buf += ret;
1172 len -= ret;
1175 return len1 - len;
1178 void socket_set_nonblock(int fd)
1180 unsigned long opt = 1;
1181 ioctlsocket(fd, FIONBIO, &opt);
1184 #else
1186 static int unix_write(int fd, const uint8_t *buf, int len1)
1188 int ret, sel_ret, len;
1189 int max_fd;
1190 fd_set writefds;
1191 struct timeval timeout;
1193 max_fd = fd;
1195 len = len1;
1196 while (len > 0) {
1197 FD_ZERO(&writefds);
1198 FD_SET(fd, &writefds);
1199 timeout.tv_sec = 0;
1200 timeout.tv_usec = 0;
1201 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1202 if (sel_ret <= 0) {
1203 /* Timeout or select error */
1204 return -1;
1205 } else {
1206 ret = write(fd, buf, len);
1207 if (ret < 0) {
1208 if (errno != EINTR && errno != EAGAIN)
1209 return -1;
1210 } else if (ret == 0) {
1211 break;
1212 } else {
1213 buf += ret;
1214 len -= ret;
1218 return len1 - len;
1221 static inline int send_all(int fd, const uint8_t *buf, int len1)
1223 return unix_write(fd, buf, len1);
1226 void socket_set_nonblock(int fd)
1228 fcntl(fd, F_SETFL, O_NONBLOCK);
1230 #endif /* !_WIN32 */
1232 #ifndef _WIN32
1234 typedef struct {
1235 int fd_in, fd_out;
1236 IOCanRWHandler *fd_can_read;
1237 IOReadHandler *fd_read;
1238 void *fd_opaque;
1239 int max_size;
1240 } FDCharDriver;
1242 #define STDIO_MAX_CLIENTS 2
1244 static int stdio_nb_clients;
1245 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1247 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1249 FDCharDriver *s = chr->opaque;
1250 return unix_write(s->fd_out, buf, len);
1253 static int fd_chr_read_poll(void *opaque)
1255 CharDriverState *chr = opaque;
1256 FDCharDriver *s = chr->opaque;
1258 s->max_size = s->fd_can_read(s->fd_opaque);
1259 return s->max_size;
1262 static void fd_chr_read(void *opaque)
1264 CharDriverState *chr = opaque;
1265 FDCharDriver *s = chr->opaque;
1266 int size, len;
1267 uint8_t buf[1024];
1269 len = sizeof(buf);
1270 if (len > s->max_size)
1271 len = s->max_size;
1272 if (len == 0)
1273 return;
1274 size = read(s->fd_in, buf, len);
1275 if (size > 0) {
1276 s->fd_read(s->fd_opaque, buf, size);
1280 static void fd_chr_add_read_handler(CharDriverState *chr,
1281 IOCanRWHandler *fd_can_read,
1282 IOReadHandler *fd_read, void *opaque)
1284 FDCharDriver *s = chr->opaque;
1286 if (s->fd_in >= 0) {
1287 s->fd_can_read = fd_can_read;
1288 s->fd_read = fd_read;
1289 s->fd_opaque = opaque;
1290 if (nographic && s->fd_in == 0) {
1291 } else {
1292 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1293 fd_chr_read, NULL, chr);
1298 /* open a character device to a unix fd */
1299 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1301 CharDriverState *chr;
1302 FDCharDriver *s;
1304 chr = qemu_mallocz(sizeof(CharDriverState));
1305 if (!chr)
1306 return NULL;
1307 s = qemu_mallocz(sizeof(FDCharDriver));
1308 if (!s) {
1309 free(chr);
1310 return NULL;
1312 s->fd_in = fd_in;
1313 s->fd_out = fd_out;
1314 chr->opaque = s;
1315 chr->chr_write = fd_chr_write;
1316 chr->chr_add_read_handler = fd_chr_add_read_handler;
1317 return chr;
1320 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1322 int fd_out;
1324 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1325 if (fd_out < 0)
1326 return NULL;
1327 return qemu_chr_open_fd(-1, fd_out);
1330 CharDriverState *qemu_chr_open_pipe(const char *filename)
1332 int fd;
1334 fd = open(filename, O_RDWR | O_BINARY);
1335 if (fd < 0)
1336 return NULL;
1337 return qemu_chr_open_fd(fd, fd);
1341 /* for STDIO, we handle the case where several clients use it
1342 (nographic mode) */
1344 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1346 #define TERM_FIFO_MAX_SIZE 1
1348 static int term_got_escape, client_index;
1349 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1350 static int term_fifo_size;
1351 static int term_timestamps;
1352 static int64_t term_timestamps_start;
1354 void term_print_help(void)
1356 printf("\n"
1357 "C-a h print this help\n"
1358 "C-a x exit emulator\n"
1359 "C-a s save disk data back to file (if -snapshot)\n"
1360 "C-a b send break (magic sysrq)\n"
1361 "C-a t toggle console timestamps\n"
1362 "C-a c switch between console and monitor\n"
1363 "C-a C-a send C-a\n"
1364 );
1367 /* called when a char is received */
1368 static void stdio_received_byte(int ch)
1370 if (term_got_escape) {
1371 term_got_escape = 0;
1372 switch(ch) {
1373 case 'h':
1374 term_print_help();
1375 break;
1376 case 'x':
1377 exit(0);
1378 break;
1379 case 's':
1381 int i;
1382 for (i = 0; i < MAX_DISKS; i++) {
1383 if (bs_table[i])
1384 bdrv_commit(bs_table[i]);
1387 break;
1388 case 'b':
1389 if (client_index < stdio_nb_clients) {
1390 CharDriverState *chr;
1391 FDCharDriver *s;
1393 chr = stdio_clients[client_index];
1394 s = chr->opaque;
1395 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1397 break;
1398 case 'c':
1399 client_index++;
1400 if (client_index >= stdio_nb_clients)
1401 client_index = 0;
1402 if (client_index == 0) {
1403 /* send a new line in the monitor to get the prompt */
1404 ch = '\r';
1405 goto send_char;
1407 break;
1408 case 't':
1409 term_timestamps = !term_timestamps;
1410 term_timestamps_start = -1;
1411 break;
1412 case TERM_ESCAPE:
1413 goto send_char;
1415 } else if (ch == TERM_ESCAPE) {
1416 term_got_escape = 1;
1417 } else {
1418 send_char:
1419 if (client_index < stdio_nb_clients) {
1420 uint8_t buf[1];
1421 CharDriverState *chr;
1422 FDCharDriver *s;
1424 chr = stdio_clients[client_index];
1425 s = chr->opaque;
1426 if (s->fd_can_read(s->fd_opaque) > 0) {
1427 buf[0] = ch;
1428 s->fd_read(s->fd_opaque, buf, 1);
1429 } else if (term_fifo_size == 0) {
1430 term_fifo[term_fifo_size++] = ch;
1436 static int stdio_read_poll(void *opaque)
1438 CharDriverState *chr;
1439 FDCharDriver *s;
1441 if (client_index < stdio_nb_clients) {
1442 chr = stdio_clients[client_index];
1443 s = chr->opaque;
1444 /* try to flush the queue if needed */
1445 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1446 s->fd_read(s->fd_opaque, term_fifo, 1);
1447 term_fifo_size = 0;
1449 /* see if we can absorb more chars */
1450 if (term_fifo_size == 0)
1451 return 1;
1452 else
1453 return 0;
1454 } else {
1455 return 1;
1459 static void stdio_read(void *opaque)
1461 int size;
1462 uint8_t buf[1];
1464 size = read(0, buf, 1);
1465 if (size > 0)
1466 stdio_received_byte(buf[0]);
1469 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1471 FDCharDriver *s = chr->opaque;
1472 if (!term_timestamps) {
1473 return unix_write(s->fd_out, buf, len);
1474 } else {
1475 int i;
1476 char buf1[64];
1478 for(i = 0; i < len; i++) {
1479 unix_write(s->fd_out, buf + i, 1);
1480 if (buf[i] == '\n') {
1481 int64_t ti;
1482 int secs;
1484 ti = get_clock();
1485 if (term_timestamps_start == -1)
1486 term_timestamps_start = ti;
1487 ti -= term_timestamps_start;
1488 secs = ti / 1000000000;
1489 snprintf(buf1, sizeof(buf1),
1490 "[%02d:%02d:%02d.%03d] ",
1491 secs / 3600,
1492 (secs / 60) % 60,
1493 secs % 60,
1494 (int)((ti / 1000000) % 1000));
1495 unix_write(s->fd_out, buf1, strlen(buf1));
1498 return len;
1502 /* init terminal so that we can grab keys */
1503 static struct termios oldtty;
1504 static int old_fd0_flags;
1506 static void term_exit(void)
1508 tcsetattr (0, TCSANOW, &oldtty);
1509 fcntl(0, F_SETFL, old_fd0_flags);
1512 static void term_init(void)
1514 struct termios tty;
1516 tcgetattr (0, &tty);
1517 oldtty = tty;
1518 old_fd0_flags = fcntl(0, F_GETFL);
1520 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1521 |INLCR|IGNCR|ICRNL|IXON);
1522 tty.c_oflag |= OPOST;
1523 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1524 /* if graphical mode, we allow Ctrl-C handling */
1525 if (nographic)
1526 tty.c_lflag &= ~ISIG;
1527 tty.c_cflag &= ~(CSIZE|PARENB);
1528 tty.c_cflag |= CS8;
1529 tty.c_cc[VMIN] = 1;
1530 tty.c_cc[VTIME] = 0;
1532 tcsetattr (0, TCSANOW, &tty);
1534 atexit(term_exit);
1536 fcntl(0, F_SETFL, O_NONBLOCK);
1539 CharDriverState *qemu_chr_open_stdio(void)
1541 CharDriverState *chr;
1543 if (nographic) {
1544 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1545 return NULL;
1546 chr = qemu_chr_open_fd(0, 1);
1547 chr->chr_write = stdio_write;
1548 if (stdio_nb_clients == 0)
1549 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1550 client_index = stdio_nb_clients;
1551 } else {
1552 if (stdio_nb_clients != 0)
1553 return NULL;
1554 chr = qemu_chr_open_fd(0, 1);
1556 stdio_clients[stdio_nb_clients++] = chr;
1557 if (stdio_nb_clients == 1) {
1558 /* set the terminal in raw mode */
1559 term_init();
1561 return chr;
1564 int store_console_dev(int domid, char *pts)
1566 int xc_handle;
1567 struct xs_handle *xs;
1568 char *path;
1570 xs = xs_daemon_open();
1571 if (xs == NULL) {
1572 fprintf(logfile, "Could not contact XenStore\n");
1573 return -1;
1576 xc_handle = xc_interface_open();
1577 if (xc_handle == -1) {
1578 fprintf(logfile, "xc_interface_open() error\n");
1579 return -1;
1582 path = xs_get_domain_path(xs, domid);
1583 if (path == NULL) {
1584 fprintf(logfile, "xs_get_domain_path() error\n");
1585 return -1;
1587 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1588 if (path == NULL) {
1589 fprintf(logfile, "realloc error\n");
1590 return -1;
1592 strcat(path, "/console/tty");
1593 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1594 fprintf(logfile, "xs_write for console fail");
1595 return -1;
1598 free(path);
1599 xs_daemon_close(xs);
1600 close(xc_handle);
1602 return 0;
1605 #if defined(__linux__)
1606 CharDriverState *qemu_chr_open_pty(void)
1608 struct termios tty;
1609 int master_fd, slave_fd;
1611 /* Not satisfying */
1612 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1613 return NULL;
1616 /* Set raw attributes on the pty. */
1617 cfmakeraw(&tty);
1618 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1620 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1621 store_console_dev(domid, ptsname(master_fd));
1623 return qemu_chr_open_fd(master_fd, master_fd);
1626 static void tty_serial_init(int fd, int speed,
1627 int parity, int data_bits, int stop_bits)
1629 struct termios tty;
1630 speed_t spd;
1632 #if 0
1633 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1634 speed, parity, data_bits, stop_bits);
1635 #endif
1636 tcgetattr (fd, &tty);
1638 switch(speed) {
1639 case 50:
1640 spd = B50;
1641 break;
1642 case 75:
1643 spd = B75;
1644 break;
1645 case 300:
1646 spd = B300;
1647 break;
1648 case 600:
1649 spd = B600;
1650 break;
1651 case 1200:
1652 spd = B1200;
1653 break;
1654 case 2400:
1655 spd = B2400;
1656 break;
1657 case 4800:
1658 spd = B4800;
1659 break;
1660 case 9600:
1661 spd = B9600;
1662 break;
1663 case 19200:
1664 spd = B19200;
1665 break;
1666 case 38400:
1667 spd = B38400;
1668 break;
1669 case 57600:
1670 spd = B57600;
1671 break;
1672 default:
1673 case 115200:
1674 spd = B115200;
1675 break;
1678 cfsetispeed(&tty, spd);
1679 cfsetospeed(&tty, spd);
1681 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1682 |INLCR|IGNCR|ICRNL|IXON);
1683 tty.c_oflag |= OPOST;
1684 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1685 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1686 switch(data_bits) {
1687 default:
1688 case 8:
1689 tty.c_cflag |= CS8;
1690 break;
1691 case 7:
1692 tty.c_cflag |= CS7;
1693 break;
1694 case 6:
1695 tty.c_cflag |= CS6;
1696 break;
1697 case 5:
1698 tty.c_cflag |= CS5;
1699 break;
1701 switch(parity) {
1702 default:
1703 case 'N':
1704 break;
1705 case 'E':
1706 tty.c_cflag |= PARENB;
1707 break;
1708 case 'O':
1709 tty.c_cflag |= PARENB | PARODD;
1710 break;
1713 tcsetattr (fd, TCSANOW, &tty);
1716 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1718 FDCharDriver *s = chr->opaque;
1720 switch(cmd) {
1721 case CHR_IOCTL_SERIAL_SET_PARAMS:
1723 QEMUSerialSetParams *ssp = arg;
1724 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1725 ssp->data_bits, ssp->stop_bits);
1727 break;
1728 case CHR_IOCTL_SERIAL_SET_BREAK:
1730 int enable = *(int *)arg;
1731 if (enable)
1732 tcsendbreak(s->fd_in, 1);
1734 break;
1735 default:
1736 return -ENOTSUP;
1738 return 0;
1741 CharDriverState *qemu_chr_open_tty(const char *filename)
1743 CharDriverState *chr;
1744 int fd;
1746 fd = open(filename, O_RDWR | O_NONBLOCK);
1747 if (fd < 0)
1748 return NULL;
1749 fcntl(fd, F_SETFL, O_NONBLOCK);
1750 tty_serial_init(fd, 115200, 'N', 8, 1);
1751 chr = qemu_chr_open_fd(fd, fd);
1752 if (!chr)
1753 return NULL;
1754 chr->chr_ioctl = tty_serial_ioctl;
1755 return chr;
1758 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1760 int fd = (int)chr->opaque;
1761 uint8_t b;
1763 switch(cmd) {
1764 case CHR_IOCTL_PP_READ_DATA:
1765 if (ioctl(fd, PPRDATA, &b) < 0)
1766 return -ENOTSUP;
1767 *(uint8_t *)arg = b;
1768 break;
1769 case CHR_IOCTL_PP_WRITE_DATA:
1770 b = *(uint8_t *)arg;
1771 if (ioctl(fd, PPWDATA, &b) < 0)
1772 return -ENOTSUP;
1773 break;
1774 case CHR_IOCTL_PP_READ_CONTROL:
1775 if (ioctl(fd, PPRCONTROL, &b) < 0)
1776 return -ENOTSUP;
1777 *(uint8_t *)arg = b;
1778 break;
1779 case CHR_IOCTL_PP_WRITE_CONTROL:
1780 b = *(uint8_t *)arg;
1781 if (ioctl(fd, PPWCONTROL, &b) < 0)
1782 return -ENOTSUP;
1783 break;
1784 case CHR_IOCTL_PP_READ_STATUS:
1785 if (ioctl(fd, PPRSTATUS, &b) < 0)
1786 return -ENOTSUP;
1787 *(uint8_t *)arg = b;
1788 break;
1789 default:
1790 return -ENOTSUP;
1792 return 0;
1795 CharDriverState *qemu_chr_open_pp(const char *filename)
1797 CharDriverState *chr;
1798 int fd;
1800 fd = open(filename, O_RDWR);
1801 if (fd < 0)
1802 return NULL;
1804 if (ioctl(fd, PPCLAIM) < 0) {
1805 close(fd);
1806 return NULL;
1809 chr = qemu_mallocz(sizeof(CharDriverState));
1810 if (!chr) {
1811 close(fd);
1812 return NULL;
1814 chr->opaque = (void *)fd;
1815 chr->chr_write = null_chr_write;
1816 chr->chr_add_read_handler = null_chr_add_read_handler;
1817 chr->chr_ioctl = pp_ioctl;
1818 return chr;
1821 #else
1822 CharDriverState *qemu_chr_open_pty(void)
1824 return NULL;
1826 #endif
1828 #endif /* !defined(_WIN32) */
1830 #ifdef _WIN32
1831 typedef struct {
1832 IOCanRWHandler *fd_can_read;
1833 IOReadHandler *fd_read;
1834 void *win_opaque;
1835 int max_size;
1836 HANDLE hcom, hrecv, hsend;
1837 OVERLAPPED orecv, osend;
1838 BOOL fpipe;
1839 DWORD len;
1840 } WinCharState;
1842 #define NSENDBUF 2048
1843 #define NRECVBUF 2048
1844 #define MAXCONNECT 1
1845 #define NTIMEOUT 5000
1847 static int win_chr_poll(void *opaque);
1848 static int win_chr_pipe_poll(void *opaque);
1850 static void win_chr_close2(WinCharState *s)
1852 if (s->hsend) {
1853 CloseHandle(s->hsend);
1854 s->hsend = NULL;
1856 if (s->hrecv) {
1857 CloseHandle(s->hrecv);
1858 s->hrecv = NULL;
1860 if (s->hcom) {
1861 CloseHandle(s->hcom);
1862 s->hcom = NULL;
1864 if (s->fpipe)
1865 qemu_del_polling_cb(win_chr_pipe_poll, s);
1866 else
1867 qemu_del_polling_cb(win_chr_poll, s);
1870 static void win_chr_close(CharDriverState *chr)
1872 WinCharState *s = chr->opaque;
1873 win_chr_close2(s);
1876 static int win_chr_init(WinCharState *s, const char *filename)
1878 COMMCONFIG comcfg;
1879 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1880 COMSTAT comstat;
1881 DWORD size;
1882 DWORD err;
1884 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1885 if (!s->hsend) {
1886 fprintf(stderr, "Failed CreateEvent\n");
1887 goto fail;
1889 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1890 if (!s->hrecv) {
1891 fprintf(stderr, "Failed CreateEvent\n");
1892 goto fail;
1895 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1896 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1897 if (s->hcom == INVALID_HANDLE_VALUE) {
1898 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1899 s->hcom = NULL;
1900 goto fail;
1903 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1904 fprintf(stderr, "Failed SetupComm\n");
1905 goto fail;
1908 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1909 size = sizeof(COMMCONFIG);
1910 GetDefaultCommConfig(filename, &comcfg, &size);
1911 comcfg.dcb.DCBlength = sizeof(DCB);
1912 CommConfigDialog(filename, NULL, &comcfg);
1914 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1915 fprintf(stderr, "Failed SetCommState\n");
1916 goto fail;
1919 if (!SetCommMask(s->hcom, EV_ERR)) {
1920 fprintf(stderr, "Failed SetCommMask\n");
1921 goto fail;
1924 cto.ReadIntervalTimeout = MAXDWORD;
1925 if (!SetCommTimeouts(s->hcom, &cto)) {
1926 fprintf(stderr, "Failed SetCommTimeouts\n");
1927 goto fail;
1930 if (!ClearCommError(s->hcom, &err, &comstat)) {
1931 fprintf(stderr, "Failed ClearCommError\n");
1932 goto fail;
1934 qemu_add_polling_cb(win_chr_poll, s);
1935 return 0;
1937 fail:
1938 win_chr_close2(s);
1939 return -1;
1942 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1944 WinCharState *s = chr->opaque;
1945 DWORD len, ret, size, err;
1947 len = len1;
1948 ZeroMemory(&s->osend, sizeof(s->osend));
1949 s->osend.hEvent = s->hsend;
1950 while (len > 0) {
1951 if (s->hsend)
1952 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1953 else
1954 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1955 if (!ret) {
1956 err = GetLastError();
1957 if (err == ERROR_IO_PENDING) {
1958 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1959 if (ret) {
1960 buf += size;
1961 len -= size;
1962 } else {
1963 break;
1965 } else {
1966 break;
1968 } else {
1969 buf += size;
1970 len -= size;
1973 return len1 - len;
1976 static int win_chr_read_poll(WinCharState *s)
1978 s->max_size = s->fd_can_read(s->win_opaque);
1979 return s->max_size;
1982 static void win_chr_readfile(WinCharState *s)
1984 int ret, err;
1985 uint8_t buf[1024];
1986 DWORD size;
1988 ZeroMemory(&s->orecv, sizeof(s->orecv));
1989 s->orecv.hEvent = s->hrecv;
1990 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1991 if (!ret) {
1992 err = GetLastError();
1993 if (err == ERROR_IO_PENDING) {
1994 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1998 if (size > 0) {
1999 s->fd_read(s->win_opaque, buf, size);
2003 static void win_chr_read(WinCharState *s)
2005 if (s->len > s->max_size)
2006 s->len = s->max_size;
2007 if (s->len == 0)
2008 return;
2010 win_chr_readfile(s);
2013 static int win_chr_poll(void *opaque)
2015 WinCharState *s = opaque;
2016 COMSTAT status;
2017 DWORD comerr;
2019 ClearCommError(s->hcom, &comerr, &status);
2020 if (status.cbInQue > 0) {
2021 s->len = status.cbInQue;
2022 win_chr_read_poll(s);
2023 win_chr_read(s);
2024 return 1;
2026 return 0;
2029 static void win_chr_add_read_handler(CharDriverState *chr,
2030 IOCanRWHandler *fd_can_read,
2031 IOReadHandler *fd_read, void *opaque)
2033 WinCharState *s = chr->opaque;
2035 s->fd_can_read = fd_can_read;
2036 s->fd_read = fd_read;
2037 s->win_opaque = opaque;
2040 CharDriverState *qemu_chr_open_win(const char *filename)
2042 CharDriverState *chr;
2043 WinCharState *s;
2045 chr = qemu_mallocz(sizeof(CharDriverState));
2046 if (!chr)
2047 return NULL;
2048 s = qemu_mallocz(sizeof(WinCharState));
2049 if (!s) {
2050 free(chr);
2051 return NULL;
2053 chr->opaque = s;
2054 chr->chr_write = win_chr_write;
2055 chr->chr_add_read_handler = win_chr_add_read_handler;
2056 chr->chr_close = win_chr_close;
2058 if (win_chr_init(s, filename) < 0) {
2059 free(s);
2060 free(chr);
2061 return NULL;
2063 return chr;
2066 static int win_chr_pipe_poll(void *opaque)
2068 WinCharState *s = opaque;
2069 DWORD size;
2071 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2072 if (size > 0) {
2073 s->len = size;
2074 win_chr_read_poll(s);
2075 win_chr_read(s);
2076 return 1;
2078 return 0;
2081 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2083 OVERLAPPED ov;
2084 int ret;
2085 DWORD size;
2086 char openname[256];
2088 s->fpipe = TRUE;
2090 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2091 if (!s->hsend) {
2092 fprintf(stderr, "Failed CreateEvent\n");
2093 goto fail;
2095 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2096 if (!s->hrecv) {
2097 fprintf(stderr, "Failed CreateEvent\n");
2098 goto fail;
2101 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2102 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2103 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2104 PIPE_WAIT,
2105 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2106 if (s->hcom == INVALID_HANDLE_VALUE) {
2107 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2108 s->hcom = NULL;
2109 goto fail;
2112 ZeroMemory(&ov, sizeof(ov));
2113 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2114 ret = ConnectNamedPipe(s->hcom, &ov);
2115 if (ret) {
2116 fprintf(stderr, "Failed ConnectNamedPipe\n");
2117 goto fail;
2120 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2121 if (!ret) {
2122 fprintf(stderr, "Failed GetOverlappedResult\n");
2123 if (ov.hEvent) {
2124 CloseHandle(ov.hEvent);
2125 ov.hEvent = NULL;
2127 goto fail;
2130 if (ov.hEvent) {
2131 CloseHandle(ov.hEvent);
2132 ov.hEvent = NULL;
2134 qemu_add_polling_cb(win_chr_pipe_poll, s);
2135 return 0;
2137 fail:
2138 win_chr_close2(s);
2139 return -1;
2143 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2145 CharDriverState *chr;
2146 WinCharState *s;
2148 chr = qemu_mallocz(sizeof(CharDriverState));
2149 if (!chr)
2150 return NULL;
2151 s = qemu_mallocz(sizeof(WinCharState));
2152 if (!s) {
2153 free(chr);
2154 return NULL;
2156 chr->opaque = s;
2157 chr->chr_write = win_chr_write;
2158 chr->chr_add_read_handler = win_chr_add_read_handler;
2159 chr->chr_close = win_chr_close;
2161 if (win_chr_pipe_init(s, filename) < 0) {
2162 free(s);
2163 free(chr);
2164 return NULL;
2166 return chr;
2169 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2171 CharDriverState *chr;
2172 WinCharState *s;
2174 chr = qemu_mallocz(sizeof(CharDriverState));
2175 if (!chr)
2176 return NULL;
2177 s = qemu_mallocz(sizeof(WinCharState));
2178 if (!s) {
2179 free(chr);
2180 return NULL;
2182 s->hcom = fd_out;
2183 chr->opaque = s;
2184 chr->chr_write = win_chr_write;
2185 chr->chr_add_read_handler = win_chr_add_read_handler;
2186 return chr;
2189 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2191 HANDLE fd_out;
2193 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2194 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2195 if (fd_out == INVALID_HANDLE_VALUE)
2196 return NULL;
2198 return qemu_chr_open_win_file(fd_out);
2200 #endif
2202 /***********************************************************/
2203 /* UDP Net console */
2205 typedef struct {
2206 IOCanRWHandler *fd_can_read;
2207 IOReadHandler *fd_read;
2208 void *fd_opaque;
2209 int fd;
2210 struct sockaddr_in daddr;
2211 char buf[1024];
2212 int bufcnt;
2213 int bufptr;
2214 int max_size;
2215 } NetCharDriver;
2217 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2219 NetCharDriver *s = chr->opaque;
2221 return sendto(s->fd, buf, len, 0,
2222 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2225 static int udp_chr_read_poll(void *opaque)
2227 CharDriverState *chr = opaque;
2228 NetCharDriver *s = chr->opaque;
2230 s->max_size = s->fd_can_read(s->fd_opaque);
2232 /* If there were any stray characters in the queue process them
2233 * first
2234 */
2235 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2236 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2237 s->bufptr++;
2238 s->max_size = s->fd_can_read(s->fd_opaque);
2240 return s->max_size;
2243 static void udp_chr_read(void *opaque)
2245 CharDriverState *chr = opaque;
2246 NetCharDriver *s = chr->opaque;
2248 if (s->max_size == 0)
2249 return;
2250 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2251 s->bufptr = s->bufcnt;
2252 if (s->bufcnt <= 0)
2253 return;
2255 s->bufptr = 0;
2256 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2257 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2258 s->bufptr++;
2259 s->max_size = s->fd_can_read(s->fd_opaque);
2263 static void udp_chr_add_read_handler(CharDriverState *chr,
2264 IOCanRWHandler *fd_can_read,
2265 IOReadHandler *fd_read, void *opaque)
2267 NetCharDriver *s = chr->opaque;
2269 if (s->fd >= 0) {
2270 s->fd_can_read = fd_can_read;
2271 s->fd_read = fd_read;
2272 s->fd_opaque = opaque;
2273 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2274 udp_chr_read, NULL, chr);
2278 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2279 int parse_host_src_port(struct sockaddr_in *haddr,
2280 struct sockaddr_in *saddr,
2281 const char *str);
2283 CharDriverState *qemu_chr_open_udp(const char *def)
2285 CharDriverState *chr = NULL;
2286 NetCharDriver *s = NULL;
2287 int fd = -1;
2288 struct sockaddr_in saddr;
2290 chr = qemu_mallocz(sizeof(CharDriverState));
2291 if (!chr)
2292 goto return_err;
2293 s = qemu_mallocz(sizeof(NetCharDriver));
2294 if (!s)
2295 goto return_err;
2297 fd = socket(PF_INET, SOCK_DGRAM, 0);
2298 if (fd < 0) {
2299 perror("socket(PF_INET, SOCK_DGRAM)");
2300 goto return_err;
2303 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2304 printf("Could not parse: %s\n", def);
2305 goto return_err;
2308 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2310 perror("bind");
2311 goto return_err;
2314 s->fd = fd;
2315 s->bufcnt = 0;
2316 s->bufptr = 0;
2317 chr->opaque = s;
2318 chr->chr_write = udp_chr_write;
2319 chr->chr_add_read_handler = udp_chr_add_read_handler;
2320 return chr;
2322 return_err:
2323 if (chr)
2324 free(chr);
2325 if (s)
2326 free(s);
2327 if (fd >= 0)
2328 closesocket(fd);
2329 return NULL;
2332 /***********************************************************/
2333 /* TCP Net console */
2335 typedef struct {
2336 IOCanRWHandler *fd_can_read;
2337 IOReadHandler *fd_read;
2338 void *fd_opaque;
2339 int fd, listen_fd;
2340 int connected;
2341 int max_size;
2342 int do_telnetopt;
2343 } TCPCharDriver;
2345 static void tcp_chr_accept(void *opaque);
2347 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2349 TCPCharDriver *s = chr->opaque;
2350 if (s->connected) {
2351 return send_all(s->fd, buf, len);
2352 } else {
2353 /* XXX: indicate an error ? */
2354 return len;
2358 static int tcp_chr_read_poll(void *opaque)
2360 CharDriverState *chr = opaque;
2361 TCPCharDriver *s = chr->opaque;
2362 if (!s->connected)
2363 return 0;
2364 s->max_size = s->fd_can_read(s->fd_opaque);
2365 return s->max_size;
2368 #define IAC 255
2369 #define IAC_BREAK 243
2370 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2371 TCPCharDriver *s,
2372 char *buf, int *size)
2374 /* Handle any telnet client's basic IAC options to satisfy char by
2375 * char mode with no echo. All IAC options will be removed from
2376 * the buf and the do_telnetopt variable will be used to track the
2377 * state of the width of the IAC information.
2379 * IAC commands come in sets of 3 bytes with the exception of the
2380 * "IAC BREAK" command and the double IAC.
2381 */
2383 int i;
2384 int j = 0;
2386 for (i = 0; i < *size; i++) {
2387 if (s->do_telnetopt > 1) {
2388 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2389 /* Double IAC means send an IAC */
2390 if (j != i)
2391 buf[j] = buf[i];
2392 j++;
2393 s->do_telnetopt = 1;
2394 } else {
2395 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2396 /* Handle IAC break commands by sending a serial break */
2397 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2398 s->do_telnetopt++;
2400 s->do_telnetopt++;
2402 if (s->do_telnetopt >= 4) {
2403 s->do_telnetopt = 1;
2405 } else {
2406 if ((unsigned char)buf[i] == IAC) {
2407 s->do_telnetopt = 2;
2408 } else {
2409 if (j != i)
2410 buf[j] = buf[i];
2411 j++;
2415 *size = j;
2418 static void tcp_chr_read(void *opaque)
2420 CharDriverState *chr = opaque;
2421 TCPCharDriver *s = chr->opaque;
2422 uint8_t buf[1024];
2423 int len, size;
2425 if (!s->connected || s->max_size <= 0)
2426 return;
2427 len = sizeof(buf);
2428 if (len > s->max_size)
2429 len = s->max_size;
2430 size = recv(s->fd, buf, len, 0);
2431 if (size == 0) {
2432 /* connection closed */
2433 s->connected = 0;
2434 if (s->listen_fd >= 0) {
2435 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2437 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2438 closesocket(s->fd);
2439 s->fd = -1;
2440 } else if (size > 0) {
2441 if (s->do_telnetopt)
2442 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2443 if (size > 0)
2444 s->fd_read(s->fd_opaque, buf, size);
2448 static void tcp_chr_add_read_handler(CharDriverState *chr,
2449 IOCanRWHandler *fd_can_read,
2450 IOReadHandler *fd_read, void *opaque)
2452 TCPCharDriver *s = chr->opaque;
2454 s->fd_can_read = fd_can_read;
2455 s->fd_read = fd_read;
2456 s->fd_opaque = opaque;
2459 static void tcp_chr_connect(void *opaque)
2461 CharDriverState *chr = opaque;
2462 TCPCharDriver *s = chr->opaque;
2464 s->connected = 1;
2465 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2466 tcp_chr_read, NULL, chr);
2469 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2470 static void tcp_chr_telnet_init(int fd)
2472 char buf[3];
2473 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2474 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2475 send(fd, (char *)buf, 3, 0);
2476 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2477 send(fd, (char *)buf, 3, 0);
2478 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2479 send(fd, (char *)buf, 3, 0);
2480 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2481 send(fd, (char *)buf, 3, 0);
2484 static void tcp_chr_accept(void *opaque)
2486 CharDriverState *chr = opaque;
2487 TCPCharDriver *s = chr->opaque;
2488 struct sockaddr_in saddr;
2489 socklen_t len;
2490 int fd;
2492 for(;;) {
2493 len = sizeof(saddr);
2494 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2495 if (fd < 0 && errno != EINTR) {
2496 return;
2497 } else if (fd >= 0) {
2498 if (s->do_telnetopt)
2499 tcp_chr_telnet_init(fd);
2500 break;
2503 socket_set_nonblock(fd);
2504 s->fd = fd;
2505 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2506 tcp_chr_connect(chr);
2509 static void tcp_chr_close(CharDriverState *chr)
2511 TCPCharDriver *s = chr->opaque;
2512 if (s->fd >= 0)
2513 closesocket(s->fd);
2514 if (s->listen_fd >= 0)
2515 closesocket(s->listen_fd);
2516 qemu_free(s);
2519 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2520 int is_telnet)
2522 CharDriverState *chr = NULL;
2523 TCPCharDriver *s = NULL;
2524 int fd = -1, ret, err, val;
2525 int is_listen = 0;
2526 int is_waitconnect = 1;
2527 const char *ptr;
2528 struct sockaddr_in saddr;
2530 if (parse_host_port(&saddr, host_str) < 0)
2531 goto fail;
2533 ptr = host_str;
2534 while((ptr = strchr(ptr,','))) {
2535 ptr++;
2536 if (!strncmp(ptr,"server",6)) {
2537 is_listen = 1;
2538 } else if (!strncmp(ptr,"nowait",6)) {
2539 is_waitconnect = 0;
2540 } else {
2541 printf("Unknown option: %s\n", ptr);
2542 goto fail;
2545 if (!is_listen)
2546 is_waitconnect = 0;
2548 chr = qemu_mallocz(sizeof(CharDriverState));
2549 if (!chr)
2550 goto fail;
2551 s = qemu_mallocz(sizeof(TCPCharDriver));
2552 if (!s)
2553 goto fail;
2555 fd = socket(PF_INET, SOCK_STREAM, 0);
2556 if (fd < 0)
2557 goto fail;
2559 if (!is_waitconnect)
2560 socket_set_nonblock(fd);
2562 s->connected = 0;
2563 s->fd = -1;
2564 s->listen_fd = -1;
2565 if (is_listen) {
2566 /* allow fast reuse */
2567 val = 1;
2568 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2570 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2571 if (ret < 0)
2572 goto fail;
2573 ret = listen(fd, 0);
2574 if (ret < 0)
2575 goto fail;
2576 s->listen_fd = fd;
2577 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2578 if (is_telnet)
2579 s->do_telnetopt = 1;
2580 } else {
2581 for(;;) {
2582 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2583 if (ret < 0) {
2584 err = socket_error();
2585 if (err == EINTR || err == EWOULDBLOCK) {
2586 } else if (err == EINPROGRESS) {
2587 break;
2588 } else {
2589 goto fail;
2591 } else {
2592 s->connected = 1;
2593 break;
2596 s->fd = fd;
2597 if (s->connected)
2598 tcp_chr_connect(chr);
2599 else
2600 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2603 chr->opaque = s;
2604 chr->chr_write = tcp_chr_write;
2605 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2606 chr->chr_close = tcp_chr_close;
2607 if (is_listen && is_waitconnect) {
2608 printf("QEMU waiting for connection on: %s\n", host_str);
2609 tcp_chr_accept(chr);
2610 socket_set_nonblock(s->listen_fd);
2613 return chr;
2614 fail:
2615 if (fd >= 0)
2616 closesocket(fd);
2617 qemu_free(s);
2618 qemu_free(chr);
2619 return NULL;
2622 CharDriverState *qemu_chr_open(const char *filename)
2624 const char *p;
2626 if (!strcmp(filename, "vc")) {
2627 return text_console_init(&display_state);
2628 } else if (!strcmp(filename, "null")) {
2629 return qemu_chr_open_null();
2630 } else
2631 if (strstart(filename, "tcp:", &p)) {
2632 return qemu_chr_open_tcp(p, 0);
2633 } else
2634 if (strstart(filename, "telnet:", &p)) {
2635 return qemu_chr_open_tcp(p, 1);
2636 } else
2637 if (strstart(filename, "udp:", &p)) {
2638 return qemu_chr_open_udp(p);
2639 } else
2640 #ifndef _WIN32
2641 if (strstart(filename, "file:", &p)) {
2642 return qemu_chr_open_file_out(p);
2643 } else if (strstart(filename, "pipe:", &p)) {
2644 return qemu_chr_open_pipe(p);
2645 } else if (!strcmp(filename, "pty")) {
2646 return qemu_chr_open_pty();
2647 } else if (!strcmp(filename, "stdio")) {
2648 return qemu_chr_open_stdio();
2649 } else
2650 #endif
2651 #if defined(__linux__)
2652 if (strstart(filename, "/dev/parport", NULL)) {
2653 return qemu_chr_open_pp(filename);
2654 } else
2655 if (strstart(filename, "/dev/", NULL)) {
2656 return qemu_chr_open_tty(filename);
2657 } else
2658 #endif
2659 #ifdef _WIN32
2660 if (strstart(filename, "COM", NULL)) {
2661 return qemu_chr_open_win(filename);
2662 } else
2663 if (strstart(filename, "pipe:", &p)) {
2664 return qemu_chr_open_win_pipe(p);
2665 } else
2666 if (strstart(filename, "file:", &p)) {
2667 return qemu_chr_open_win_file_out(p);
2669 #endif
2671 return NULL;
2675 void qemu_chr_close(CharDriverState *chr)
2677 if (chr->chr_close)
2678 chr->chr_close(chr);
2681 /***********************************************************/
2682 /* network device redirectors */
2684 void hex_dump(FILE *f, const uint8_t *buf, int size)
2686 int len, i, j, c;
2688 for(i=0;i<size;i+=16) {
2689 len = size - i;
2690 if (len > 16)
2691 len = 16;
2692 fprintf(f, "%08x ", i);
2693 for(j=0;j<16;j++) {
2694 if (j < len)
2695 fprintf(f, " %02x", buf[i+j]);
2696 else
2697 fprintf(f, " ");
2699 fprintf(f, " ");
2700 for(j=0;j<len;j++) {
2701 c = buf[i+j];
2702 if (c < ' ' || c > '~')
2703 c = '.';
2704 fprintf(f, "%c", c);
2706 fprintf(f, "\n");
2710 static int parse_macaddr(uint8_t *macaddr, const char *p)
2712 int i;
2713 for(i = 0; i < 6; i++) {
2714 macaddr[i] = strtol(p, (char **)&p, 16);
2715 if (i == 5) {
2716 if (*p != '\0')
2717 return -1;
2718 } else {
2719 if (*p != ':')
2720 return -1;
2721 p++;
2724 return 0;
2727 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2729 const char *p, *p1;
2730 int len;
2731 p = *pp;
2732 p1 = strchr(p, sep);
2733 if (!p1)
2734 return -1;
2735 len = p1 - p;
2736 p1++;
2737 if (buf_size > 0) {
2738 if (len > buf_size - 1)
2739 len = buf_size - 1;
2740 memcpy(buf, p, len);
2741 buf[len] = '\0';
2743 *pp = p1;
2744 return 0;
2747 int parse_host_src_port(struct sockaddr_in *haddr,
2748 struct sockaddr_in *saddr,
2749 const char *input_str)
2751 char *str = strdup(input_str);
2752 char *host_str = str;
2753 char *src_str;
2754 char *ptr;
2756 /*
2757 * Chop off any extra arguments at the end of the string which
2758 * would start with a comma, then fill in the src port information
2759 * if it was provided else use the "any address" and "any port".
2760 */
2761 if ((ptr = strchr(str,',')))
2762 *ptr = '\0';
2764 if ((src_str = strchr(input_str,'@'))) {
2765 *src_str = '\0';
2766 src_str++;
2769 if (parse_host_port(haddr, host_str) < 0)
2770 goto fail;
2772 if (!src_str || *src_str == '\0')
2773 src_str = ":0";
2775 if (parse_host_port(saddr, src_str) < 0)
2776 goto fail;
2778 free(str);
2779 return(0);
2781 fail:
2782 free(str);
2783 return -1;
2786 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2788 char buf[512];
2789 struct hostent *he;
2790 const char *p, *r;
2791 int port;
2793 p = str;
2794 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2795 return -1;
2796 saddr->sin_family = AF_INET;
2797 if (buf[0] == '\0') {
2798 saddr->sin_addr.s_addr = 0;
2799 } else {
2800 if (isdigit(buf[0])) {
2801 if (!inet_aton(buf, &saddr->sin_addr))
2802 return -1;
2803 } else {
2804 if ((he = gethostbyname(buf)) == NULL)
2805 return - 1;
2806 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2809 port = strtol(p, (char **)&r, 0);
2810 if (r == p)
2811 return -1;
2812 saddr->sin_port = htons(port);
2813 return 0;
2816 /* find or alloc a new VLAN */
2817 VLANState *qemu_find_vlan(int id)
2819 VLANState **pvlan, *vlan;
2820 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2821 if (vlan->id == id)
2822 return vlan;
2824 vlan = qemu_mallocz(sizeof(VLANState));
2825 if (!vlan)
2826 return NULL;
2827 vlan->id = id;
2828 vlan->next = NULL;
2829 pvlan = &first_vlan;
2830 while (*pvlan != NULL)
2831 pvlan = &(*pvlan)->next;
2832 *pvlan = vlan;
2833 return vlan;
2836 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2837 IOReadHandler *fd_read,
2838 IOCanRWHandler *fd_can_read,
2839 void *opaque)
2841 VLANClientState *vc, **pvc;
2842 vc = qemu_mallocz(sizeof(VLANClientState));
2843 if (!vc)
2844 return NULL;
2845 vc->fd_read = fd_read;
2846 vc->fd_can_read = fd_can_read;
2847 vc->opaque = opaque;
2848 vc->vlan = vlan;
2850 vc->next = NULL;
2851 pvc = &vlan->first_client;
2852 while (*pvc != NULL)
2853 pvc = &(*pvc)->next;
2854 *pvc = vc;
2855 return vc;
2858 int qemu_can_send_packet(VLANClientState *vc1)
2860 VLANState *vlan = vc1->vlan;
2861 VLANClientState *vc;
2863 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2864 if (vc != vc1) {
2865 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2866 return 0;
2869 return 1;
2872 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2874 VLANState *vlan = vc1->vlan;
2875 VLANClientState *vc;
2877 #if 0
2878 printf("vlan %d send:\n", vlan->id);
2879 hex_dump(stdout, buf, size);
2880 #endif
2881 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2882 if (vc != vc1) {
2883 vc->fd_read(vc->opaque, buf, size);
2888 #if defined(CONFIG_SLIRP)
2890 /* slirp network adapter */
2892 static int slirp_inited;
2893 static VLANClientState *slirp_vc;
2895 int slirp_can_output(void)
2897 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2900 void slirp_output(const uint8_t *pkt, int pkt_len)
2902 #if 0
2903 printf("slirp output:\n");
2904 hex_dump(stdout, pkt, pkt_len);
2905 #endif
2906 if (!slirp_vc)
2907 return;
2908 qemu_send_packet(slirp_vc, pkt, pkt_len);
2911 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2913 #if 0
2914 printf("slirp input:\n");
2915 hex_dump(stdout, buf, size);
2916 #endif
2917 slirp_input(buf, size);
2920 static int net_slirp_init(VLANState *vlan)
2922 if (!slirp_inited) {
2923 slirp_inited = 1;
2924 slirp_init();
2926 slirp_vc = qemu_new_vlan_client(vlan,
2927 slirp_receive, NULL, NULL);
2928 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2929 return 0;
2932 static void net_slirp_redir(const char *redir_str)
2934 int is_udp;
2935 char buf[256], *r;
2936 const char *p;
2937 struct in_addr guest_addr;
2938 int host_port, guest_port;
2940 if (!slirp_inited) {
2941 slirp_inited = 1;
2942 slirp_init();
2945 p = redir_str;
2946 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2947 goto fail;
2948 if (!strcmp(buf, "tcp")) {
2949 is_udp = 0;
2950 } else if (!strcmp(buf, "udp")) {
2951 is_udp = 1;
2952 } else {
2953 goto fail;
2956 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2957 goto fail;
2958 host_port = strtol(buf, &r, 0);
2959 if (r == buf)
2960 goto fail;
2962 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2963 goto fail;
2964 if (buf[0] == '\0') {
2965 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2967 if (!inet_aton(buf, &guest_addr))
2968 goto fail;
2970 guest_port = strtol(p, &r, 0);
2971 if (r == p)
2972 goto fail;
2974 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2975 fprintf(stderr, "qemu: could not set up redirection\n");
2976 exit(1);
2978 return;
2979 fail:
2980 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2981 exit(1);
2984 #ifndef _WIN32
2986 char smb_dir[1024];
2988 static void smb_exit(void)
2990 DIR *d;
2991 struct dirent *de;
2992 char filename[1024];
2994 /* erase all the files in the directory */
2995 d = opendir(smb_dir);
2996 for(;;) {
2997 de = readdir(d);
2998 if (!de)
2999 break;
3000 if (strcmp(de->d_name, ".") != 0 &&
3001 strcmp(de->d_name, "..") != 0) {
3002 snprintf(filename, sizeof(filename), "%s/%s",
3003 smb_dir, de->d_name);
3004 unlink(filename);
3007 closedir(d);
3008 rmdir(smb_dir);
3011 /* automatic user mode samba server configuration */
3012 void net_slirp_smb(const char *exported_dir)
3014 char smb_conf[1024];
3015 char smb_cmdline[1024];
3016 FILE *f;
3018 if (!slirp_inited) {
3019 slirp_inited = 1;
3020 slirp_init();
3023 /* XXX: better tmp dir construction */
3024 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3025 if (mkdir(smb_dir, 0700) < 0) {
3026 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3027 exit(1);
3029 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3031 f = fopen(smb_conf, "w");
3032 if (!f) {
3033 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3034 exit(1);
3036 fprintf(f,
3037 "[global]\n"
3038 "private dir=%s\n"
3039 "smb ports=0\n"
3040 "socket address=127.0.0.1\n"
3041 "pid directory=%s\n"
3042 "lock directory=%s\n"
3043 "log file=%s/log.smbd\n"
3044 "smb passwd file=%s/smbpasswd\n"
3045 "security = share\n"
3046 "[qemu]\n"
3047 "path=%s\n"
3048 "read only=no\n"
3049 "guest ok=yes\n",
3050 smb_dir,
3051 smb_dir,
3052 smb_dir,
3053 smb_dir,
3054 smb_dir,
3055 exported_dir
3056 );
3057 fclose(f);
3058 atexit(smb_exit);
3060 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3061 smb_conf);
3063 slirp_add_exec(0, smb_cmdline, 4, 139);
3066 #endif /* !defined(_WIN32) */
3068 #endif /* CONFIG_SLIRP */
3070 #if !defined(_WIN32)
3072 typedef struct TAPState {
3073 VLANClientState *vc;
3074 int fd;
3075 } TAPState;
3077 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3079 TAPState *s = opaque;
3080 int ret;
3081 for(;;) {
3082 ret = write(s->fd, buf, size);
3083 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3084 } else {
3085 break;
3090 static void tap_send(void *opaque)
3092 TAPState *s = opaque;
3093 uint8_t buf[4096];
3094 int size;
3096 size = read(s->fd, buf, sizeof(buf));
3097 if (size > 0) {
3098 qemu_send_packet(s->vc, buf, size);
3102 /* fd support */
3104 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3106 TAPState *s;
3108 s = qemu_mallocz(sizeof(TAPState));
3109 if (!s)
3110 return NULL;
3111 s->fd = fd;
3112 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3113 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3114 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3115 return s;
3118 #ifdef _BSD
3119 static int tap_open(char *ifname, int ifname_size)
3121 int fd;
3122 char *dev;
3123 struct stat s;
3125 fd = open("/dev/tap", O_RDWR);
3126 if (fd < 0) {
3127 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3128 return -1;
3131 fstat(fd, &s);
3132 dev = devname(s.st_rdev, S_IFCHR);
3133 pstrcpy(ifname, ifname_size, dev);
3135 fcntl(fd, F_SETFL, O_NONBLOCK);
3136 return fd;
3138 #elif defined(__sun__)
3139 static int tap_open(char *ifname, int ifname_size)
3141 fprintf(stderr, "warning: tap_open not yet implemented\n");
3142 return -1;
3144 #else
3145 static int tap_open(char *ifname, int ifname_size)
3147 struct ifreq ifr;
3148 int fd, ret;
3150 fd = open("/dev/net/tun", O_RDWR);
3151 if (fd < 0) {
3152 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3153 return -1;
3155 memset(&ifr, 0, sizeof(ifr));
3156 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3157 if (ifname[0] != '\0')
3158 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3159 else
3160 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3161 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3162 if (ret != 0) {
3163 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3164 close(fd);
3165 return -1;
3167 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3168 fcntl(fd, F_SETFL, O_NONBLOCK);
3169 return fd;
3171 #endif
3173 static int net_tap_init(VLANState *vlan, const char *ifname1,
3174 const char *setup_script, const char *bridge)
3176 TAPState *s;
3177 int pid, status, fd;
3178 char *args[4];
3179 char **parg;
3180 char ifname[128];
3182 if (ifname1 != NULL)
3183 pstrcpy(ifname, sizeof(ifname), ifname1);
3184 else
3185 ifname[0] = '\0';
3186 fd = tap_open(ifname, sizeof(ifname));
3187 if (fd < 0)
3188 return -1;
3190 if (!setup_script)
3191 setup_script = "";
3192 if (setup_script[0] != '\0') {
3193 /* try to launch network init script */
3194 pid = fork();
3195 if (pid >= 0) {
3196 if (pid == 0) {
3197 parg = args;
3198 *parg++ = (char *)setup_script;
3199 *parg++ = ifname;
3200 *parg++ = (char *)bridge;
3201 *parg++ = NULL;
3202 execv(setup_script, args);
3203 _exit(1);
3205 while (waitpid(pid, &status, 0) != pid);
3206 if (!WIFEXITED(status) ||
3207 WEXITSTATUS(status) != 0) {
3208 fprintf(stderr, "%s: could not launch network script\n",
3209 setup_script);
3210 return -1;
3214 s = net_tap_fd_init(vlan, fd);
3215 if (!s)
3216 return -1;
3217 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3218 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3219 return 0;
3222 #endif /* !_WIN32 */
3224 /* network connection */
3225 typedef struct NetSocketState {
3226 VLANClientState *vc;
3227 int fd;
3228 int state; /* 0 = getting length, 1 = getting data */
3229 int index;
3230 int packet_len;
3231 uint8_t buf[4096];
3232 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3233 } NetSocketState;
3235 typedef struct NetSocketListenState {
3236 VLANState *vlan;
3237 int fd;
3238 } NetSocketListenState;
3240 /* XXX: we consider we can send the whole packet without blocking */
3241 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3243 NetSocketState *s = opaque;
3244 uint32_t len;
3245 len = htonl(size);
3247 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3248 send_all(s->fd, buf, size);
3251 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3253 NetSocketState *s = opaque;
3254 sendto(s->fd, buf, size, 0,
3255 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3258 static void net_socket_send(void *opaque)
3260 NetSocketState *s = opaque;
3261 int l, size, err;
3262 uint8_t buf1[4096];
3263 const uint8_t *buf;
3265 size = recv(s->fd, buf1, sizeof(buf1), 0);
3266 if (size < 0) {
3267 err = socket_error();
3268 if (err != EWOULDBLOCK)
3269 goto eoc;
3270 } else if (size == 0) {
3271 /* end of connection */
3272 eoc:
3273 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3274 closesocket(s->fd);
3275 return;
3277 buf = buf1;
3278 while (size > 0) {
3279 /* reassemble a packet from the network */
3280 switch(s->state) {
3281 case 0:
3282 l = 4 - s->index;
3283 if (l > size)
3284 l = size;
3285 memcpy(s->buf + s->index, buf, l);
3286 buf += l;
3287 size -= l;
3288 s->index += l;
3289 if (s->index == 4) {
3290 /* got length */
3291 s->packet_len = ntohl(*(uint32_t *)s->buf);
3292 s->index = 0;
3293 s->state = 1;
3295 break;
3296 case 1:
3297 l = s->packet_len - s->index;
3298 if (l > size)
3299 l = size;
3300 memcpy(s->buf + s->index, buf, l);
3301 s->index += l;
3302 buf += l;
3303 size -= l;
3304 if (s->index >= s->packet_len) {
3305 qemu_send_packet(s->vc, s->buf, s->packet_len);
3306 s->index = 0;
3307 s->state = 0;
3309 break;
3314 static void net_socket_send_dgram(void *opaque)
3316 NetSocketState *s = opaque;
3317 int size;
3319 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3320 if (size < 0)
3321 return;
3322 if (size == 0) {
3323 /* end of connection */
3324 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3325 return;
3327 qemu_send_packet(s->vc, s->buf, size);
3330 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3332 struct ip_mreq imr;
3333 int fd;
3334 int val, ret;
3335 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3336 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3337 inet_ntoa(mcastaddr->sin_addr),
3338 (int)ntohl(mcastaddr->sin_addr.s_addr));
3339 return -1;
3342 fd = socket(PF_INET, SOCK_DGRAM, 0);
3343 if (fd < 0) {
3344 perror("socket(PF_INET, SOCK_DGRAM)");
3345 return -1;
3348 val = 1;
3349 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3350 (const char *)&val, sizeof(val));
3351 if (ret < 0) {
3352 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3353 goto fail;
3356 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3357 if (ret < 0) {
3358 perror("bind");
3359 goto fail;
3362 /* Add host to multicast group */
3363 imr.imr_multiaddr = mcastaddr->sin_addr;
3364 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3366 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3367 (const char *)&imr, sizeof(struct ip_mreq));
3368 if (ret < 0) {
3369 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3370 goto fail;
3373 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3374 val = 1;
3375 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3376 (const char *)&val, sizeof(val));
3377 if (ret < 0) {
3378 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3379 goto fail;
3382 socket_set_nonblock(fd);
3383 return fd;
3384 fail:
3385 if (fd >= 0)
3386 closesocket(fd);
3387 return -1;
3390 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3391 int is_connected)
3393 struct sockaddr_in saddr;
3394 int newfd;
3395 socklen_t saddr_len;
3396 NetSocketState *s;
3398 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3399 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3400 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3401 */
3403 if (is_connected) {
3404 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3405 /* must be bound */
3406 if (saddr.sin_addr.s_addr==0) {
3407 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3408 fd);
3409 return NULL;
3411 /* clone dgram socket */
3412 newfd = net_socket_mcast_create(&saddr);
3413 if (newfd < 0) {
3414 /* error already reported by net_socket_mcast_create() */
3415 close(fd);
3416 return NULL;
3418 /* clone newfd to fd, close newfd */
3419 dup2(newfd, fd);
3420 close(newfd);
3422 } else {
3423 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3424 fd, strerror(errno));
3425 return NULL;
3429 s = qemu_mallocz(sizeof(NetSocketState));
3430 if (!s)
3431 return NULL;
3432 s->fd = fd;
3434 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3435 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3437 /* mcast: save bound address as dst */
3438 if (is_connected) s->dgram_dst=saddr;
3440 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3441 "socket: fd=%d (%s mcast=%s:%d)",
3442 fd, is_connected? "cloned" : "",
3443 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3444 return s;
3447 static void net_socket_connect(void *opaque)
3449 NetSocketState *s = opaque;
3450 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3453 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3454 int is_connected)
3456 NetSocketState *s;
3457 s = qemu_mallocz(sizeof(NetSocketState));
3458 if (!s)
3459 return NULL;
3460 s->fd = fd;
3461 s->vc = qemu_new_vlan_client(vlan,
3462 net_socket_receive, NULL, s);
3463 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3464 "socket: fd=%d", fd);
3465 if (is_connected) {
3466 net_socket_connect(s);
3467 } else {
3468 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3470 return s;
3473 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3474 int is_connected)
3476 int so_type=-1, optlen=sizeof(so_type);
3478 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3479 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3480 return NULL;
3482 switch(so_type) {
3483 case SOCK_DGRAM:
3484 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3485 case SOCK_STREAM:
3486 return net_socket_fd_init_stream(vlan, fd, is_connected);
3487 default:
3488 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3489 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3490 return net_socket_fd_init_stream(vlan, fd, is_connected);
3492 return NULL;
3495 static void net_socket_accept(void *opaque)
3497 NetSocketListenState *s = opaque;
3498 NetSocketState *s1;
3499 struct sockaddr_in saddr;
3500 socklen_t len;
3501 int fd;
3503 for(;;) {
3504 len = sizeof(saddr);
3505 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3506 if (fd < 0 && errno != EINTR) {
3507 return;
3508 } else if (fd >= 0) {
3509 break;
3512 s1 = net_socket_fd_init(s->vlan, fd, 1);
3513 if (!s1) {
3514 closesocket(fd);
3515 } else {
3516 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3517 "socket: connection from %s:%d",
3518 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3522 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3524 NetSocketListenState *s;
3525 int fd, val, ret;
3526 struct sockaddr_in saddr;
3528 if (parse_host_port(&saddr, host_str) < 0)
3529 return -1;
3531 s = qemu_mallocz(sizeof(NetSocketListenState));
3532 if (!s)
3533 return -1;
3535 fd = socket(PF_INET, SOCK_STREAM, 0);
3536 if (fd < 0) {
3537 perror("socket");
3538 return -1;
3540 socket_set_nonblock(fd);
3542 /* allow fast reuse */
3543 val = 1;
3544 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3546 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3547 if (ret < 0) {
3548 perror("bind");
3549 return -1;
3551 ret = listen(fd, 0);
3552 if (ret < 0) {
3553 perror("listen");
3554 return -1;
3556 s->vlan = vlan;
3557 s->fd = fd;
3558 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3559 return 0;
3562 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3564 NetSocketState *s;
3565 int fd, connected, ret, err;
3566 struct sockaddr_in saddr;
3568 if (parse_host_port(&saddr, host_str) < 0)
3569 return -1;
3571 fd = socket(PF_INET, SOCK_STREAM, 0);
3572 if (fd < 0) {
3573 perror("socket");
3574 return -1;
3576 socket_set_nonblock(fd);
3578 connected = 0;
3579 for(;;) {
3580 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3581 if (ret < 0) {
3582 err = socket_error();
3583 if (err == EINTR || err == EWOULDBLOCK) {
3584 } else if (err == EINPROGRESS) {
3585 break;
3586 } else {
3587 perror("connect");
3588 closesocket(fd);
3589 return -1;
3591 } else {
3592 connected = 1;
3593 break;
3596 s = net_socket_fd_init(vlan, fd, connected);
3597 if (!s)
3598 return -1;
3599 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3600 "socket: connect to %s:%d",
3601 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3602 return 0;
3605 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3607 NetSocketState *s;
3608 int fd;
3609 struct sockaddr_in saddr;
3611 if (parse_host_port(&saddr, host_str) < 0)
3612 return -1;
3615 fd = net_socket_mcast_create(&saddr);
3616 if (fd < 0)
3617 return -1;
3619 s = net_socket_fd_init(vlan, fd, 0);
3620 if (!s)
3621 return -1;
3623 s->dgram_dst = saddr;
3625 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3626 "socket: mcast=%s:%d",
3627 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3628 return 0;
3632 static int get_param_value(char *buf, int buf_size,
3633 const char *tag, const char *str)
3635 const char *p;
3636 char *q;
3637 char option[128];
3639 p = str;
3640 for(;;) {
3641 q = option;
3642 while (*p != '\0' && *p != '=') {
3643 if ((q - option) < sizeof(option) - 1)
3644 *q++ = *p;
3645 p++;
3647 *q = '\0';
3648 if (*p != '=')
3649 break;
3650 p++;
3651 if (!strcmp(tag, option)) {
3652 q = buf;
3653 while (*p != '\0' && *p != ',') {
3654 if ((q - buf) < buf_size - 1)
3655 *q++ = *p;
3656 p++;
3658 *q = '\0';
3659 return q - buf;
3660 } else {
3661 while (*p != '\0' && *p != ',') {
3662 p++;
3665 if (*p != ',')
3666 break;
3667 p++;
3669 return 0;
3672 int net_client_init(const char *str)
3674 const char *p;
3675 char *q;
3676 char device[64];
3677 char buf[1024];
3678 int vlan_id, ret;
3679 VLANState *vlan;
3681 p = str;
3682 q = device;
3683 while (*p != '\0' && *p != ',') {
3684 if ((q - device) < sizeof(device) - 1)
3685 *q++ = *p;
3686 p++;
3688 *q = '\0';
3689 if (*p == ',')
3690 p++;
3691 vlan_id = 0;
3692 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3693 vlan_id = strtol(buf, NULL, 0);
3695 vlan = qemu_find_vlan(vlan_id);
3696 if (!vlan) {
3697 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3698 return -1;
3700 if (!strcmp(device, "nic")) {
3701 NICInfo *nd;
3702 uint8_t *macaddr;
3704 if (nb_nics >= MAX_NICS) {
3705 fprintf(stderr, "Too Many NICs\n");
3706 return -1;
3708 nd = &nd_table[nb_nics];
3709 macaddr = nd->macaddr;
3710 macaddr[0] = 0x52;
3711 macaddr[1] = 0x54;
3712 macaddr[2] = 0x00;
3713 macaddr[3] = 0x12;
3714 macaddr[4] = 0x34;
3715 macaddr[5] = 0x56 + nb_nics;
3717 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3718 if (parse_macaddr(macaddr, buf) < 0) {
3719 fprintf(stderr, "invalid syntax for ethernet address\n");
3720 return -1;
3723 if (get_param_value(buf, sizeof(buf), "model", p)) {
3724 nd->model = strdup(buf);
3726 nd->vlan = vlan;
3727 nb_nics++;
3728 ret = 0;
3729 } else
3730 if (!strcmp(device, "none")) {
3731 /* does nothing. It is needed to signal that no network cards
3732 are wanted */
3733 ret = 0;
3734 } else
3735 #ifdef CONFIG_SLIRP
3736 if (!strcmp(device, "user")) {
3737 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3738 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3740 ret = net_slirp_init(vlan);
3741 } else
3742 #endif
3743 #ifdef _WIN32
3744 if (!strcmp(device, "tap")) {
3745 char ifname[64];
3746 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3747 fprintf(stderr, "tap: no interface name\n");
3748 return -1;
3750 ret = tap_win32_init(vlan, ifname);
3751 } else
3752 #else
3753 if (!strcmp(device, "tap")) {
3754 char ifname[64];
3755 char setup_script[1024];
3756 char bridge[16];
3757 int fd;
3758 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3759 fd = strtol(buf, NULL, 0);
3760 ret = -1;
3761 if (net_tap_fd_init(vlan, fd))
3762 ret = 0;
3763 } else {
3764 ifname[0] = '\0';
3765 get_param_value(ifname, sizeof(ifname), "ifname", p);
3766 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3767 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3769 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3770 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3772 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3774 } else
3775 #endif
3776 if (!strcmp(device, "socket")) {
3777 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3778 int fd;
3779 fd = strtol(buf, NULL, 0);
3780 ret = -1;
3781 if (net_socket_fd_init(vlan, fd, 1))
3782 ret = 0;
3783 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3784 ret = net_socket_listen_init(vlan, buf);
3785 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3786 ret = net_socket_connect_init(vlan, buf);
3787 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3788 ret = net_socket_mcast_init(vlan, buf);
3789 } else {
3790 fprintf(stderr, "Unknown socket options: %s\n", p);
3791 return -1;
3793 } else
3795 fprintf(stderr, "Unknown network device: %s\n", device);
3796 return -1;
3798 if (ret < 0) {
3799 fprintf(stderr, "Could not initialize device '%s'\n", device);
3802 return ret;
3805 void do_info_network(void)
3807 VLANState *vlan;
3808 VLANClientState *vc;
3810 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3811 term_printf("VLAN %d devices:\n", vlan->id);
3812 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3813 term_printf(" %s\n", vc->info_str);
3817 /***********************************************************/
3818 /* USB devices */
3820 static USBPort *used_usb_ports;
3821 static USBPort *free_usb_ports;
3823 /* ??? Maybe change this to register a hub to keep track of the topology. */
3824 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3825 usb_attachfn attach)
3827 port->opaque = opaque;
3828 port->index = index;
3829 port->attach = attach;
3830 port->next = free_usb_ports;
3831 free_usb_ports = port;
3834 static int usb_device_add(const char *devname)
3836 const char *p;
3837 USBDevice *dev;
3838 USBPort *port;
3840 if (!free_usb_ports)
3841 return -1;
3843 if (strstart(devname, "host:", &p)) {
3844 dev = usb_host_device_open(p);
3845 } else if (!strcmp(devname, "mouse")) {
3846 dev = usb_mouse_init();
3847 } else if (!strcmp(devname, "tablet")) {
3848 dev = usb_tablet_init();
3849 } else if (strstart(devname, "disk:", &p)) {
3850 dev = usb_msd_init(p);
3851 } else {
3852 return -1;
3854 if (!dev)
3855 return -1;
3857 /* Find a USB port to add the device to. */
3858 port = free_usb_ports;
3859 if (!port->next) {
3860 USBDevice *hub;
3862 /* Create a new hub and chain it on. */
3863 free_usb_ports = NULL;
3864 port->next = used_usb_ports;
3865 used_usb_ports = port;
3867 hub = usb_hub_init(VM_USB_HUB_SIZE);
3868 usb_attach(port, hub);
3869 port = free_usb_ports;
3872 free_usb_ports = port->next;
3873 port->next = used_usb_ports;
3874 used_usb_ports = port;
3875 usb_attach(port, dev);
3876 return 0;
3879 static int usb_device_del(const char *devname)
3881 USBPort *port;
3882 USBPort **lastp;
3883 USBDevice *dev;
3884 int bus_num, addr;
3885 const char *p;
3887 if (!used_usb_ports)
3888 return -1;
3890 p = strchr(devname, '.');
3891 if (!p)
3892 return -1;
3893 bus_num = strtoul(devname, NULL, 0);
3894 addr = strtoul(p + 1, NULL, 0);
3895 if (bus_num != 0)
3896 return -1;
3898 lastp = &used_usb_ports;
3899 port = used_usb_ports;
3900 while (port && port->dev->addr != addr) {
3901 lastp = &port->next;
3902 port = port->next;
3905 if (!port)
3906 return -1;
3908 dev = port->dev;
3909 *lastp = port->next;
3910 usb_attach(port, NULL);
3911 dev->handle_destroy(dev);
3912 port->next = free_usb_ports;
3913 free_usb_ports = port;
3914 return 0;
3917 void do_usb_add(const char *devname)
3919 int ret;
3920 ret = usb_device_add(devname);
3921 if (ret < 0)
3922 term_printf("Could not add USB device '%s'\n", devname);
3925 void do_usb_del(const char *devname)
3927 int ret;
3928 ret = usb_device_del(devname);
3929 if (ret < 0)
3930 term_printf("Could not remove USB device '%s'\n", devname);
3933 void usb_info(void)
3935 USBDevice *dev;
3936 USBPort *port;
3937 const char *speed_str;
3939 if (!usb_enabled) {
3940 term_printf("USB support not enabled\n");
3941 return;
3944 for (port = used_usb_ports; port; port = port->next) {
3945 dev = port->dev;
3946 if (!dev)
3947 continue;
3948 switch(dev->speed) {
3949 case USB_SPEED_LOW:
3950 speed_str = "1.5";
3951 break;
3952 case USB_SPEED_FULL:
3953 speed_str = "12";
3954 break;
3955 case USB_SPEED_HIGH:
3956 speed_str = "480";
3957 break;
3958 default:
3959 speed_str = "?";
3960 break;
3962 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3963 0, dev->addr, speed_str, dev->devname);
3967 /***********************************************************/
3968 /* pid file */
3970 static char *pid_filename;
3972 /* Remove PID file. Called on normal exit */
3974 static void remove_pidfile(void)
3976 unlink (pid_filename);
3979 static void create_pidfile(const char *filename)
3981 struct stat pidstat;
3982 FILE *f;
3984 /* Try to write our PID to the named file */
3985 if (stat(filename, &pidstat) < 0) {
3986 if (errno == ENOENT) {
3987 if ((f = fopen (filename, "w")) == NULL) {
3988 perror("Opening pidfile");
3989 exit(1);
3991 fprintf(f, "%d\n", getpid());
3992 fclose(f);
3993 pid_filename = qemu_strdup(filename);
3994 if (!pid_filename) {
3995 fprintf(stderr, "Could not save PID filename");
3996 exit(1);
3998 atexit(remove_pidfile);
4000 } else {
4001 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4002 filename);
4003 exit(1);
4007 /***********************************************************/
4008 /* dumb display */
4010 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4014 static void dumb_resize(DisplayState *ds, int w, int h)
4018 static void dumb_refresh(DisplayState *ds)
4020 vga_hw_update();
4023 void dumb_display_init(DisplayState *ds)
4025 ds->data = NULL;
4026 ds->linesize = 0;
4027 ds->depth = 0;
4028 ds->dpy_update = dumb_update;
4029 ds->dpy_resize = dumb_resize;
4030 ds->dpy_refresh = dumb_refresh;
4033 /***********************************************************/
4034 /* I/O handling */
4036 #define MAX_IO_HANDLERS 64
4038 typedef struct IOHandlerRecord {
4039 int fd;
4040 IOCanRWHandler *fd_read_poll;
4041 IOHandler *fd_read;
4042 IOHandler *fd_write;
4043 void *opaque;
4044 /* temporary data */
4045 struct pollfd *ufd;
4046 struct IOHandlerRecord *next;
4047 } IOHandlerRecord;
4049 static IOHandlerRecord *first_io_handler;
4051 /* XXX: fd_read_poll should be suppressed, but an API change is
4052 necessary in the character devices to suppress fd_can_read(). */
4053 int qemu_set_fd_handler2(int fd,
4054 IOCanRWHandler *fd_read_poll,
4055 IOHandler *fd_read,
4056 IOHandler *fd_write,
4057 void *opaque)
4059 IOHandlerRecord **pioh, *ioh;
4061 if (!fd_read && !fd_write) {
4062 pioh = &first_io_handler;
4063 for(;;) {
4064 ioh = *pioh;
4065 if (ioh == NULL)
4066 break;
4067 if (ioh->fd == fd) {
4068 *pioh = ioh->next;
4069 qemu_free(ioh);
4070 break;
4072 pioh = &ioh->next;
4074 } else {
4075 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4076 if (ioh->fd == fd)
4077 goto found;
4079 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4080 if (!ioh)
4081 return -1;
4082 ioh->next = first_io_handler;
4083 first_io_handler = ioh;
4084 found:
4085 ioh->fd = fd;
4086 ioh->fd_read_poll = fd_read_poll;
4087 ioh->fd_read = fd_read;
4088 ioh->fd_write = fd_write;
4089 ioh->opaque = opaque;
4091 return 0;
4094 int qemu_set_fd_handler(int fd,
4095 IOHandler *fd_read,
4096 IOHandler *fd_write,
4097 void *opaque)
4099 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4102 /***********************************************************/
4103 /* Polling handling */
4105 typedef struct PollingEntry {
4106 PollingFunc *func;
4107 void *opaque;
4108 struct PollingEntry *next;
4109 } PollingEntry;
4111 static PollingEntry *first_polling_entry;
4113 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4115 PollingEntry **ppe, *pe;
4116 pe = qemu_mallocz(sizeof(PollingEntry));
4117 if (!pe)
4118 return -1;
4119 pe->func = func;
4120 pe->opaque = opaque;
4121 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4122 *ppe = pe;
4123 return 0;
4126 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4128 PollingEntry **ppe, *pe;
4129 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4130 pe = *ppe;
4131 if (pe->func == func && pe->opaque == opaque) {
4132 *ppe = pe->next;
4133 qemu_free(pe);
4134 break;
4139 #ifdef _WIN32
4140 /***********************************************************/
4141 /* Wait objects support */
4142 typedef struct WaitObjects {
4143 int num;
4144 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4145 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4146 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4147 } WaitObjects;
4149 static WaitObjects wait_objects = {0};
4151 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4153 WaitObjects *w = &wait_objects;
4155 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4156 return -1;
4157 w->events[w->num] = handle;
4158 w->func[w->num] = func;
4159 w->opaque[w->num] = opaque;
4160 w->num++;
4161 return 0;
4164 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4166 int i, found;
4167 WaitObjects *w = &wait_objects;
4169 found = 0;
4170 for (i = 0; i < w->num; i++) {
4171 if (w->events[i] == handle)
4172 found = 1;
4173 if (found) {
4174 w->events[i] = w->events[i + 1];
4175 w->func[i] = w->func[i + 1];
4176 w->opaque[i] = w->opaque[i + 1];
4179 if (found)
4180 w->num--;
4182 #endif
4184 /***********************************************************/
4185 /* savevm/loadvm support */
4187 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4189 fwrite(buf, 1, size, f);
4192 void qemu_put_byte(QEMUFile *f, int v)
4194 fputc(v, f);
4197 void qemu_put_be16(QEMUFile *f, unsigned int v)
4199 qemu_put_byte(f, v >> 8);
4200 qemu_put_byte(f, v);
4203 void qemu_put_be32(QEMUFile *f, unsigned int v)
4205 qemu_put_byte(f, v >> 24);
4206 qemu_put_byte(f, v >> 16);
4207 qemu_put_byte(f, v >> 8);
4208 qemu_put_byte(f, v);
4211 void qemu_put_be64(QEMUFile *f, uint64_t v)
4213 qemu_put_be32(f, v >> 32);
4214 qemu_put_be32(f, v);
4217 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4219 return fread(buf, 1, size, f);
4222 int qemu_get_byte(QEMUFile *f)
4224 int v;
4225 v = fgetc(f);
4226 if (v == EOF)
4227 return 0;
4228 else
4229 return v;
4232 unsigned int qemu_get_be16(QEMUFile *f)
4234 unsigned int v;
4235 v = qemu_get_byte(f) << 8;
4236 v |= qemu_get_byte(f);
4237 return v;
4240 unsigned int qemu_get_be32(QEMUFile *f)
4242 unsigned int v;
4243 v = qemu_get_byte(f) << 24;
4244 v |= qemu_get_byte(f) << 16;
4245 v |= qemu_get_byte(f) << 8;
4246 v |= qemu_get_byte(f);
4247 return v;
4250 uint64_t qemu_get_be64(QEMUFile *f)
4252 uint64_t v;
4253 v = (uint64_t)qemu_get_be32(f) << 32;
4254 v |= qemu_get_be32(f);
4255 return v;
4258 int64_t qemu_ftell(QEMUFile *f)
4260 return ftell(f);
4263 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4265 if (fseek(f, pos, whence) < 0)
4266 return -1;
4267 return ftell(f);
4270 typedef struct SaveStateEntry {
4271 char idstr[256];
4272 int instance_id;
4273 int version_id;
4274 SaveStateHandler *save_state;
4275 LoadStateHandler *load_state;
4276 void *opaque;
4277 struct SaveStateEntry *next;
4278 } SaveStateEntry;
4280 static SaveStateEntry *first_se;
4282 int register_savevm(const char *idstr,
4283 int instance_id,
4284 int version_id,
4285 SaveStateHandler *save_state,
4286 LoadStateHandler *load_state,
4287 void *opaque)
4289 SaveStateEntry *se, **pse;
4291 se = qemu_malloc(sizeof(SaveStateEntry));
4292 if (!se)
4293 return -1;
4294 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4295 se->instance_id = instance_id;
4296 se->version_id = version_id;
4297 se->save_state = save_state;
4298 se->load_state = load_state;
4299 se->opaque = opaque;
4300 se->next = NULL;
4302 /* add at the end of list */
4303 pse = &first_se;
4304 while (*pse != NULL)
4305 pse = &(*pse)->next;
4306 *pse = se;
4307 return 0;
4310 #define QEMU_VM_FILE_MAGIC 0x5145564d
4311 #define QEMU_VM_FILE_VERSION 0x00000001
4313 int qemu_savevm(const char *filename)
4315 SaveStateEntry *se;
4316 QEMUFile *f;
4317 int len, len_pos, cur_pos, saved_vm_running, ret;
4319 saved_vm_running = vm_running;
4320 vm_stop(0);
4322 f = fopen(filename, "wb");
4323 if (!f) {
4324 ret = -1;
4325 goto the_end;
4328 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4329 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4331 for(se = first_se; se != NULL; se = se->next) {
4332 /* ID string */
4333 len = strlen(se->idstr);
4334 qemu_put_byte(f, len);
4335 qemu_put_buffer(f, se->idstr, len);
4337 qemu_put_be32(f, se->instance_id);
4338 qemu_put_be32(f, se->version_id);
4340 /* record size: filled later */
4341 len_pos = ftell(f);
4342 qemu_put_be32(f, 0);
4344 se->save_state(f, se->opaque);
4346 /* fill record size */
4347 cur_pos = ftell(f);
4348 len = ftell(f) - len_pos - 4;
4349 fseek(f, len_pos, SEEK_SET);
4350 qemu_put_be32(f, len);
4351 fseek(f, cur_pos, SEEK_SET);
4354 fclose(f);
4355 ret = 0;
4356 the_end:
4357 if (saved_vm_running)
4358 vm_start();
4359 return ret;
4362 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4364 SaveStateEntry *se;
4366 for(se = first_se; se != NULL; se = se->next) {
4367 if (!strcmp(se->idstr, idstr) &&
4368 instance_id == se->instance_id)
4369 return se;
4371 return NULL;
4374 int qemu_loadvm(const char *filename)
4376 SaveStateEntry *se;
4377 QEMUFile *f;
4378 int len, cur_pos, ret, instance_id, record_len, version_id;
4379 int saved_vm_running;
4380 unsigned int v;
4381 char idstr[256];
4383 saved_vm_running = vm_running;
4384 vm_stop(0);
4386 f = fopen(filename, "rb");
4387 if (!f) {
4388 ret = -1;
4389 goto the_end;
4392 v = qemu_get_be32(f);
4393 if (v != QEMU_VM_FILE_MAGIC)
4394 goto fail;
4395 v = qemu_get_be32(f);
4396 if (v != QEMU_VM_FILE_VERSION) {
4397 fail:
4398 fclose(f);
4399 ret = -1;
4400 goto the_end;
4402 for(;;) {
4403 len = qemu_get_byte(f);
4404 if (feof(f))
4405 break;
4406 qemu_get_buffer(f, idstr, len);
4407 idstr[len] = '\0';
4408 instance_id = qemu_get_be32(f);
4409 version_id = qemu_get_be32(f);
4410 record_len = qemu_get_be32(f);
4411 #if 0
4412 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4413 idstr, instance_id, version_id, record_len);
4414 #endif
4415 cur_pos = ftell(f);
4416 se = find_se(idstr, instance_id);
4417 if (!se) {
4418 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4419 instance_id, idstr);
4420 } else {
4421 ret = se->load_state(f, se->opaque, version_id);
4422 if (ret < 0) {
4423 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4424 instance_id, idstr);
4427 /* always seek to exact end of record */
4428 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4430 fclose(f);
4431 ret = 0;
4432 the_end:
4433 if (saved_vm_running)
4434 vm_start();
4435 return ret;
4438 #ifndef CONFIG_DM
4439 /***********************************************************/
4440 /* cpu save/restore */
4442 #if defined(TARGET_I386)
4444 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4446 qemu_put_be32(f, dt->selector);
4447 qemu_put_betl(f, dt->base);
4448 qemu_put_be32(f, dt->limit);
4449 qemu_put_be32(f, dt->flags);
4452 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4454 dt->selector = qemu_get_be32(f);
4455 dt->base = qemu_get_betl(f);
4456 dt->limit = qemu_get_be32(f);
4457 dt->flags = qemu_get_be32(f);
4460 void cpu_save(QEMUFile *f, void *opaque)
4462 CPUState *env = opaque;
4463 uint16_t fptag, fpus, fpuc, fpregs_format;
4464 uint32_t hflags;
4465 int i;
4467 for(i = 0; i < CPU_NB_REGS; i++)
4468 qemu_put_betls(f, &env->regs[i]);
4469 qemu_put_betls(f, &env->eip);
4470 qemu_put_betls(f, &env->eflags);
4471 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4472 qemu_put_be32s(f, &hflags);
4474 /* FPU */
4475 fpuc = env->fpuc;
4476 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4477 fptag = 0;
4478 for(i = 0; i < 8; i++) {
4479 fptag |= ((!env->fptags[i]) << i);
4482 qemu_put_be16s(f, &fpuc);
4483 qemu_put_be16s(f, &fpus);
4484 qemu_put_be16s(f, &fptag);
4486 #ifdef USE_X86LDOUBLE
4487 fpregs_format = 0;
4488 #else
4489 fpregs_format = 1;
4490 #endif
4491 qemu_put_be16s(f, &fpregs_format);
4493 for(i = 0; i < 8; i++) {
4494 #ifdef USE_X86LDOUBLE
4496 uint64_t mant;
4497 uint16_t exp;
4498 /* we save the real CPU data (in case of MMX usage only 'mant'
4499 contains the MMX register */
4500 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4501 qemu_put_be64(f, mant);
4502 qemu_put_be16(f, exp);
4504 #else
4505 /* if we use doubles for float emulation, we save the doubles to
4506 avoid losing information in case of MMX usage. It can give
4507 problems if the image is restored on a CPU where long
4508 doubles are used instead. */
4509 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4510 #endif
4513 for(i = 0; i < 6; i++)
4514 cpu_put_seg(f, &env->segs[i]);
4515 cpu_put_seg(f, &env->ldt);
4516 cpu_put_seg(f, &env->tr);
4517 cpu_put_seg(f, &env->gdt);
4518 cpu_put_seg(f, &env->idt);
4520 qemu_put_be32s(f, &env->sysenter_cs);
4521 qemu_put_be32s(f, &env->sysenter_esp);
4522 qemu_put_be32s(f, &env->sysenter_eip);
4524 qemu_put_betls(f, &env->cr[0]);
4525 qemu_put_betls(f, &env->cr[2]);
4526 qemu_put_betls(f, &env->cr[3]);
4527 qemu_put_betls(f, &env->cr[4]);
4529 for(i = 0; i < 8; i++)
4530 qemu_put_betls(f, &env->dr[i]);
4532 /* MMU */
4533 qemu_put_be32s(f, &env->a20_mask);
4535 /* XMM */
4536 qemu_put_be32s(f, &env->mxcsr);
4537 for(i = 0; i < CPU_NB_REGS; i++) {
4538 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4539 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4542 #ifdef TARGET_X86_64
4543 qemu_put_be64s(f, &env->efer);
4544 qemu_put_be64s(f, &env->star);
4545 qemu_put_be64s(f, &env->lstar);
4546 qemu_put_be64s(f, &env->cstar);
4547 qemu_put_be64s(f, &env->fmask);
4548 qemu_put_be64s(f, &env->kernelgsbase);
4549 #endif
4552 #ifdef USE_X86LDOUBLE
4553 /* XXX: add that in a FPU generic layer */
4554 union x86_longdouble {
4555 uint64_t mant;
4556 uint16_t exp;
4557 };
4559 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4560 #define EXPBIAS1 1023
4561 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4562 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4564 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4566 int e;
4567 /* mantissa */
4568 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4569 /* exponent + sign */
4570 e = EXPD1(temp) - EXPBIAS1 + 16383;
4571 e |= SIGND1(temp) >> 16;
4572 p->exp = e;
4574 #endif
4576 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4578 CPUState *env = opaque;
4579 int i, guess_mmx;
4580 uint32_t hflags;
4581 uint16_t fpus, fpuc, fptag, fpregs_format;
4583 if (version_id != 3)
4584 return -EINVAL;
4585 for(i = 0; i < CPU_NB_REGS; i++)
4586 qemu_get_betls(f, &env->regs[i]);
4587 qemu_get_betls(f, &env->eip);
4588 qemu_get_betls(f, &env->eflags);
4589 qemu_get_be32s(f, &hflags);
4591 qemu_get_be16s(f, &fpuc);
4592 qemu_get_be16s(f, &fpus);
4593 qemu_get_be16s(f, &fptag);
4594 qemu_get_be16s(f, &fpregs_format);
4596 /* NOTE: we cannot always restore the FPU state if the image come
4597 from a host with a different 'USE_X86LDOUBLE' define. We guess
4598 if we are in an MMX state to restore correctly in that case. */
4599 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4600 for(i = 0; i < 8; i++) {
4601 uint64_t mant;
4602 uint16_t exp;
4604 switch(fpregs_format) {
4605 case 0:
4606 mant = qemu_get_be64(f);
4607 exp = qemu_get_be16(f);
4608 #ifdef USE_X86LDOUBLE
4609 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4610 #else
4611 /* difficult case */
4612 if (guess_mmx)
4613 env->fpregs[i].mmx.MMX_Q(0) = mant;
4614 else
4615 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4616 #endif
4617 break;
4618 case 1:
4619 mant = qemu_get_be64(f);
4620 #ifdef USE_X86LDOUBLE
4622 union x86_longdouble *p;
4623 /* difficult case */
4624 p = (void *)&env->fpregs[i];
4625 if (guess_mmx) {
4626 p->mant = mant;
4627 p->exp = 0xffff;
4628 } else {
4629 fp64_to_fp80(p, mant);
4632 #else
4633 env->fpregs[i].mmx.MMX_Q(0) = mant;
4634 #endif
4635 break;
4636 default:
4637 return -EINVAL;
4641 env->fpuc = fpuc;
4642 /* XXX: restore FPU round state */
4643 env->fpstt = (fpus >> 11) & 7;
4644 env->fpus = fpus & ~0x3800;
4645 fptag ^= 0xff;
4646 for(i = 0; i < 8; i++) {
4647 env->fptags[i] = (fptag >> i) & 1;
4650 for(i = 0; i < 6; i++)
4651 cpu_get_seg(f, &env->segs[i]);
4652 cpu_get_seg(f, &env->ldt);
4653 cpu_get_seg(f, &env->tr);
4654 cpu_get_seg(f, &env->gdt);
4655 cpu_get_seg(f, &env->idt);
4657 qemu_get_be32s(f, &env->sysenter_cs);
4658 qemu_get_be32s(f, &env->sysenter_esp);
4659 qemu_get_be32s(f, &env->sysenter_eip);
4661 qemu_get_betls(f, &env->cr[0]);
4662 qemu_get_betls(f, &env->cr[2]);
4663 qemu_get_betls(f, &env->cr[3]);
4664 qemu_get_betls(f, &env->cr[4]);
4666 for(i = 0; i < 8; i++)
4667 qemu_get_betls(f, &env->dr[i]);
4669 /* MMU */
4670 qemu_get_be32s(f, &env->a20_mask);
4672 qemu_get_be32s(f, &env->mxcsr);
4673 for(i = 0; i < CPU_NB_REGS; i++) {
4674 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4675 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4678 #ifdef TARGET_X86_64
4679 qemu_get_be64s(f, &env->efer);
4680 qemu_get_be64s(f, &env->star);
4681 qemu_get_be64s(f, &env->lstar);
4682 qemu_get_be64s(f, &env->cstar);
4683 qemu_get_be64s(f, &env->fmask);
4684 qemu_get_be64s(f, &env->kernelgsbase);
4685 #endif
4687 /* XXX: compute hflags from scratch, except for CPL and IIF */
4688 env->hflags = hflags;
4689 tlb_flush(env, 1);
4690 return 0;
4693 #elif defined(TARGET_PPC)
4694 void cpu_save(QEMUFile *f, void *opaque)
4698 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4700 return 0;
4703 #elif defined(TARGET_MIPS)
4704 void cpu_save(QEMUFile *f, void *opaque)
4708 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4710 return 0;
4713 #elif defined(TARGET_SPARC)
4714 void cpu_save(QEMUFile *f, void *opaque)
4716 CPUState *env = opaque;
4717 int i;
4718 uint32_t tmp;
4720 for(i = 0; i < 8; i++)
4721 qemu_put_betls(f, &env->gregs[i]);
4722 for(i = 0; i < NWINDOWS * 16; i++)
4723 qemu_put_betls(f, &env->regbase[i]);
4725 /* FPU */
4726 for(i = 0; i < TARGET_FPREGS; i++) {
4727 union {
4728 float32 f;
4729 uint32_t i;
4730 } u;
4731 u.f = env->fpr[i];
4732 qemu_put_be32(f, u.i);
4735 qemu_put_betls(f, &env->pc);
4736 qemu_put_betls(f, &env->npc);
4737 qemu_put_betls(f, &env->y);
4738 tmp = GET_PSR(env);
4739 qemu_put_be32(f, tmp);
4740 qemu_put_betls(f, &env->fsr);
4741 qemu_put_betls(f, &env->tbr);
4742 #ifndef TARGET_SPARC64
4743 qemu_put_be32s(f, &env->wim);
4744 /* MMU */
4745 for(i = 0; i < 16; i++)
4746 qemu_put_be32s(f, &env->mmuregs[i]);
4747 #endif
4750 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4752 CPUState *env = opaque;
4753 int i;
4754 uint32_t tmp;
4756 for(i = 0; i < 8; i++)
4757 qemu_get_betls(f, &env->gregs[i]);
4758 for(i = 0; i < NWINDOWS * 16; i++)
4759 qemu_get_betls(f, &env->regbase[i]);
4761 /* FPU */
4762 for(i = 0; i < TARGET_FPREGS; i++) {
4763 union {
4764 float32 f;
4765 uint32_t i;
4766 } u;
4767 u.i = qemu_get_be32(f);
4768 env->fpr[i] = u.f;
4771 qemu_get_betls(f, &env->pc);
4772 qemu_get_betls(f, &env->npc);
4773 qemu_get_betls(f, &env->y);
4774 tmp = qemu_get_be32(f);
4775 env->cwp = 0; /* needed to ensure that the wrapping registers are
4776 correctly updated */
4777 PUT_PSR(env, tmp);
4778 qemu_get_betls(f, &env->fsr);
4779 qemu_get_betls(f, &env->tbr);
4780 #ifndef TARGET_SPARC64
4781 qemu_get_be32s(f, &env->wim);
4782 /* MMU */
4783 for(i = 0; i < 16; i++)
4784 qemu_get_be32s(f, &env->mmuregs[i]);
4785 #endif
4786 tlb_flush(env, 1);
4787 return 0;
4790 #elif defined(TARGET_ARM)
4792 /* ??? Need to implement these. */
4793 void cpu_save(QEMUFile *f, void *opaque)
4797 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4799 return 0;
4802 #else
4804 #warning No CPU save/restore functions
4806 #endif
4808 /***********************************************************/
4809 /* ram save/restore */
4811 /* we just avoid storing empty pages */
4812 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4814 int i, v;
4816 v = buf[0];
4817 for(i = 1; i < len; i++) {
4818 if (buf[i] != v)
4819 goto normal_save;
4821 qemu_put_byte(f, 1);
4822 qemu_put_byte(f, v);
4823 return;
4824 normal_save:
4825 qemu_put_byte(f, 0);
4826 qemu_put_buffer(f, buf, len);
4829 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4831 int v;
4833 v = qemu_get_byte(f);
4834 switch(v) {
4835 case 0:
4836 if (qemu_get_buffer(f, buf, len) != len)
4837 return -EIO;
4838 break;
4839 case 1:
4840 v = qemu_get_byte(f);
4841 memset(buf, v, len);
4842 break;
4843 default:
4844 return -EINVAL;
4846 return 0;
4849 static void ram_save(QEMUFile *f, void *opaque)
4851 int i;
4852 qemu_put_be32(f, phys_ram_size);
4853 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4854 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4858 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4860 int i, ret;
4862 if (version_id != 1)
4863 return -EINVAL;
4864 if (qemu_get_be32(f) != phys_ram_size)
4865 return -EINVAL;
4866 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4867 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4868 if (ret)
4869 return ret;
4871 return 0;
4873 #else /* CONFIG_DM */
4874 void cpu_save(QEMUFile *f, void *opaque)
4878 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4880 return 0;
4883 static void ram_save(QEMUFile *f, void *opaque)
4887 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4889 return 0;
4891 #endif /* CONFIG_DM */
4893 /***********************************************************/
4894 /* machine registration */
4896 QEMUMachine *first_machine = NULL;
4898 int qemu_register_machine(QEMUMachine *m)
4900 QEMUMachine **pm;
4901 pm = &first_machine;
4902 while (*pm != NULL)
4903 pm = &(*pm)->next;
4904 m->next = NULL;
4905 *pm = m;
4906 return 0;
4909 QEMUMachine *find_machine(const char *name)
4911 QEMUMachine *m;
4913 for(m = first_machine; m != NULL; m = m->next) {
4914 if (!strcmp(m->name, name))
4915 return m;
4917 return NULL;
4920 /***********************************************************/
4921 /* main execution loop */
4923 void gui_update(void *opaque)
4925 display_state.dpy_refresh(&display_state);
4926 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4929 struct vm_change_state_entry {
4930 VMChangeStateHandler *cb;
4931 void *opaque;
4932 LIST_ENTRY (vm_change_state_entry) entries;
4933 };
4935 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4937 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4938 void *opaque)
4940 VMChangeStateEntry *e;
4942 e = qemu_mallocz(sizeof (*e));
4943 if (!e)
4944 return NULL;
4946 e->cb = cb;
4947 e->opaque = opaque;
4948 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4949 return e;
4952 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4954 LIST_REMOVE (e, entries);
4955 qemu_free (e);
4958 static void vm_state_notify(int running)
4960 VMChangeStateEntry *e;
4962 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4963 e->cb(e->opaque, running);
4967 /* XXX: support several handlers */
4968 static VMStopHandler *vm_stop_cb;
4969 static void *vm_stop_opaque;
4971 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4973 vm_stop_cb = cb;
4974 vm_stop_opaque = opaque;
4975 return 0;
4978 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4980 vm_stop_cb = NULL;
4983 void vm_start(void)
4985 if (!vm_running) {
4986 cpu_enable_ticks();
4987 vm_running = 1;
4988 vm_state_notify(1);
4992 void vm_stop(int reason)
4994 if (vm_running) {
4995 cpu_disable_ticks();
4996 vm_running = 0;
4997 if (reason != 0) {
4998 if (vm_stop_cb) {
4999 vm_stop_cb(vm_stop_opaque, reason);
5002 vm_state_notify(0);
5006 /* reset/shutdown handler */
5008 typedef struct QEMUResetEntry {
5009 QEMUResetHandler *func;
5010 void *opaque;
5011 struct QEMUResetEntry *next;
5012 } QEMUResetEntry;
5014 static QEMUResetEntry *first_reset_entry;
5015 int reset_requested;
5016 int shutdown_requested;
5017 static int powerdown_requested;
5019 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5021 QEMUResetEntry **pre, *re;
5023 pre = &first_reset_entry;
5024 while (*pre != NULL)
5025 pre = &(*pre)->next;
5026 re = qemu_mallocz(sizeof(QEMUResetEntry));
5027 re->func = func;
5028 re->opaque = opaque;
5029 re->next = NULL;
5030 *pre = re;
5033 void qemu_system_reset(void)
5035 QEMUResetEntry *re;
5037 /* reset all devices */
5038 for(re = first_reset_entry; re != NULL; re = re->next) {
5039 re->func(re->opaque);
5043 void qemu_system_reset_request(void)
5045 reset_requested = 1;
5046 if (cpu_single_env)
5047 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5050 void qemu_system_shutdown_request(void)
5052 shutdown_requested = 1;
5053 if (cpu_single_env)
5054 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5057 void qemu_system_powerdown_request(void)
5059 powerdown_requested = 1;
5060 if (cpu_single_env)
5061 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5064 void main_loop_wait(int timeout)
5066 IOHandlerRecord *ioh, *ioh_next;
5067 fd_set rfds, wfds, xfds;
5068 int ret, nfds;
5069 struct timeval tv;
5070 PollingEntry *pe;
5073 /* XXX: need to suppress polling by better using win32 events */
5074 ret = 0;
5075 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5076 ret |= pe->func(pe->opaque);
5078 #ifdef _WIN32
5079 if (ret == 0 && timeout > 0) {
5080 int err;
5081 WaitObjects *w = &wait_objects;
5083 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5084 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5085 if (w->func[ret - WAIT_OBJECT_0])
5086 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5087 } else if (ret == WAIT_TIMEOUT) {
5088 } else {
5089 err = GetLastError();
5090 fprintf(stderr, "Wait error %d %d\n", ret, err);
5093 #endif
5094 /* poll any events */
5095 /* XXX: separate device handlers from system ones */
5096 nfds = -1;
5097 FD_ZERO(&rfds);
5098 FD_ZERO(&wfds);
5099 FD_ZERO(&xfds);
5100 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5101 if (ioh->fd_read &&
5102 (!ioh->fd_read_poll ||
5103 ioh->fd_read_poll(ioh->opaque) != 0)) {
5104 FD_SET(ioh->fd, &rfds);
5105 if (ioh->fd > nfds)
5106 nfds = ioh->fd;
5108 if (ioh->fd_write) {
5109 FD_SET(ioh->fd, &wfds);
5110 if (ioh->fd > nfds)
5111 nfds = ioh->fd;
5115 tv.tv_sec = 0;
5116 #ifdef _WIN32
5117 tv.tv_usec = 0;
5118 #else
5119 tv.tv_usec = timeout * 1000;
5120 #endif
5121 #if defined(CONFIG_SLIRP)
5122 if (slirp_inited) {
5123 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5125 #endif
5126 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5127 if (ret > 0) {
5128 /* XXX: better handling of removal */
5129 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5130 ioh_next = ioh->next;
5131 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
5132 ioh->fd_read(ioh->opaque);
5134 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
5135 ioh->fd_write(ioh->opaque);
5139 #if defined(CONFIG_SLIRP)
5140 if (slirp_inited) {
5141 if (ret < 0) {
5142 FD_ZERO(&rfds);
5143 FD_ZERO(&wfds);
5144 FD_ZERO(&xfds);
5146 slirp_select_poll(&rfds, &wfds, &xfds);
5148 #endif
5149 #ifdef _WIN32
5150 tap_win32_poll();
5151 #endif
5153 if (vm_running) {
5154 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5155 qemu_get_clock(vm_clock));
5156 /* run dma transfers, if any */
5157 DMA_run();
5160 /* real time timers */
5161 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5162 qemu_get_clock(rt_clock));
5165 #ifndef CONFIG_DM
5166 static CPUState *cur_cpu;
5168 int main_loop(void)
5170 int ret, timeout;
5171 #ifdef CONFIG_PROFILER
5172 int64_t ti;
5173 #endif
5174 CPUState *env;
5176 cur_cpu = first_cpu;
5177 for(;;) {
5178 if (vm_running) {
5180 env = cur_cpu;
5181 for(;;) {
5182 /* get next cpu */
5183 env = env->next_cpu;
5184 if (!env)
5185 env = first_cpu;
5186 #ifdef CONFIG_PROFILER
5187 ti = profile_getclock();
5188 #endif
5189 ret = cpu_exec(env);
5190 #ifdef CONFIG_PROFILER
5191 qemu_time += profile_getclock() - ti;
5192 #endif
5193 if (ret != EXCP_HALTED)
5194 break;
5195 /* all CPUs are halted ? */
5196 if (env == cur_cpu) {
5197 ret = EXCP_HLT;
5198 break;
5201 cur_cpu = env;
5203 if (shutdown_requested) {
5204 ret = EXCP_INTERRUPT;
5205 break;
5207 if (reset_requested) {
5208 reset_requested = 0;
5209 qemu_system_reset();
5210 ret = EXCP_INTERRUPT;
5212 if (powerdown_requested) {
5213 powerdown_requested = 0;
5214 qemu_system_powerdown();
5215 ret = EXCP_INTERRUPT;
5217 if (ret == EXCP_DEBUG) {
5218 vm_stop(EXCP_DEBUG);
5220 /* if hlt instruction, we wait until the next IRQ */
5221 /* XXX: use timeout computed from timers */
5222 if (ret == EXCP_HLT)
5223 timeout = 10;
5224 else
5225 timeout = 0;
5226 } else {
5227 timeout = 10;
5229 #ifdef CONFIG_PROFILER
5230 ti = profile_getclock();
5231 #endif
5232 main_loop_wait(timeout);
5233 #ifdef CONFIG_PROFILER
5234 dev_time += profile_getclock() - ti;
5235 #endif
5237 cpu_disable_ticks();
5238 return ret;
5240 #endif /* !CONFIG_DM */
5242 void help(void)
5244 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5245 "usage: %s [options] [disk_image]\n"
5246 "\n"
5247 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5248 "\n"
5249 "Standard options:\n"
5250 "-M machine select emulated machine (-M ? for list)\n"
5251 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5252 #ifndef CONFIG_DM
5253 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5254 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5255 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5256 #endif /* !CONFIG_DM */
5257 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5258 "-snapshot write to temporary files instead of disk image files\n"
5259 #ifdef TARGET_I386
5260 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5261 #endif
5262 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5263 "-smp n set the number of CPUs to 'n' [default=1]\n"
5264 "-nographic disable graphical output and redirect serial I/Os to console\n"
5265 "-vcpus set CPU number of guest platform\n"
5266 #ifndef _WIN32
5267 "-k language use keyboard layout (for example \"fr\" for French)\n"
5268 #endif
5269 #ifdef HAS_AUDIO
5270 "-audio-help print list of audio drivers and their options\n"
5271 "-soundhw c1,... enable audio support\n"
5272 " and only specified sound cards (comma separated list)\n"
5273 " use -soundhw ? to get the list of supported cards\n"
5274 " use -soundhw all to enable all of them\n"
5275 #endif
5276 "-localtime set the real time clock to local time [default=utc]\n"
5277 "-full-screen start in full screen\n"
5278 #ifdef TARGET_I386
5279 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5280 #endif
5281 "-usb enable the USB driver (will be the default soon)\n"
5282 "-usbdevice name add the host or guest USB device 'name'\n"
5283 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5284 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5285 #endif
5286 "\n"
5287 "Network options:\n"
5288 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5289 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5290 #ifdef CONFIG_SLIRP
5291 "-net user[,vlan=n][,hostname=host]\n"
5292 " connect the user mode network stack to VLAN 'n' and send\n"
5293 " hostname 'host' to DHCP clients\n"
5294 #endif
5295 #ifdef _WIN32
5296 "-net tap[,vlan=n],ifname=name\n"
5297 " connect the host TAP network interface to VLAN 'n'\n"
5298 #else
5299 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
5300 " connect the host TAP network interface to VLAN 'n' and use\n"
5301 " the network script 'file' (default=%s);\n"
5302 " use 'fd=h' to connect to an already opened TAP interface\n"
5303 #endif
5304 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5305 " connect the vlan 'n' to another VLAN using a socket connection\n"
5306 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5307 " connect the vlan 'n' to multicast maddr and port\n"
5308 "-net none use it alone to have zero network devices; if no -net option\n"
5309 " is provided, the default is '-net nic -net user'\n"
5310 "\n"
5311 #ifdef CONFIG_SLIRP
5312 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5313 #ifndef _WIN32
5314 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5315 #endif
5316 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5317 " redirect TCP or UDP connections from host to guest [-net user]\n"
5318 #endif
5319 "\n"
5320 "Linux boot specific:\n"
5321 "-kernel bzImage use 'bzImage' as kernel image\n"
5322 "-append cmdline use 'cmdline' as kernel command line\n"
5323 "-initrd file use 'file' as initial ram disk\n"
5324 "\n"
5325 "Debug/Expert options:\n"
5326 "-monitor dev redirect the monitor to char device 'dev'\n"
5327 "-serial dev redirect the serial port to char device 'dev'\n"
5328 "-parallel dev redirect the parallel port to char device 'dev'\n"
5329 "-pidfile file Write PID to 'file'\n"
5330 "-S freeze CPU at startup (use 'c' to start execution)\n"
5331 "-s wait gdb connection to port %d\n"
5332 "-p port change gdb connection port\n"
5333 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
5334 "-d domain domain that we're serving\n"
5335 "-domain-name domain name that we're serving\n"
5336 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5337 " translation (t=none or lba) (usually qemu can guess them)\n"
5338 "-L path set the directory for the BIOS and VGA BIOS\n"
5339 #ifdef USE_KQEMU
5340 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5341 "-no-kqemu disable KQEMU kernel module usage\n"
5342 #endif
5343 #ifdef USE_CODE_COPY
5344 "-no-code-copy disable code copy acceleration\n"
5345 #endif
5346 #ifdef TARGET_I386
5347 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5348 " (default is CL-GD5446 PCI VGA)\n"
5349 "-no-acpi disable ACPI\n"
5350 #endif
5351 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5352 "-vnc display start a VNC server on display\n"
5353 "-vncviewer start a vncviewer process for this domain\n"
5354 "-vncunused bind the VNC server to an unused port\n"
5355 "-timeoffset time offset (in seconds) from local time\n"
5356 "-acpi disable or enable ACPI of HVM domain \n"
5357 "\n"
5358 "During emulation, the following keys are useful:\n"
5359 "ctrl-alt-f toggle full screen\n"
5360 "ctrl-alt-n switch to virtual console 'n'\n"
5361 "ctrl-alt toggle mouse and keyboard grab\n"
5362 "\n"
5363 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5365 "qemu",
5366 DEFAULT_RAM_SIZE,
5367 #ifndef _WIN32
5368 DEFAULT_NETWORK_SCRIPT,
5369 #endif
5370 DEFAULT_GDBSTUB_PORT,
5371 "/tmp/qemu.log");
5372 exit(1);
5375 #define HAS_ARG 0x0001
5377 enum {
5378 QEMU_OPTION_h,
5380 QEMU_OPTION_M,
5381 QEMU_OPTION_fda,
5382 QEMU_OPTION_fdb,
5383 #ifndef CONFIG_DM
5384 QEMU_OPTION_hda,
5385 QEMU_OPTION_hdb,
5386 QEMU_OPTION_hdc,
5387 QEMU_OPTION_hdd,
5388 QEMU_OPTION_cdrom,
5389 #endif /* !CONFIG_DM */
5390 QEMU_OPTION_boot,
5391 QEMU_OPTION_snapshot,
5392 #ifdef TARGET_I386
5393 QEMU_OPTION_no_fd_bootchk,
5394 #endif
5395 QEMU_OPTION_m,
5396 QEMU_OPTION_nographic,
5397 #ifdef HAS_AUDIO
5398 QEMU_OPTION_audio_help,
5399 QEMU_OPTION_soundhw,
5400 #endif
5402 QEMU_OPTION_net,
5403 QEMU_OPTION_tftp,
5404 QEMU_OPTION_smb,
5405 QEMU_OPTION_redir,
5407 QEMU_OPTION_kernel,
5408 QEMU_OPTION_append,
5409 QEMU_OPTION_initrd,
5411 QEMU_OPTION_S,
5412 QEMU_OPTION_s,
5413 QEMU_OPTION_p,
5414 QEMU_OPTION_l,
5415 QEMU_OPTION_hdachs,
5416 QEMU_OPTION_L,
5417 #ifdef USE_CODE_COPY
5418 QEMU_OPTION_no_code_copy,
5419 #endif
5420 QEMU_OPTION_k,
5421 QEMU_OPTION_localtime,
5422 QEMU_OPTION_cirrusvga,
5423 QEMU_OPTION_g,
5424 QEMU_OPTION_std_vga,
5425 QEMU_OPTION_monitor,
5426 QEMU_OPTION_domainname,
5427 QEMU_OPTION_serial,
5428 QEMU_OPTION_parallel,
5429 QEMU_OPTION_loadvm,
5430 QEMU_OPTION_full_screen,
5431 QEMU_OPTION_pidfile,
5432 QEMU_OPTION_no_kqemu,
5433 QEMU_OPTION_kernel_kqemu,
5434 QEMU_OPTION_win2k_hack,
5435 QEMU_OPTION_usb,
5436 QEMU_OPTION_usbdevice,
5437 QEMU_OPTION_smp,
5438 QEMU_OPTION_vnc,
5439 QEMU_OPTION_no_acpi,
5441 QEMU_OPTION_d,
5442 QEMU_OPTION_vcpus,
5443 QEMU_OPTION_timeoffset,
5444 QEMU_OPTION_acpi,
5445 QEMU_OPTION_vncviewer,
5446 QEMU_OPTION_vncunused,
5447 };
5449 typedef struct QEMUOption {
5450 const char *name;
5451 int flags;
5452 int index;
5453 } QEMUOption;
5455 const QEMUOption qemu_options[] = {
5456 { "h", 0, QEMU_OPTION_h },
5458 { "M", HAS_ARG, QEMU_OPTION_M },
5459 { "fda", HAS_ARG, QEMU_OPTION_fda },
5460 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5461 #ifndef CONFIG_DM
5462 { "hda", HAS_ARG, QEMU_OPTION_hda },
5463 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5464 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5465 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5466 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5467 #endif /* !CONFIG_DM */
5468 { "boot", HAS_ARG, QEMU_OPTION_boot },
5469 { "snapshot", 0, QEMU_OPTION_snapshot },
5470 #ifdef TARGET_I386
5471 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5472 #endif
5473 { "m", HAS_ARG, QEMU_OPTION_m },
5474 { "nographic", 0, QEMU_OPTION_nographic },
5475 { "k", HAS_ARG, QEMU_OPTION_k },
5476 #ifdef HAS_AUDIO
5477 { "audio-help", 0, QEMU_OPTION_audio_help },
5478 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5479 #endif
5481 { "net", HAS_ARG, QEMU_OPTION_net},
5482 #ifdef CONFIG_SLIRP
5483 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5484 #ifndef _WIN32
5485 { "smb", HAS_ARG, QEMU_OPTION_smb },
5486 #endif
5487 { "redir", HAS_ARG, QEMU_OPTION_redir },
5488 #endif
5490 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5491 { "append", HAS_ARG, QEMU_OPTION_append },
5492 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5494 { "S", 0, QEMU_OPTION_S },
5495 { "s", 0, QEMU_OPTION_s },
5496 { "p", HAS_ARG, QEMU_OPTION_p },
5497 { "l", HAS_ARG, QEMU_OPTION_l },
5498 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5499 { "L", HAS_ARG, QEMU_OPTION_L },
5500 #ifdef USE_CODE_COPY
5501 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5502 #endif
5503 #ifdef USE_KQEMU
5504 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5505 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5506 #endif
5507 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5508 { "g", 1, QEMU_OPTION_g },
5509 #endif
5510 { "localtime", 0, QEMU_OPTION_localtime },
5511 { "std-vga", 0, QEMU_OPTION_std_vga },
5512 { "monitor", 1, QEMU_OPTION_monitor },
5513 { "domain-name", 1, QEMU_OPTION_domainname },
5514 { "serial", 1, QEMU_OPTION_serial },
5515 { "parallel", 1, QEMU_OPTION_parallel },
5516 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5517 { "full-screen", 0, QEMU_OPTION_full_screen },
5518 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5519 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5520 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5521 { "smp", HAS_ARG, QEMU_OPTION_smp },
5522 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5523 { "vncviewer", 0, QEMU_OPTION_vncviewer },
5524 { "vncunused", 0, QEMU_OPTION_vncunused },
5526 /* temporary options */
5527 { "usb", 0, QEMU_OPTION_usb },
5528 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5529 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5531 { "d", HAS_ARG, QEMU_OPTION_d },
5532 { "vcpus", 1, QEMU_OPTION_vcpus },
5533 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
5534 { "acpi", 0, QEMU_OPTION_acpi },
5535 { NULL },
5536 };
5538 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5540 /* this stack is only used during signal handling */
5541 #define SIGNAL_STACK_SIZE 32768
5543 static uint8_t *signal_stack;
5545 #endif
5547 /* password input */
5549 static BlockDriverState *get_bdrv(int index)
5551 BlockDriverState *bs;
5553 if (index < 4) {
5554 bs = bs_table[index];
5555 } else if (index < 6) {
5556 bs = fd_table[index - 4];
5557 } else {
5558 bs = NULL;
5560 return bs;
5563 static void read_passwords(void)
5565 BlockDriverState *bs;
5566 int i, j;
5567 char password[256];
5569 for(i = 0; i < 6; i++) {
5570 bs = get_bdrv(i);
5571 if (bs && bdrv_is_encrypted(bs)) {
5572 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5573 for(j = 0; j < 3; j++) {
5574 monitor_readline("Password: ",
5575 1, password, sizeof(password));
5576 if (bdrv_set_key(bs, password) == 0)
5577 break;
5578 term_printf("invalid password\n");
5584 /* XXX: currently we cannot use simultaneously different CPUs */
5585 void register_machines(void)
5587 #if defined(TARGET_I386)
5588 qemu_register_machine(&pc_machine);
5589 qemu_register_machine(&isapc_machine);
5590 #elif defined(TARGET_PPC)
5591 qemu_register_machine(&heathrow_machine);
5592 qemu_register_machine(&core99_machine);
5593 qemu_register_machine(&prep_machine);
5594 #elif defined(TARGET_MIPS)
5595 qemu_register_machine(&mips_machine);
5596 #elif defined(TARGET_SPARC)
5597 #ifdef TARGET_SPARC64
5598 qemu_register_machine(&sun4u_machine);
5599 #else
5600 qemu_register_machine(&sun4m_machine);
5601 #endif
5602 #elif defined(TARGET_ARM)
5603 qemu_register_machine(&integratorcp926_machine);
5604 qemu_register_machine(&integratorcp1026_machine);
5605 qemu_register_machine(&versatilepb_machine);
5606 qemu_register_machine(&versatileab_machine);
5607 #elif defined(TARGET_SH4)
5608 qemu_register_machine(&shix_machine);
5609 #else
5610 #error unsupported CPU
5611 #endif
5614 #ifdef HAS_AUDIO
5615 struct soundhw soundhw[] = {
5616 #ifndef CONFIG_DM
5617 #ifdef TARGET_I386
5619 "pcspk",
5620 "PC speaker",
5621 0,
5622 1,
5623 { .init_isa = pcspk_audio_init }
5624 },
5625 #endif
5626 #endif /* !CONFIG_DM */
5628 "sb16",
5629 "Creative Sound Blaster 16",
5630 0,
5631 1,
5632 { .init_isa = SB16_init }
5633 },
5635 #ifdef CONFIG_ADLIB
5637 "adlib",
5638 #ifdef HAS_YMF262
5639 "Yamaha YMF262 (OPL3)",
5640 #else
5641 "Yamaha YM3812 (OPL2)",
5642 #endif
5643 0,
5644 1,
5645 { .init_isa = Adlib_init }
5646 },
5647 #endif
5649 #ifdef CONFIG_GUS
5651 "gus",
5652 "Gravis Ultrasound GF1",
5653 0,
5654 1,
5655 { .init_isa = GUS_init }
5656 },
5657 #endif
5660 "es1370",
5661 "ENSONIQ AudioPCI ES1370",
5662 0,
5663 0,
5664 { .init_pci = es1370_init }
5665 },
5667 { NULL, NULL, 0, 0, { NULL } }
5668 };
5670 static void select_soundhw (const char *optarg)
5672 struct soundhw *c;
5674 if (*optarg == '?') {
5675 show_valid_cards:
5677 printf ("Valid sound card names (comma separated):\n");
5678 for (c = soundhw; c->name; ++c) {
5679 printf ("%-11s %s\n", c->name, c->descr);
5681 printf ("\n-soundhw all will enable all of the above\n");
5682 exit (*optarg != '?');
5684 else {
5685 size_t l;
5686 const char *p;
5687 char *e;
5688 int bad_card = 0;
5690 if (!strcmp (optarg, "all")) {
5691 for (c = soundhw; c->name; ++c) {
5692 c->enabled = 1;
5694 return;
5697 p = optarg;
5698 while (*p) {
5699 e = strchr (p, ',');
5700 l = !e ? strlen (p) : (size_t) (e - p);
5702 for (c = soundhw; c->name; ++c) {
5703 if (!strncmp (c->name, p, l)) {
5704 c->enabled = 1;
5705 break;
5709 if (!c->name) {
5710 if (l > 80) {
5711 fprintf (stderr,
5712 "Unknown sound card name (too big to show)\n");
5714 else {
5715 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5716 (int) l, p);
5718 bad_card = 1;
5720 p += l + (e != NULL);
5723 if (bad_card)
5724 goto show_valid_cards;
5727 #endif
5729 #ifdef _WIN32
5730 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5732 exit(STATUS_CONTROL_C_EXIT);
5733 return TRUE;
5735 #endif
5737 #define MAX_NET_CLIENTS 32
5739 #include <xg_private.h>
5741 /* FIXME Flush the shadow page */
5742 int unset_mm_mapping(int xc_handle, uint32_t domid,
5743 unsigned long nr_pages, unsigned int address_bits,
5744 xen_pfn_t *extent_start)
5746 int err = 0;
5747 xc_dominfo_t info;
5749 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5750 nr_pages, 0, extent_start);
5751 if (err)
5752 fprintf(stderr, "Failed to decrease physmap\n");
5754 xc_domain_getinfo(xc_handle, domid, 1, &info);
5756 if ((info.nr_pages - nr_pages) <= 0) {
5757 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5758 err = -1;
5761 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5762 PAGE_SIZE/1024) != 0) {
5763 fprintf(logfile, "set maxmem returned error %d\n", errno);
5764 err = -1;
5767 return err;
5770 int set_mm_mapping(int xc_handle, uint32_t domid,
5771 unsigned long nr_pages, unsigned int address_bits,
5772 xen_pfn_t *extent_start)
5774 #if 0
5775 int i;
5776 #endif
5777 xc_dominfo_t info;
5778 int err = 0;
5780 xc_domain_getinfo(xc_handle, domid, 1, &info);
5782 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5783 nr_pages * PAGE_SIZE/1024) != 0) {
5784 fprintf(logfile, "set maxmem returned error %d\n", errno);
5785 return -1;
5788 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5789 address_bits, extent_start);
5790 if (err) {
5791 fprintf(stderr, "Failed to populate physmap\n");
5792 return -1;
5795 err = xc_domain_translate_gpfn_list(xc_handle, domid, nr_pages,
5796 extent_start, extent_start);
5797 if (err) {
5798 fprintf(stderr, "Failed to translate gpfn list\n");
5799 return -1;
5802 #if 0 /* Generates lots of log file output - turn on for debugging */
5803 for (i = 0; i < nr_pages; i++)
5804 fprintf(stderr, "set_map result i %x result %lx\n", i,
5805 extent_start[i]);
5806 #endif
5808 return 0;
5811 int main(int argc, char **argv)
5813 #ifdef CONFIG_GDBSTUB
5814 int use_gdbstub, gdbstub_port;
5815 #endif
5816 int i;
5817 #ifndef CONFIG_DM
5818 int cdrom_index;
5819 #endif /* !CONFIG_DM */
5820 int snapshot, linux_boot;
5821 const char *initrd_filename;
5822 #ifndef CONFIG_DM
5823 const char *hd_filename[MAX_DISKS];
5824 #endif /* !CONFIG_DM */
5825 const char *fd_filename[MAX_FD];
5826 const char *kernel_filename, *kernel_cmdline;
5827 DisplayState *ds = &display_state;
5828 int cyls, heads, secs, translation;
5829 int start_emulation = 1;
5830 char net_clients[MAX_NET_CLIENTS][256];
5831 int nb_net_clients;
5832 int optind;
5833 const char *r, *optarg;
5834 CharDriverState *monitor_hd;
5835 char monitor_device[128];
5836 char serial_devices[MAX_SERIAL_PORTS][128];
5837 int serial_device_index;
5838 char parallel_devices[MAX_PARALLEL_PORTS][128];
5839 int parallel_device_index;
5840 const char *loadvm = NULL;
5841 QEMUMachine *machine;
5842 char usb_devices[MAX_USB_CMDLINE][128];
5843 int usb_devices_index;
5844 unsigned long nr_pages, tmp_nr_pages, shared_page_nr;
5845 xen_pfn_t *page_array;
5846 extern void *shared_page;
5847 extern void *buffered_io_page;
5849 char qemu_dm_logfilename[64];
5851 LIST_INIT (&vm_change_state_head);
5852 #ifndef _WIN32
5854 struct sigaction act;
5855 sigfillset(&act.sa_mask);
5856 act.sa_flags = 0;
5857 act.sa_handler = SIG_IGN;
5858 sigaction(SIGPIPE, &act, NULL);
5860 #else
5861 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5862 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5863 QEMU to run on a single CPU */
5865 HANDLE h;
5866 DWORD mask, smask;
5867 int i;
5868 h = GetCurrentProcess();
5869 if (GetProcessAffinityMask(h, &mask, &smask)) {
5870 for(i = 0; i < 32; i++) {
5871 if (mask & (1 << i))
5872 break;
5874 if (i != 32) {
5875 mask = 1 << i;
5876 SetProcessAffinityMask(h, mask);
5880 #endif
5882 register_machines();
5883 machine = first_machine;
5884 initrd_filename = NULL;
5885 for(i = 0; i < MAX_FD; i++)
5886 fd_filename[i] = NULL;
5887 #ifndef CONFIG_DM
5888 for(i = 0; i < MAX_DISKS; i++)
5889 hd_filename[i] = NULL;
5890 #endif /* !CONFIG_DM */
5891 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5892 vga_ram_size = VGA_RAM_SIZE;
5893 bios_size = BIOS_SIZE;
5894 #ifdef CONFIG_GDBSTUB
5895 use_gdbstub = 0;
5896 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5897 #endif
5898 snapshot = 0;
5899 nographic = 0;
5900 vncviewer = 0;
5901 vncunused = 0;
5902 kernel_filename = NULL;
5903 kernel_cmdline = "";
5904 #ifndef CONFIG_DM
5905 #ifdef TARGET_PPC
5906 cdrom_index = 1;
5907 #else
5908 cdrom_index = 2;
5909 #endif
5910 #endif /* !CONFIG_DM */
5911 cyls = heads = secs = 0;
5912 translation = BIOS_ATA_TRANSLATION_AUTO;
5913 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5915 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5916 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5917 serial_devices[i][0] = '\0';
5918 serial_device_index = 0;
5920 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5921 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5922 parallel_devices[i][0] = '\0';
5923 parallel_device_index = 0;
5925 usb_devices_index = 0;
5927 nb_net_clients = 0;
5929 nb_nics = 0;
5930 /* default mac address of the first network interface */
5932 /* init debug */
5933 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm.%d.log", getpid());
5934 cpu_set_log_filename(qemu_dm_logfilename);
5935 cpu_set_log(0);
5937 optind = 1;
5938 for(;;) {
5939 if (optind >= argc)
5940 break;
5941 r = argv[optind];
5942 if (r[0] != '-') {
5943 #ifndef CONFIG_DM
5944 hd_filename[0] = argv[optind++];
5945 #else
5946 help();
5947 #endif /* !CONFIG_DM */
5948 } else {
5949 const QEMUOption *popt;
5951 optind++;
5952 popt = qemu_options;
5953 for(;;) {
5954 if (!popt->name) {
5955 fprintf(stderr, "%s: invalid option -- '%s'\n",
5956 argv[0], r);
5957 exit(1);
5959 if (!strcmp(popt->name, r + 1))
5960 break;
5961 popt++;
5963 if (popt->flags & HAS_ARG) {
5964 if (optind >= argc) {
5965 fprintf(stderr, "%s: option '%s' requires an argument\n",
5966 argv[0], r);
5967 exit(1);
5969 optarg = argv[optind++];
5970 } else {
5971 optarg = NULL;
5974 switch(popt->index) {
5975 case QEMU_OPTION_M:
5976 machine = find_machine(optarg);
5977 if (!machine) {
5978 QEMUMachine *m;
5979 printf("Supported machines are:\n");
5980 for(m = first_machine; m != NULL; m = m->next) {
5981 printf("%-10s %s%s\n",
5982 m->name, m->desc,
5983 m == first_machine ? " (default)" : "");
5985 exit(1);
5987 break;
5988 case QEMU_OPTION_initrd:
5989 initrd_filename = optarg;
5990 break;
5991 #ifndef CONFIG_DM
5992 case QEMU_OPTION_hda:
5993 case QEMU_OPTION_hdb:
5994 case QEMU_OPTION_hdc:
5995 case QEMU_OPTION_hdd:
5997 int hd_index;
5998 hd_index = popt->index - QEMU_OPTION_hda;
5999 hd_filename[hd_index] = optarg;
6000 if (hd_index == cdrom_index)
6001 cdrom_index = -1;
6003 break;
6004 #endif /* !CONFIG_DM */
6005 case QEMU_OPTION_snapshot:
6006 snapshot = 1;
6007 break;
6008 case QEMU_OPTION_hdachs:
6010 const char *p;
6011 p = optarg;
6012 cyls = strtol(p, (char **)&p, 0);
6013 if (cyls < 1 || cyls > 16383)
6014 goto chs_fail;
6015 if (*p != ',')
6016 goto chs_fail;
6017 p++;
6018 heads = strtol(p, (char **)&p, 0);
6019 if (heads < 1 || heads > 16)
6020 goto chs_fail;
6021 if (*p != ',')
6022 goto chs_fail;
6023 p++;
6024 secs = strtol(p, (char **)&p, 0);
6025 if (secs < 1 || secs > 63)
6026 goto chs_fail;
6027 if (*p == ',') {
6028 p++;
6029 if (!strcmp(p, "none"))
6030 translation = BIOS_ATA_TRANSLATION_NONE;
6031 else if (!strcmp(p, "lba"))
6032 translation = BIOS_ATA_TRANSLATION_LBA;
6033 else if (!strcmp(p, "auto"))
6034 translation = BIOS_ATA_TRANSLATION_AUTO;
6035 else
6036 goto chs_fail;
6037 } else if (*p != '\0') {
6038 chs_fail:
6039 fprintf(stderr, "qemu: invalid physical CHS format\n");
6040 exit(1);
6043 break;
6044 case QEMU_OPTION_nographic:
6045 if(!strcmp(monitor_device, "vc"))
6046 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6047 if(!strcmp(serial_devices[0], "vc"))
6048 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
6049 "null");
6050 nographic = 1;
6051 break;
6052 case QEMU_OPTION_kernel:
6053 kernel_filename = optarg;
6054 break;
6055 case QEMU_OPTION_append:
6056 kernel_cmdline = optarg;
6057 break;
6058 #ifndef CONFIG_DM
6059 case QEMU_OPTION_cdrom:
6060 if (cdrom_index >= 0) {
6061 hd_filename[cdrom_index] = optarg;
6063 break;
6064 #endif /* !CONFIG_DM */
6065 case QEMU_OPTION_boot:
6066 boot_device = strdup(optarg);
6067 if (strspn(boot_device, "acd"
6068 #ifdef TARGET_SPARC
6069 "n"
6070 #endif
6071 ) != strlen(boot_device)) {
6072 fprintf(stderr, "qemu: invalid boot device in '%s'\n",
6073 boot_device);
6074 exit(1);
6076 break;
6077 case QEMU_OPTION_fda:
6078 fd_filename[0] = optarg;
6079 break;
6080 case QEMU_OPTION_fdb:
6081 fd_filename[1] = optarg;
6082 break;
6083 #ifdef TARGET_I386
6084 case QEMU_OPTION_no_fd_bootchk:
6085 fd_bootchk = 0;
6086 break;
6087 #endif
6088 #ifdef USE_CODE_COPY
6089 case QEMU_OPTION_no_code_copy:
6090 code_copy_enabled = 0;
6091 break;
6092 #endif
6093 case QEMU_OPTION_net:
6094 if (nb_net_clients >= MAX_NET_CLIENTS) {
6095 fprintf(stderr, "qemu: too many network clients\n");
6096 exit(1);
6098 pstrcpy(net_clients[nb_net_clients],
6099 sizeof(net_clients[0]),
6100 optarg);
6101 nb_net_clients++;
6102 break;
6103 #ifdef CONFIG_SLIRP
6104 case QEMU_OPTION_tftp:
6105 tftp_prefix = optarg;
6106 break;
6107 #ifndef _WIN32
6108 case QEMU_OPTION_smb:
6109 net_slirp_smb(optarg);
6110 break;
6111 #endif
6112 case QEMU_OPTION_redir:
6113 net_slirp_redir(optarg);
6114 break;
6115 #endif
6116 #ifdef HAS_AUDIO
6117 case QEMU_OPTION_audio_help:
6118 AUD_help ();
6119 exit (0);
6120 break;
6121 case QEMU_OPTION_soundhw:
6122 select_soundhw (optarg);
6123 break;
6124 #endif
6125 case QEMU_OPTION_h:
6126 help();
6127 break;
6128 case QEMU_OPTION_m:
6129 ram_size = atol(optarg) * 1024 * 1024;
6130 if (ram_size <= 0)
6131 help();
6132 #ifndef CONFIG_DM
6133 if (ram_size > PHYS_RAM_MAX_SIZE) {
6134 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6135 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6136 exit(1);
6138 #endif /* !CONFIG_DM */
6139 break;
6140 case QEMU_OPTION_l:
6142 int mask;
6143 CPULogItem *item;
6145 mask = cpu_str_to_log_mask(optarg);
6146 if (!mask) {
6147 printf("Log items (comma separated):\n");
6148 for(item = cpu_log_items; item->mask != 0; item++) {
6149 printf("%-10s %s\n", item->name, item->help);
6151 exit(1);
6153 cpu_set_log(mask);
6155 break;
6156 #ifdef CONFIG_GDBSTUB
6157 case QEMU_OPTION_s:
6158 use_gdbstub = 1;
6159 break;
6160 case QEMU_OPTION_p:
6161 gdbstub_port = atoi(optarg);
6162 break;
6163 #endif
6164 case QEMU_OPTION_L:
6165 bios_dir = optarg;
6166 break;
6167 case QEMU_OPTION_S:
6168 start_emulation = 0;
6169 break;
6170 case QEMU_OPTION_k:
6171 keyboard_layout = optarg;
6172 break;
6173 case QEMU_OPTION_localtime:
6174 rtc_utc = 0;
6175 break;
6176 case QEMU_OPTION_cirrusvga:
6177 cirrus_vga_enabled = 1;
6178 break;
6179 case QEMU_OPTION_std_vga:
6180 cirrus_vga_enabled = 0;
6181 break;
6182 case QEMU_OPTION_g:
6184 const char *p;
6185 int w, h, depth;
6186 p = optarg;
6187 w = strtol(p, (char **)&p, 10);
6188 if (w <= 0) {
6189 graphic_error:
6190 fprintf(stderr, "qemu: invalid resolution or depth\n");
6191 exit(1);
6193 if (*p != 'x')
6194 goto graphic_error;
6195 p++;
6196 h = strtol(p, (char **)&p, 10);
6197 if (h <= 0)
6198 goto graphic_error;
6199 if (*p == 'x') {
6200 p++;
6201 depth = strtol(p, (char **)&p, 10);
6202 if (depth != 8 && depth != 15 && depth != 16 &&
6203 depth != 24 && depth != 32)
6204 goto graphic_error;
6205 } else if (*p == '\0') {
6206 depth = graphic_depth;
6207 } else {
6208 goto graphic_error;
6211 graphic_width = w;
6212 graphic_height = h;
6213 graphic_depth = depth;
6215 break;
6216 case QEMU_OPTION_monitor:
6217 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6218 break;
6219 case QEMU_OPTION_serial:
6220 if (serial_device_index >= MAX_SERIAL_PORTS) {
6221 fprintf(stderr, "qemu: too many serial ports\n");
6222 exit(1);
6224 pstrcpy(serial_devices[serial_device_index],
6225 sizeof(serial_devices[0]), optarg);
6226 serial_device_index++;
6227 break;
6228 case QEMU_OPTION_parallel:
6229 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6230 fprintf(stderr, "qemu: too many parallel ports\n");
6231 exit(1);
6233 pstrcpy(parallel_devices[parallel_device_index],
6234 sizeof(parallel_devices[0]), optarg);
6235 parallel_device_index++;
6236 break;
6237 case QEMU_OPTION_loadvm:
6238 loadvm = optarg;
6239 break;
6240 case QEMU_OPTION_full_screen:
6241 full_screen = 1;
6242 break;
6243 case QEMU_OPTION_pidfile:
6244 create_pidfile(optarg);
6245 break;
6246 #ifdef TARGET_I386
6247 case QEMU_OPTION_win2k_hack:
6248 win2k_install_hack = 1;
6249 break;
6250 #endif
6251 #ifdef USE_KQEMU
6252 case QEMU_OPTION_no_kqemu:
6253 kqemu_allowed = 0;
6254 break;
6255 case QEMU_OPTION_kernel_kqemu:
6256 kqemu_allowed = 2;
6257 break;
6258 #endif
6259 case QEMU_OPTION_usb:
6260 usb_enabled = 1;
6261 break;
6262 case QEMU_OPTION_usbdevice:
6263 usb_enabled = 1;
6264 if (usb_devices_index >= MAX_USB_CMDLINE) {
6265 fprintf(stderr, "Too many USB devices\n");
6266 exit(1);
6268 pstrcpy(usb_devices[usb_devices_index],
6269 sizeof(usb_devices[usb_devices_index]),
6270 optarg);
6271 usb_devices_index++;
6272 break;
6273 case QEMU_OPTION_smp:
6274 smp_cpus = atoi(optarg);
6275 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6276 fprintf(stderr, "Invalid number of CPUs\n");
6277 exit(1);
6279 break;
6280 case QEMU_OPTION_vnc:
6281 vnc_display = atoi(optarg);
6282 if (vnc_display < 0) {
6283 fprintf(stderr, "Invalid VNC display\n");
6284 exit(1);
6286 break;
6287 case QEMU_OPTION_no_acpi:
6288 acpi_enabled = 0;
6289 break;
6290 case QEMU_OPTION_domainname:
6291 strncat(domain_name, optarg, sizeof(domain_name) - 20);
6292 break;
6293 case QEMU_OPTION_d:
6294 domid = atoi(optarg);
6295 fprintf(logfile, "domid: %d\n", domid);
6296 break;
6297 case QEMU_OPTION_vcpus:
6298 vcpus = atoi(optarg);
6299 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
6300 break;
6301 case QEMU_OPTION_timeoffset:
6302 timeoffset = strtol(optarg, NULL, 0);
6303 break;
6304 case QEMU_OPTION_acpi:
6305 acpi_enabled = 1;
6306 break;
6307 case QEMU_OPTION_vncviewer:
6308 vncviewer++;
6309 break;
6310 case QEMU_OPTION_vncunused:
6311 vncunused++;
6312 if (vnc_display == -1)
6313 vnc_display = 0;
6314 break;
6319 #ifdef CONFIG_DM
6320 bdrv_init();
6321 xenstore_parse_domain_config(domid);
6322 #endif /* CONFIG_DM */
6324 #ifdef USE_KQEMU
6325 if (smp_cpus > 1)
6326 kqemu_allowed = 0;
6327 #endif
6328 linux_boot = (kernel_filename != NULL);
6330 #ifndef CONFIG_DM
6331 if (!linux_boot &&
6332 hd_filename[0] == '\0' &&
6333 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6334 fd_filename[0] == '\0')
6335 help();
6337 #if 0
6338 /* boot to cd by default if no hard disk */
6339 if (hd_filename[0] == '\0' && boot_device == 'c') {
6340 if (fd_filename[0] != '\0')
6341 boot_device = 'a';
6342 else
6343 boot_device = 'd';
6345 #endif
6346 #endif /* !CONFIG_DM */
6348 setvbuf(stdout, NULL, _IOLBF, 0);
6350 init_timers();
6351 init_timer_alarm();
6353 #ifdef _WIN32
6354 socket_init();
6355 #endif
6357 #ifndef CONFIG_DM
6358 /* init network clients */
6359 if (nb_net_clients == 0) {
6360 /* if no clients, we use a default config */
6361 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6362 "nic");
6363 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6364 "user");
6365 nb_net_clients = 2;
6367 #endif /* !CONFIG_DM */
6369 for(i = 0;i < nb_net_clients; i++) {
6370 if (net_client_init(net_clients[i]) < 0)
6371 exit(1);
6374 /* init the memory */
6375 phys_ram_size = ram_size + vga_ram_size + bios_size;
6377 #ifdef CONFIG_DM
6379 xc_handle = xc_interface_open();
6381 #if defined (__ia64__)
6382 if (ram_size > MMIO_START)
6383 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
6384 #endif
6386 nr_pages = ram_size/PAGE_SIZE;
6387 tmp_nr_pages = nr_pages;
6389 #if defined(__i386__) || defined(__x86_64__)
6390 if (ram_size > HVM_BELOW_4G_RAM_END) {
6391 tmp_nr_pages += HVM_BELOW_4G_MMIO_LENGTH >> PAGE_SHIFT;
6392 shared_page_nr = (HVM_BELOW_4G_RAM_END >> PAGE_SHIFT) - 1;
6393 } else
6394 shared_page_nr = nr_pages - 1;
6395 #endif
6397 page_array = (xen_pfn_t *)malloc(tmp_nr_pages * sizeof(xen_pfn_t));
6398 if (page_array == NULL) {
6399 fprintf(logfile, "malloc returned error %d\n", errno);
6400 exit(-1);
6403 #if defined(__i386__) || defined(__x86_64__)
6404 if (xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages) {
6405 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
6406 exit(-1);
6409 if (ram_size > HVM_BELOW_4G_RAM_END)
6410 for (i = 0; i < nr_pages - (HVM_BELOW_4G_RAM_END >> PAGE_SHIFT); i++)
6411 page_array[tmp_nr_pages - 1 - i] = page_array[nr_pages - 1 - i];
6413 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6414 PROT_READ|PROT_WRITE, page_array,
6415 tmp_nr_pages);
6416 if (phys_ram_base == NULL) {
6417 fprintf(logfile, "batch map guest memory returned error %d\n", errno);
6418 exit(-1);
6421 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6422 PROT_READ|PROT_WRITE,
6423 page_array[shared_page_nr]);
6424 if (shared_page == NULL) {
6425 fprintf(logfile, "map shared IO page returned error %d\n", errno);
6426 exit(-1);
6429 fprintf(logfile, "shared page at pfn:%lx, mfn: %"PRIx64"\n",
6430 shared_page_nr, (uint64_t)(page_array[shared_page_nr]));
6432 /* not yet add for IA64 */
6433 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6434 PROT_READ|PROT_WRITE,
6435 page_array[shared_page_nr - 2]);
6436 if (buffered_io_page == NULL) {
6437 fprintf(logfile, "map buffered IO page returned error %d\n", errno);
6438 exit(-1);
6441 fprintf(logfile, "buffered io page at pfn:%lx, mfn: %"PRIx64"\n",
6442 shared_page_nr - 2, (uint64_t)(page_array[shared_page_nr - 2]));
6444 free(page_array);
6446 #elif defined(__ia64__)
6448 if (xc_ia64_get_pfn_list(xc_handle, domid, page_array,
6449 IO_PAGE_START >> PAGE_SHIFT, 1) != 1) {
6450 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
6451 exit(-1);
6454 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6455 PROT_READ|PROT_WRITE,
6456 page_array[0]);
6458 fprintf(logfile, "shared page at pfn:%lx, mfn: %016lx\n",
6459 IO_PAGE_START >> PAGE_SHIFT, page_array[0]);
6461 if (xc_ia64_get_pfn_list(xc_handle, domid,
6462 page_array, 0, nr_pages) != nr_pages) {
6463 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
6464 exit(-1);
6467 if (ram_size > MMIO_START) {
6468 for (i = 0 ; i < MEM_G >> PAGE_SHIFT; i++)
6469 page_array[MMIO_START >> PAGE_SHIFT + i] =
6470 page_array[IO_PAGE_START >> PAGE_SHIFT + 1];
6473 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6474 PROT_READ|PROT_WRITE,
6475 page_array, nr_pages);
6476 if (phys_ram_base == 0) {
6477 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6478 exit(-1);
6480 #endif
6481 #else /* !CONFIG_DM */
6483 phys_ram_base = qemu_vmalloc(phys_ram_size);
6484 if (!phys_ram_base) {
6485 fprintf(stderr, "Could not allocate physical memory\n");
6486 exit(1);
6489 #endif /* !CONFIG_DM */
6491 #ifndef CONFIG_DM
6492 /* we always create the cdrom drive, even if no disk is there */
6493 bdrv_init();
6494 if (cdrom_index >= 0) {
6495 bs_table[cdrom_index] = bdrv_new("cdrom");
6496 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6499 /* open the virtual block devices */
6500 for(i = 0; i < MAX_DISKS; i++) {
6501 if (hd_filename[i]) {
6502 if (!bs_table[i]) {
6503 char buf[64];
6504 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6505 bs_table[i] = bdrv_new(buf);
6507 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6508 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6509 hd_filename[i]);
6510 exit(1);
6512 if (i == 0 && cyls != 0) {
6513 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6514 bdrv_set_translation_hint(bs_table[i], translation);
6518 #endif /* !CONFIG_DM */
6520 /* we always create at least one floppy disk */
6521 fd_table[0] = bdrv_new("fda");
6522 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6524 for(i = 0; i < MAX_FD; i++) {
6525 if (fd_filename[i]) {
6526 if (!fd_table[i]) {
6527 char buf[64];
6528 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6529 fd_table[i] = bdrv_new(buf);
6530 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6532 if (fd_filename[i] != '\0') {
6533 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6534 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6535 fd_filename[i]);
6536 exit(1);
6542 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6543 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6545 init_ioports();
6547 /* terminal init */
6548 if (nographic) {
6549 dumb_display_init(ds);
6550 } else if (vnc_display != -1) {
6551 vnc_display = vnc_display_init(ds, vnc_display, vncunused);
6552 if (vncviewer)
6553 vnc_start_viewer(vnc_display);
6554 xenstore_write_vncport(vnc_display);
6555 } else {
6556 #if defined(CONFIG_SDL)
6557 sdl_display_init(ds, full_screen);
6558 #elif defined(CONFIG_COCOA)
6559 cocoa_display_init(ds, full_screen);
6560 #else
6561 dumb_display_init(ds);
6562 #endif
6565 monitor_hd = qemu_chr_open(monitor_device);
6566 if (!monitor_hd) {
6567 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6568 exit(1);
6570 monitor_init(monitor_hd, !nographic);
6572 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6573 if (serial_devices[i][0] != '\0') {
6574 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6575 if (!serial_hds[i]) {
6576 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6577 serial_devices[i]);
6578 exit(1);
6580 if (!strcmp(serial_devices[i], "vc"))
6581 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6585 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6586 if (parallel_devices[i][0] != '\0') {
6587 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6588 if (!parallel_hds[i]) {
6589 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6590 parallel_devices[i]);
6591 exit(1);
6593 if (!strcmp(parallel_devices[i], "vc"))
6594 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6598 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6600 machine->init(ram_size, vga_ram_size, boot_device,
6601 ds, fd_filename, snapshot,
6602 kernel_filename, kernel_cmdline, initrd_filename,
6603 timeoffset);
6604 free(boot_device);
6606 /* init USB devices */
6607 if (usb_enabled) {
6608 for(i = 0; i < usb_devices_index; i++) {
6609 if (usb_device_add(usb_devices[i]) < 0) {
6610 fprintf(stderr, "Warning: could not add USB device %s\n",
6611 usb_devices[i]);
6616 if (vnc_display == -1) {
6617 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6618 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6621 #ifdef CONFIG_GDBSTUB
6622 if (use_gdbstub) {
6623 if (gdbserver_start(gdbstub_port) < 0) {
6624 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6625 gdbstub_port);
6626 exit(1);
6627 } else {
6628 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6630 } else
6631 #endif
6632 if (loadvm)
6633 qemu_loadvm(loadvm);
6636 /* XXX: simplify init */
6637 read_passwords();
6638 if (start_emulation) {
6639 vm_start();
6642 main_loop();
6643 quit_timers();
6644 return 0;