ia64/xen-unstable

view tools/ioemu/vl.c @ 15268:d0dc12484bf2

qemu: More care over filename string sizes.
Signed-off-by: Keir Fraser <keir@xensource.com>
author kfraser@localhost.localdomain
date Mon Jun 04 15:21:12 2007 +0100 (2007-06-04)
parents fc8e40692690
children f45c84dd5f41
line source
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 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>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44 #include <dirent.h>
45 #include <netdb.h>
46 #ifdef _BSD
47 #include <sys/stat.h>
48 #ifndef __APPLE__
49 #include <libutil.h>
50 #endif
51 #else
52 #ifndef __sun__
53 #include <linux/if.h>
54 #include <linux/if_tun.h>
55 #include <pty.h>
56 #include <malloc.h>
57 #include <linux/rtc.h>
58 #include <linux/ppdev.h>
59 #endif
60 #endif
61 #endif
63 #if defined(CONFIG_SLIRP)
64 #include "libslirp.h"
65 #endif
67 #ifdef _WIN32
68 #include <malloc.h>
69 #include <sys/timeb.h>
70 #include <windows.h>
71 #define getopt_long_only getopt_long
72 #define memalign(align, size) malloc(size)
73 #endif
75 #include "qemu_socket.h"
77 #ifdef CONFIG_SDL
78 #ifdef __APPLE__
79 #include <SDL/SDL.h>
80 #endif
81 #endif /* CONFIG_SDL */
83 #ifdef CONFIG_COCOA
84 #undef main
85 #define main qemu_main
86 #endif /* CONFIG_COCOA */
88 #include "disas.h"
90 #include "exec-all.h"
92 #include <xen/hvm/params.h>
93 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
94 #define DEFAULT_BRIDGE "xenbr0"
95 #ifdef __sun__
96 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
97 #else
98 #define SMBD_COMMAND "/usr/sbin/smbd"
99 #endif
101 //#define DEBUG_UNUSED_IOPORT
102 //#define DEBUG_IOPORT
104 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
106 #ifdef TARGET_PPC
107 #define DEFAULT_RAM_SIZE 144
108 #else
109 #define DEFAULT_RAM_SIZE 128
110 #endif
111 /* in ms */
112 #define GUI_REFRESH_INTERVAL 30
114 /* Max number of USB devices that can be specified on the commandline. */
115 #define MAX_USB_CMDLINE 8
117 /* XXX: use a two level table to limit memory usage */
118 #define MAX_IOPORTS 65536
120 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
121 char phys_ram_file[1024];
122 void *ioport_opaque[MAX_IOPORTS];
123 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
124 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
125 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
126 to store the VM snapshots */
127 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
128 /* point to the block driver where the snapshots are managed */
129 BlockDriverState *bs_snapshots;
130 int vga_ram_size;
131 int bios_size;
132 static DisplayState display_state;
133 int nographic;
134 int vncviewer;
135 int vncunused;
136 const char* keyboard_layout = NULL;
137 int64_t ticks_per_sec;
138 char *boot_device = NULL;
139 uint64_t ram_size;
140 int pit_min_timer_count = 0;
141 int nb_nics;
142 NICInfo nd_table[MAX_NICS];
143 QEMUTimer *gui_timer;
144 int vm_running;
145 int rtc_utc = 1;
146 int cirrus_vga_enabled = 1;
147 #ifdef TARGET_SPARC
148 int graphic_width = 1024;
149 int graphic_height = 768;
150 #else
151 int graphic_width = 800;
152 int graphic_height = 600;
153 #endif
154 int graphic_depth = 15;
155 int full_screen = 0;
156 int no_quit = 0;
157 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
158 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
159 #ifdef TARGET_I386
160 int win2k_install_hack = 0;
161 #endif
162 int usb_enabled = 0;
163 static VLANState *first_vlan;
164 int smp_cpus = 1;
165 const char *vnc_display;
166 #if defined(TARGET_SPARC)
167 #define MAX_CPUS 16
168 #elif defined(TARGET_I386)
169 #define MAX_CPUS 255
170 #else
171 #define MAX_CPUS 1
172 #endif
173 int acpi_enabled = 0;
174 int fd_bootchk = 1;
175 int no_reboot = 0;
176 int daemonize = 0;
177 const char *option_rom[MAX_OPTION_ROMS];
178 int nb_option_roms;
179 int semihosting_enabled = 0;
180 int autostart = 1;
182 extern int vcpus;
184 int xc_handle;
186 char domain_name[64] = "Xen HVM Guest";
187 extern int domid;
189 char vncpasswd[64];
190 unsigned char challenge[AUTHCHALLENGESIZE];
192 /***********************************************************/
193 /* x86 ISA bus support */
195 target_phys_addr_t isa_mem_base = 0;
196 PicState2 *isa_pic;
198 uint32_t default_ioport_readb(void *opaque, uint32_t address)
199 {
200 #ifdef DEBUG_UNUSED_IOPORT
201 fprintf(stderr, "inb: port=0x%04x\n", address);
202 #endif
203 return 0xff;
204 }
206 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
207 {
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
210 #endif
211 }
213 /* default is to make two byte accesses */
214 uint32_t default_ioport_readw(void *opaque, uint32_t address)
215 {
216 uint32_t data;
217 data = ioport_read_table[0][address](ioport_opaque[address], address);
218 address = (address + 1) & (MAX_IOPORTS - 1);
219 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
220 return data;
221 }
223 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
224 {
225 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
226 address = (address + 1) & (MAX_IOPORTS - 1);
227 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
228 }
230 uint32_t default_ioport_readl(void *opaque, uint32_t address)
231 {
232 #ifdef DEBUG_UNUSED_IOPORT
233 fprintf(stderr, "inl: port=0x%04x\n", address);
234 #endif
235 return 0xffffffff;
236 }
238 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
239 {
240 #ifdef DEBUG_UNUSED_IOPORT
241 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
242 #endif
243 }
245 void init_ioports(void)
246 {
247 int i;
249 for(i = 0; i < MAX_IOPORTS; i++) {
250 ioport_read_table[0][i] = default_ioport_readb;
251 ioport_write_table[0][i] = default_ioport_writeb;
252 ioport_read_table[1][i] = default_ioport_readw;
253 ioport_write_table[1][i] = default_ioport_writew;
254 ioport_read_table[2][i] = default_ioport_readl;
255 ioport_write_table[2][i] = default_ioport_writel;
256 }
257 }
259 /* size is the word size in byte */
260 int register_ioport_read(int start, int length, int size,
261 IOPortReadFunc *func, void *opaque)
262 {
263 int i, bsize;
265 if (size == 1) {
266 bsize = 0;
267 } else if (size == 2) {
268 bsize = 1;
269 } else if (size == 4) {
270 bsize = 2;
271 } else {
272 hw_error("register_ioport_read: invalid size");
273 return -1;
274 }
275 for(i = start; i < start + length; i += size) {
276 ioport_read_table[bsize][i] = func;
277 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
278 hw_error("register_ioport_write: invalid opaque");
279 ioport_opaque[i] = opaque;
280 }
281 return 0;
282 }
284 /* size is the word size in byte */
285 int register_ioport_write(int start, int length, int size,
286 IOPortWriteFunc *func, void *opaque)
287 {
288 int i, bsize;
290 if (size == 1) {
291 bsize = 0;
292 } else if (size == 2) {
293 bsize = 1;
294 } else if (size == 4) {
295 bsize = 2;
296 } else {
297 hw_error("register_ioport_write: invalid size");
298 return -1;
299 }
300 for(i = start; i < start + length; i += size) {
301 ioport_write_table[bsize][i] = func;
302 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
303 hw_error("register_ioport_write: invalid opaque");
304 ioport_opaque[i] = opaque;
305 }
306 return 0;
307 }
309 void isa_unassign_ioport(int start, int length)
310 {
311 int i;
313 for(i = start; i < start + length; i++) {
314 ioport_read_table[0][i] = default_ioport_readb;
315 ioport_read_table[1][i] = default_ioport_readw;
316 ioport_read_table[2][i] = default_ioport_readl;
318 ioport_write_table[0][i] = default_ioport_writeb;
319 ioport_write_table[1][i] = default_ioport_writew;
320 ioport_write_table[2][i] = default_ioport_writel;
321 }
322 }
324 /***********************************************************/
326 void cpu_outb(CPUState *env, int addr, int val)
327 {
328 #ifdef DEBUG_IOPORT
329 if (loglevel & CPU_LOG_IOPORT)
330 fprintf(logfile, "outb: %04x %02x\n", addr, val);
331 #endif
332 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
333 #ifdef USE_KQEMU
334 if (env)
335 env->last_io_time = cpu_get_time_fast();
336 #endif
337 }
339 void cpu_outw(CPUState *env, int addr, int val)
340 {
341 #ifdef DEBUG_IOPORT
342 if (loglevel & CPU_LOG_IOPORT)
343 fprintf(logfile, "outw: %04x %04x\n", addr, val);
344 #endif
345 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
346 #ifdef USE_KQEMU
347 if (env)
348 env->last_io_time = cpu_get_time_fast();
349 #endif
350 }
352 void cpu_outl(CPUState *env, int addr, int val)
353 {
354 #ifdef DEBUG_IOPORT
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "outl: %04x %08x\n", addr, val);
357 #endif
358 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
359 #ifdef USE_KQEMU
360 if (env)
361 env->last_io_time = cpu_get_time_fast();
362 #endif
363 }
365 int cpu_inb(CPUState *env, int addr)
366 {
367 int val;
368 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
369 #ifdef DEBUG_IOPORT
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "inb : %04x %02x\n", addr, val);
372 #endif
373 #ifdef USE_KQEMU
374 if (env)
375 env->last_io_time = cpu_get_time_fast();
376 #endif
377 return val;
378 }
380 int cpu_inw(CPUState *env, int addr)
381 {
382 int val;
383 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
384 #ifdef DEBUG_IOPORT
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inw : %04x %04x\n", addr, val);
387 #endif
388 #ifdef USE_KQEMU
389 if (env)
390 env->last_io_time = cpu_get_time_fast();
391 #endif
392 return val;
393 }
395 int cpu_inl(CPUState *env, int addr)
396 {
397 int val;
398 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
399 #ifdef DEBUG_IOPORT
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inl : %04x %08x\n", addr, val);
402 #endif
403 #ifdef USE_KQEMU
404 if (env)
405 env->last_io_time = cpu_get_time_fast();
406 #endif
407 return val;
408 }
410 /***********************************************************/
411 void hw_error(const char *fmt, ...)
412 {
413 va_list ap;
414 #ifndef CONFIG_DM
415 CPUState *env;
416 #endif /* !CONFIG_DM */
418 va_start(ap, fmt);
419 fprintf(stderr, "qemu: hardware error: ");
420 vfprintf(stderr, fmt, ap);
421 fprintf(stderr, "\n");
422 #ifndef CONFIG_DM
423 for(env = first_cpu; env != NULL; env = env->next_cpu) {
424 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
425 #ifdef TARGET_I386
426 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
427 #else
428 cpu_dump_state(env, stderr, fprintf, 0);
429 #endif
430 }
431 #endif /* !CONFIG_DM */
432 va_end(ap);
433 abort();
434 }
436 /***********************************************************/
437 /* keyboard/mouse */
439 static QEMUPutKBDEvent *qemu_put_kbd_event;
440 static void *qemu_put_kbd_event_opaque;
441 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
442 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
444 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
445 {
446 qemu_put_kbd_event_opaque = opaque;
447 qemu_put_kbd_event = func;
448 }
450 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
451 void *opaque, int absolute,
452 const char *name)
453 {
454 QEMUPutMouseEntry *s, *cursor;
456 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
457 if (!s)
458 return NULL;
460 s->qemu_put_mouse_event = func;
461 s->qemu_put_mouse_event_opaque = opaque;
462 s->qemu_put_mouse_event_absolute = absolute;
463 s->qemu_put_mouse_event_name = qemu_strdup(name);
464 s->next = NULL;
466 if (!qemu_put_mouse_event_head) {
467 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
468 return s;
469 }
471 cursor = qemu_put_mouse_event_head;
472 while (cursor->next != NULL)
473 cursor = cursor->next;
475 cursor->next = s;
476 qemu_put_mouse_event_current = s;
478 return s;
479 }
481 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
482 {
483 QEMUPutMouseEntry *prev = NULL, *cursor;
485 if (!qemu_put_mouse_event_head || entry == NULL)
486 return;
488 cursor = qemu_put_mouse_event_head;
489 while (cursor != NULL && cursor != entry) {
490 prev = cursor;
491 cursor = cursor->next;
492 }
494 if (cursor == NULL) // does not exist or list empty
495 return;
496 else if (prev == NULL) { // entry is head
497 qemu_put_mouse_event_head = cursor->next;
498 if (qemu_put_mouse_event_current == entry)
499 qemu_put_mouse_event_current = cursor->next;
500 qemu_free(entry->qemu_put_mouse_event_name);
501 qemu_free(entry);
502 return;
503 }
505 prev->next = entry->next;
507 if (qemu_put_mouse_event_current == entry)
508 qemu_put_mouse_event_current = prev;
510 qemu_free(entry->qemu_put_mouse_event_name);
511 qemu_free(entry);
512 }
514 void kbd_put_keycode(int keycode)
515 {
516 if (qemu_put_kbd_event) {
517 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
518 }
519 }
521 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
522 {
523 QEMUPutMouseEvent *mouse_event;
524 void *mouse_event_opaque;
526 if (!qemu_put_mouse_event_current) {
527 return;
528 }
530 mouse_event =
531 qemu_put_mouse_event_current->qemu_put_mouse_event;
532 mouse_event_opaque =
533 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
535 if (mouse_event) {
536 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
537 }
538 }
540 int kbd_mouse_is_absolute(void)
541 {
542 if (!qemu_put_mouse_event_current)
543 return 0;
545 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
546 }
548 void do_info_mice(void)
549 {
550 QEMUPutMouseEntry *cursor;
551 int index = 0;
553 if (!qemu_put_mouse_event_head) {
554 term_printf("No mouse devices connected\n");
555 return;
556 }
558 term_printf("Mouse devices available:\n");
559 cursor = qemu_put_mouse_event_head;
560 while (cursor != NULL) {
561 term_printf("%c Mouse #%d: %s\n",
562 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
563 index, cursor->qemu_put_mouse_event_name);
564 index++;
565 cursor = cursor->next;
566 }
567 }
569 void do_mouse_set(int index)
570 {
571 QEMUPutMouseEntry *cursor;
572 int i = 0;
574 if (!qemu_put_mouse_event_head) {
575 term_printf("No mouse devices connected\n");
576 return;
577 }
579 cursor = qemu_put_mouse_event_head;
580 while (cursor != NULL && index != i) {
581 i++;
582 cursor = cursor->next;
583 }
585 if (cursor != NULL)
586 qemu_put_mouse_event_current = cursor;
587 else
588 term_printf("Mouse at given index not found\n");
589 }
591 /* compute with 96 bit intermediate result: (a*b)/c */
592 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
593 {
594 union {
595 uint64_t ll;
596 struct {
597 #ifdef WORDS_BIGENDIAN
598 uint32_t high, low;
599 #else
600 uint32_t low, high;
601 #endif
602 } l;
603 } u, res;
604 uint64_t rl, rh;
606 u.ll = a;
607 rl = (uint64_t)u.l.low * (uint64_t)b;
608 rh = (uint64_t)u.l.high * (uint64_t)b;
609 rh += (rl >> 32);
610 res.l.high = rh / c;
611 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
612 return res.ll;
613 }
615 /***********************************************************/
616 /* real time host monotonic timer */
618 #define QEMU_TIMER_BASE 1000000000LL
620 #ifdef WIN32
622 static int64_t clock_freq;
624 static void init_get_clock(void)
625 {
626 LARGE_INTEGER freq;
627 int ret;
628 ret = QueryPerformanceFrequency(&freq);
629 if (ret == 0) {
630 fprintf(stderr, "Could not calibrate ticks\n");
631 exit(1);
632 }
633 clock_freq = freq.QuadPart;
634 }
636 static int64_t get_clock(void)
637 {
638 LARGE_INTEGER ti;
639 QueryPerformanceCounter(&ti);
640 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
641 }
643 #else
645 static int use_rt_clock;
647 static void init_get_clock(void)
648 {
649 use_rt_clock = 0;
650 #if defined(__linux__)
651 {
652 struct timespec ts;
653 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
654 use_rt_clock = 1;
655 }
656 }
657 #endif
658 }
660 static int64_t get_clock(void)
661 {
662 #if defined(__linux__)
663 if (use_rt_clock) {
664 struct timespec ts;
665 clock_gettime(CLOCK_MONOTONIC, &ts);
666 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
667 } else
668 #endif
669 {
670 /* XXX: using gettimeofday leads to problems if the date
671 changes, so it should be avoided. */
672 struct timeval tv;
673 gettimeofday(&tv, NULL);
674 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
675 }
676 }
678 #endif
680 /***********************************************************/
681 /* guest cycle counter */
683 static int64_t cpu_ticks_prev;
684 static int64_t cpu_ticks_offset;
685 static int64_t cpu_clock_offset;
686 static int cpu_ticks_enabled;
688 /* return the host CPU cycle counter and handle stop/restart */
689 int64_t cpu_get_ticks(void)
690 {
691 if (!cpu_ticks_enabled) {
692 return cpu_ticks_offset;
693 } else {
694 int64_t ticks;
695 ticks = cpu_get_real_ticks();
696 if (cpu_ticks_prev > ticks) {
697 /* Note: non increasing ticks may happen if the host uses
698 software suspend */
699 cpu_ticks_offset += cpu_ticks_prev - ticks;
700 }
701 cpu_ticks_prev = ticks;
702 return ticks + cpu_ticks_offset;
703 }
704 }
706 /* return the host CPU monotonic timer and handle stop/restart */
707 static int64_t cpu_get_clock(void)
708 {
709 int64_t ti;
710 if (!cpu_ticks_enabled) {
711 return cpu_clock_offset;
712 } else {
713 ti = get_clock();
714 return ti + cpu_clock_offset;
715 }
716 }
718 /* enable cpu_get_ticks() */
719 void cpu_enable_ticks(void)
720 {
721 if (!cpu_ticks_enabled) {
722 cpu_ticks_offset -= cpu_get_real_ticks();
723 cpu_clock_offset -= get_clock();
724 cpu_ticks_enabled = 1;
725 }
726 }
728 /* disable cpu_get_ticks() : the clock is stopped. You must not call
729 cpu_get_ticks() after that. */
730 void cpu_disable_ticks(void)
731 {
732 if (cpu_ticks_enabled) {
733 cpu_ticks_offset = cpu_get_ticks();
734 cpu_clock_offset = cpu_get_clock();
735 cpu_ticks_enabled = 0;
736 }
737 }
739 /***********************************************************/
740 /* timers */
742 #define QEMU_TIMER_REALTIME 0
743 #define QEMU_TIMER_VIRTUAL 1
745 struct QEMUClock {
746 int type;
747 /* XXX: add frequency */
748 };
750 struct QEMUTimer {
751 QEMUClock *clock;
752 int64_t expire_time;
753 QEMUTimerCB *cb;
754 void *opaque;
755 struct QEMUTimer *next;
756 };
758 QEMUClock *rt_clock;
759 QEMUClock *vm_clock;
761 static QEMUTimer *active_timers[2];
762 #ifdef _WIN32
763 static MMRESULT timerID;
764 static HANDLE host_alarm = NULL;
765 static unsigned int period = 1;
766 #else
767 /* frequency of the times() clock tick */
768 static int timer_freq;
769 #endif
771 QEMUClock *qemu_new_clock(int type)
772 {
773 QEMUClock *clock;
774 clock = qemu_mallocz(sizeof(QEMUClock));
775 if (!clock)
776 return NULL;
777 clock->type = type;
778 return clock;
779 }
781 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
782 {
783 QEMUTimer *ts;
785 ts = qemu_mallocz(sizeof(QEMUTimer));
786 ts->clock = clock;
787 ts->cb = cb;
788 ts->opaque = opaque;
789 return ts;
790 }
792 void qemu_free_timer(QEMUTimer *ts)
793 {
794 qemu_free(ts);
795 }
797 /* stop a timer, but do not dealloc it */
798 void qemu_del_timer(QEMUTimer *ts)
799 {
800 QEMUTimer **pt, *t;
802 /* NOTE: this code must be signal safe because
803 qemu_timer_expired() can be called from a signal. */
804 pt = &active_timers[ts->clock->type];
805 for(;;) {
806 t = *pt;
807 if (!t)
808 break;
809 if (t == ts) {
810 *pt = t->next;
811 break;
812 }
813 pt = &t->next;
814 }
815 }
817 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
818 {
819 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
820 qemu_mod_timer(ts, expire_time);
821 }
823 /* modify the current timer so that it will be fired when current_time
824 >= expire_time. The corresponding callback will be called. */
825 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
826 {
827 QEMUTimer **pt, *t;
829 qemu_del_timer(ts);
831 /* add the timer in the sorted list */
832 /* NOTE: this code must be signal safe because
833 qemu_timer_expired() can be called from a signal. */
834 pt = &active_timers[ts->clock->type];
835 for(;;) {
836 t = *pt;
837 if (!t)
838 break;
839 if (t->expire_time > expire_time)
840 break;
841 pt = &t->next;
842 }
843 ts->expire_time = expire_time;
844 ts->next = *pt;
845 *pt = ts;
846 }
848 int qemu_timer_pending(QEMUTimer *ts)
849 {
850 QEMUTimer *t;
851 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
852 if (t == ts)
853 return 1;
854 }
855 return 0;
856 }
858 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
859 {
860 if (!timer_head)
861 return 0;
862 return (timer_head->expire_time <= current_time);
863 }
865 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
866 {
867 QEMUTimer *ts;
869 for(;;) {
870 ts = *ptimer_head;
871 if (!ts || ts->expire_time > current_time)
872 break;
873 /* remove timer from the list before calling the callback */
874 *ptimer_head = ts->next;
875 ts->next = NULL;
877 /* run the callback (the timer list can be modified) */
878 ts->cb(ts->opaque);
879 }
880 }
882 int64_t qemu_get_clock(QEMUClock *clock)
883 {
884 switch(clock->type) {
885 case QEMU_TIMER_REALTIME:
886 return get_clock() / 1000000;
887 default:
888 case QEMU_TIMER_VIRTUAL:
889 return cpu_get_clock();
890 }
891 }
893 static void init_timers(void)
894 {
895 init_get_clock();
896 ticks_per_sec = QEMU_TIMER_BASE;
897 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
898 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
899 }
901 /* save a timer */
902 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
903 {
904 uint64_t expire_time;
906 if (qemu_timer_pending(ts)) {
907 expire_time = ts->expire_time;
908 } else {
909 expire_time = -1;
910 }
911 qemu_put_be64(f, expire_time);
912 }
914 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
915 {
916 uint64_t expire_time;
918 expire_time = qemu_get_be64(f);
919 if (expire_time != -1) {
920 qemu_mod_timer(ts, expire_time);
921 } else {
922 qemu_del_timer(ts);
923 }
924 }
926 #ifdef CONFIG_DM
927 static void timer_save(QEMUFile *f, void *opaque)
928 {
929 /* need timer for save/restoe qemu_timer in usb_uhci */
930 if (cpu_ticks_enabled) {
931 hw_error("cannot save state if virtual timers are running");
932 }
933 qemu_put_be64s(f, &cpu_clock_offset);
934 }
936 static int timer_load(QEMUFile *f, void *opaque, int version_id)
937 {
938 if (version_id != 1)
939 return -EINVAL;
940 if (cpu_ticks_enabled) {
941 return -EINVAL;
942 }
944 qemu_get_be64s(f, &cpu_clock_offset);
945 return 0;
946 }
947 #else /* !CONFIG_DM */
948 static void timer_save(QEMUFile *f, void *opaque)
949 {
950 if (cpu_ticks_enabled) {
951 hw_error("cannot save state if virtual timers are running");
952 }
953 qemu_put_be64s(f, &cpu_ticks_offset);
954 qemu_put_be64s(f, &ticks_per_sec);
955 qemu_put_be64s(f, &cpu_clock_offset);
956 }
958 static int timer_load(QEMUFile *f, void *opaque, int version_id)
959 {
960 if (version_id != 1 && version_id != 2)
961 return -EINVAL;
962 if (cpu_ticks_enabled) {
963 return -EINVAL;
964 }
965 qemu_get_be64s(f, &cpu_ticks_offset);
966 qemu_get_be64s(f, &ticks_per_sec);
967 if (version_id == 2) {
968 qemu_get_be64s(f, &cpu_clock_offset);
969 }
970 return 0;
971 }
973 #ifdef _WIN32
974 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
975 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
976 #else
977 static void host_alarm_handler(int host_signum)
978 #endif
979 {
980 #if 0
981 #define DISP_FREQ 1000
982 {
983 static int64_t delta_min = INT64_MAX;
984 static int64_t delta_max, delta_cum, last_clock, delta, ti;
985 static int count;
986 ti = qemu_get_clock(vm_clock);
987 if (last_clock != 0) {
988 delta = ti - last_clock;
989 if (delta < delta_min)
990 delta_min = delta;
991 if (delta > delta_max)
992 delta_max = delta;
993 delta_cum += delta;
994 if (++count == DISP_FREQ) {
995 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
996 muldiv64(delta_min, 1000000, ticks_per_sec),
997 muldiv64(delta_max, 1000000, ticks_per_sec),
998 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
999 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1000 count = 0;
1001 delta_min = INT64_MAX;
1002 delta_max = 0;
1003 delta_cum = 0;
1006 last_clock = ti;
1008 #endif
1009 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1010 qemu_get_clock(vm_clock)) ||
1011 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1012 qemu_get_clock(rt_clock))) {
1013 #ifdef _WIN32
1014 SetEvent(host_alarm);
1015 #endif
1016 CPUState *env = cpu_single_env;
1017 if (env) {
1018 /* stop the currently executing cpu because a timer occured */
1019 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1020 #ifdef USE_KQEMU
1021 if (env->kqemu_enabled) {
1022 kqemu_cpu_interrupt(env);
1024 #endif
1029 #ifndef _WIN32
1031 #if defined(__linux__)
1033 #define RTC_FREQ 1024
1035 static int rtc_fd;
1037 static int start_rtc_timer(void)
1039 rtc_fd = open("/dev/rtc", O_RDONLY);
1040 if (rtc_fd < 0)
1041 return -1;
1042 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1043 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1044 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1045 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1046 goto fail;
1048 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1049 fail:
1050 close(rtc_fd);
1051 return -1;
1053 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1054 return 0;
1057 #else
1059 static int start_rtc_timer(void)
1061 return -1;
1064 #endif /* !defined(__linux__) */
1066 #endif /* !defined(_WIN32) */
1068 #endif /* !CONFIG_DM */
1070 static void init_timer_alarm(void)
1072 #ifdef _WIN32
1074 int count=0;
1075 TIMECAPS tc;
1077 ZeroMemory(&tc, sizeof(TIMECAPS));
1078 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1079 if (period < tc.wPeriodMin)
1080 period = tc.wPeriodMin;
1081 timeBeginPeriod(period);
1082 timerID = timeSetEvent(1, // interval (ms)
1083 period, // resolution
1084 host_alarm_handler, // function
1085 (DWORD)&count, // user parameter
1086 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1087 if( !timerID ) {
1088 perror("failed timer alarm");
1089 exit(1);
1091 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1092 if (!host_alarm) {
1093 perror("failed CreateEvent");
1094 exit(1);
1096 qemu_add_wait_object(host_alarm, NULL, NULL);
1098 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1099 #else
1101 #ifndef CONFIG_DM
1102 struct sigaction act;
1103 struct itimerval itv;
1104 #endif
1106 /* get times() syscall frequency */
1107 timer_freq = sysconf(_SC_CLK_TCK);
1109 #ifndef CONFIG_DM
1110 /* timer signal */
1111 sigfillset(&act.sa_mask);
1112 act.sa_flags = 0;
1113 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1114 act.sa_flags |= SA_ONSTACK;
1115 #endif
1116 act.sa_handler = host_alarm_handler;
1117 sigaction(SIGALRM, &act, NULL);
1119 itv.it_interval.tv_sec = 0;
1120 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1121 itv.it_value.tv_sec = 0;
1122 itv.it_value.tv_usec = 10 * 1000;
1123 setitimer(ITIMER_REAL, &itv, NULL);
1124 /* we probe the tick duration of the kernel to inform the user if
1125 the emulated kernel requested a too high timer frequency */
1126 getitimer(ITIMER_REAL, &itv);
1128 #if defined(__linux__)
1129 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1130 have timers with 1 ms resolution. The correct solution will
1131 be to use the POSIX real time timers available in recent
1132 2.6 kernels */
1133 if (itv.it_interval.tv_usec > 1000 || 1) {
1134 /* try to use /dev/rtc to have a faster timer */
1135 if (start_rtc_timer() < 0)
1136 goto use_itimer;
1137 /* disable itimer */
1138 itv.it_interval.tv_sec = 0;
1139 itv.it_interval.tv_usec = 0;
1140 itv.it_value.tv_sec = 0;
1141 itv.it_value.tv_usec = 0;
1142 setitimer(ITIMER_REAL, &itv, NULL);
1144 /* use the RTC */
1145 sigaction(SIGIO, &act, NULL);
1146 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1147 fcntl(rtc_fd, F_SETOWN, getpid());
1148 } else
1149 #endif /* defined(__linux__) */
1151 use_itimer:
1152 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1153 PIT_FREQ) / 1000000;
1155 #endif /* CONFIG_DM */
1157 #endif
1160 void quit_timers(void)
1162 #ifdef _WIN32
1163 timeKillEvent(timerID);
1164 timeEndPeriod(period);
1165 if (host_alarm) {
1166 CloseHandle(host_alarm);
1167 host_alarm = NULL;
1169 #endif
1172 /***********************************************************/
1173 /* character device */
1175 static void qemu_chr_event(CharDriverState *s, int event)
1177 if (!s->chr_event)
1178 return;
1179 s->chr_event(s->handler_opaque, event);
1182 static void qemu_chr_reset_bh(void *opaque)
1184 CharDriverState *s = opaque;
1185 qemu_chr_event(s, CHR_EVENT_RESET);
1186 qemu_bh_delete(s->bh);
1187 s->bh = NULL;
1190 void qemu_chr_reset(CharDriverState *s)
1192 if (s->bh == NULL) {
1193 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1194 qemu_bh_schedule(s->bh);
1198 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1200 return s->chr_write(s, buf, len);
1203 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1205 if (!s->chr_ioctl)
1206 return -ENOTSUP;
1207 return s->chr_ioctl(s, cmd, arg);
1210 int qemu_chr_can_read(CharDriverState *s)
1212 if (!s->chr_can_read)
1213 return 0;
1214 return s->chr_can_read(s->handler_opaque);
1217 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1219 s->chr_read(s->handler_opaque, buf, len);
1223 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1225 char buf[4096];
1226 va_list ap;
1227 va_start(ap, fmt);
1228 vsnprintf(buf, sizeof(buf), fmt, ap);
1229 qemu_chr_write(s, buf, strlen(buf));
1230 va_end(ap);
1233 void qemu_chr_send_event(CharDriverState *s, int event)
1235 if (s->chr_send_event)
1236 s->chr_send_event(s, event);
1239 void qemu_chr_add_handlers(CharDriverState *s,
1240 IOCanRWHandler *fd_can_read,
1241 IOReadHandler *fd_read,
1242 IOEventHandler *fd_event,
1243 void *opaque)
1245 s->chr_can_read = fd_can_read;
1246 s->chr_read = fd_read;
1247 s->chr_event = fd_event;
1248 s->handler_opaque = opaque;
1249 if (s->chr_update_read_handler)
1250 s->chr_update_read_handler(s);
1253 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1255 return len;
1258 static CharDriverState *qemu_chr_open_null(void)
1260 CharDriverState *chr;
1262 chr = qemu_mallocz(sizeof(CharDriverState));
1263 if (!chr)
1264 return NULL;
1265 chr->chr_write = null_chr_write;
1266 return chr;
1269 #ifdef _WIN32
1271 static void socket_cleanup(void)
1273 WSACleanup();
1276 static int socket_init(void)
1278 WSADATA Data;
1279 int ret, err;
1281 ret = WSAStartup(MAKEWORD(2,2), &Data);
1282 if (ret != 0) {
1283 err = WSAGetLastError();
1284 fprintf(stderr, "WSAStartup: %d\n", err);
1285 return -1;
1287 atexit(socket_cleanup);
1288 return 0;
1291 static int send_all(int fd, const uint8_t *buf, int len1)
1293 int ret, len;
1295 len = len1;
1296 while (len > 0) {
1297 ret = send(fd, buf, len, 0);
1298 if (ret < 0) {
1299 int errno;
1300 errno = WSAGetLastError();
1301 if (errno != WSAEWOULDBLOCK) {
1302 return -1;
1304 } else if (ret == 0) {
1305 break;
1306 } else {
1307 buf += ret;
1308 len -= ret;
1311 return len1 - len;
1314 void socket_set_nonblock(int fd)
1316 unsigned long opt = 1;
1317 ioctlsocket(fd, FIONBIO, &opt);
1320 #else
1322 static int unix_write(int fd, const uint8_t *buf, int len1)
1324 int ret, sel_ret, len;
1325 int max_fd;
1326 fd_set writefds;
1327 struct timeval timeout;
1329 max_fd = fd;
1331 len = len1;
1332 while (len > 0) {
1333 FD_ZERO(&writefds);
1334 FD_SET(fd, &writefds);
1335 timeout.tv_sec = 0;
1336 timeout.tv_usec = 0;
1337 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1338 if (sel_ret <= 0) {
1339 /* Timeout or select error */
1340 return -1;
1341 } else {
1342 ret = write(fd, buf, len);
1343 if (ret < 0) {
1344 if (errno != EINTR && errno != EAGAIN)
1345 return -1;
1346 } else if (ret == 0) {
1347 break;
1348 } else {
1349 buf += ret;
1350 len -= ret;
1354 return len1 - len;
1357 static inline int send_all(int fd, const uint8_t *buf, int len1)
1359 return unix_write(fd, buf, len1);
1362 void socket_set_nonblock(int fd)
1364 fcntl(fd, F_SETFL, O_NONBLOCK);
1366 #endif /* !_WIN32 */
1368 #ifndef _WIN32
1370 typedef struct {
1371 int fd_in, fd_out;
1372 int max_size;
1373 } FDCharDriver;
1375 #define STDIO_MAX_CLIENTS 2
1377 static int stdio_nb_clients;
1378 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1380 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1382 FDCharDriver *s = chr->opaque;
1383 return unix_write(s->fd_out, buf, len);
1386 static int fd_chr_read_poll(void *opaque)
1388 CharDriverState *chr = opaque;
1389 FDCharDriver *s = chr->opaque;
1391 s->max_size = qemu_chr_can_read(chr);
1392 return s->max_size;
1395 static void fd_chr_read(void *opaque)
1397 CharDriverState *chr = opaque;
1398 FDCharDriver *s = chr->opaque;
1399 int size, len;
1400 uint8_t buf[1024];
1402 len = sizeof(buf);
1403 if (len > s->max_size)
1404 len = s->max_size;
1405 if (len == 0)
1406 return;
1407 size = read(s->fd_in, buf, len);
1408 if (size == 0) {
1409 /* FD has been closed. Remove it from the active list. */
1410 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1411 return;
1413 if (size > 0) {
1414 qemu_chr_read(chr, buf, size);
1418 static void fd_chr_update_read_handler(CharDriverState *chr)
1420 FDCharDriver *s = chr->opaque;
1422 if (s->fd_in >= 0) {
1423 if (nographic && s->fd_in == 0) {
1424 } else {
1425 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1426 fd_chr_read, NULL, chr);
1431 /* open a character device to a unix fd */
1432 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1434 CharDriverState *chr;
1435 FDCharDriver *s;
1437 chr = qemu_mallocz(sizeof(CharDriverState));
1438 if (!chr)
1439 return NULL;
1440 s = qemu_mallocz(sizeof(FDCharDriver));
1441 if (!s) {
1442 free(chr);
1443 return NULL;
1445 s->fd_in = fd_in;
1446 s->fd_out = fd_out;
1447 chr->opaque = s;
1448 chr->chr_write = fd_chr_write;
1449 chr->chr_update_read_handler = fd_chr_update_read_handler;
1451 qemu_chr_reset(chr);
1453 return chr;
1456 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1458 int fd_out;
1460 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1461 if (fd_out < 0)
1462 return NULL;
1463 return qemu_chr_open_fd(-1, fd_out);
1466 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1468 int fd_in, fd_out;
1469 char filename_in[256], filename_out[256];
1471 snprintf(filename_in, 256, "%s.in", filename);
1472 snprintf(filename_out, 256, "%s.out", filename);
1473 fd_in = open(filename_in, O_RDWR | O_BINARY);
1474 fd_out = open(filename_out, O_RDWR | O_BINARY);
1475 if (fd_in < 0 || fd_out < 0) {
1476 if (fd_in >= 0)
1477 close(fd_in);
1478 if (fd_out >= 0)
1479 close(fd_out);
1480 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1481 if (fd_in < 0)
1482 return NULL;
1484 return qemu_chr_open_fd(fd_in, fd_out);
1488 /* for STDIO, we handle the case where several clients use it
1489 (nographic mode) */
1491 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1493 #define TERM_FIFO_MAX_SIZE 1
1495 static int term_got_escape, client_index;
1496 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1497 static int term_fifo_size;
1498 static int term_timestamps;
1499 static int64_t term_timestamps_start;
1501 void term_print_help(void)
1503 printf("\n"
1504 "C-a h print this help\n"
1505 "C-a x exit emulator\n"
1506 "C-a s save disk data back to file (if -snapshot)\n"
1507 "C-a b send break (magic sysrq)\n"
1508 "C-a t toggle console timestamps\n"
1509 "C-a c switch between console and monitor\n"
1510 "C-a C-a send C-a\n"
1511 );
1514 /* called when a char is received */
1515 static void stdio_received_byte(int ch)
1517 if (term_got_escape) {
1518 term_got_escape = 0;
1519 switch(ch) {
1520 case 'h':
1521 term_print_help();
1522 break;
1523 case 'x':
1524 exit(0);
1525 break;
1526 case 's':
1528 int i;
1529 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1530 if (bs_table[i])
1531 bdrv_commit(bs_table[i]);
1534 break;
1535 case 'b':
1536 if (client_index < stdio_nb_clients) {
1537 CharDriverState *chr;
1538 FDCharDriver *s;
1540 chr = stdio_clients[client_index];
1541 s = chr->opaque;
1542 qemu_chr_event(chr, CHR_EVENT_BREAK);
1544 break;
1545 case 'c':
1546 client_index++;
1547 if (client_index >= stdio_nb_clients)
1548 client_index = 0;
1549 if (client_index == 0) {
1550 /* send a new line in the monitor to get the prompt */
1551 ch = '\r';
1552 goto send_char;
1554 break;
1555 case 't':
1556 term_timestamps = !term_timestamps;
1557 term_timestamps_start = -1;
1558 break;
1559 case TERM_ESCAPE:
1560 goto send_char;
1562 } else if (ch == TERM_ESCAPE) {
1563 term_got_escape = 1;
1564 } else {
1565 send_char:
1566 if (client_index < stdio_nb_clients) {
1567 uint8_t buf[1];
1568 CharDriverState *chr;
1570 chr = stdio_clients[client_index];
1571 if (qemu_chr_can_read(chr) > 0) {
1572 buf[0] = ch;
1573 qemu_chr_read(chr, buf, 1);
1574 } else if (term_fifo_size == 0) {
1575 term_fifo[term_fifo_size++] = ch;
1581 static int stdio_read_poll(void *opaque)
1583 CharDriverState *chr;
1585 if (client_index < stdio_nb_clients) {
1586 chr = stdio_clients[client_index];
1587 /* try to flush the queue if needed */
1588 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1589 qemu_chr_read(chr, term_fifo, 1);
1590 term_fifo_size = 0;
1592 /* see if we can absorb more chars */
1593 if (term_fifo_size == 0)
1594 return 1;
1595 else
1596 return 0;
1597 } else {
1598 return 1;
1602 static void stdio_read(void *opaque)
1604 int size;
1605 uint8_t buf[1];
1607 size = read(0, buf, 1);
1608 if (size == 0) {
1609 /* stdin has been closed. Remove it from the active list. */
1610 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1611 return;
1613 if (size > 0)
1614 stdio_received_byte(buf[0]);
1617 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1619 FDCharDriver *s = chr->opaque;
1620 if (!term_timestamps) {
1621 return unix_write(s->fd_out, buf, len);
1622 } else {
1623 int i;
1624 char buf1[64];
1626 for(i = 0; i < len; i++) {
1627 unix_write(s->fd_out, buf + i, 1);
1628 if (buf[i] == '\n') {
1629 int64_t ti;
1630 int secs;
1632 ti = get_clock();
1633 if (term_timestamps_start == -1)
1634 term_timestamps_start = ti;
1635 ti -= term_timestamps_start;
1636 secs = ti / 1000000000;
1637 snprintf(buf1, sizeof(buf1),
1638 "[%02d:%02d:%02d.%03d] ",
1639 secs / 3600,
1640 (secs / 60) % 60,
1641 secs % 60,
1642 (int)((ti / 1000000) % 1000));
1643 unix_write(s->fd_out, buf1, strlen(buf1));
1646 return len;
1650 /* init terminal so that we can grab keys */
1651 static struct termios oldtty;
1652 static int old_fd0_flags;
1654 static void term_exit(void)
1656 tcsetattr (0, TCSANOW, &oldtty);
1657 fcntl(0, F_SETFL, old_fd0_flags);
1660 static void term_init(void)
1662 struct termios tty;
1664 tcgetattr (0, &tty);
1665 oldtty = tty;
1666 old_fd0_flags = fcntl(0, F_GETFL);
1668 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1669 |INLCR|IGNCR|ICRNL|IXON);
1670 tty.c_oflag |= OPOST;
1671 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1672 /* if graphical mode, we allow Ctrl-C handling */
1673 if (nographic)
1674 tty.c_lflag &= ~ISIG;
1675 tty.c_cflag &= ~(CSIZE|PARENB);
1676 tty.c_cflag |= CS8;
1677 tty.c_cc[VMIN] = 1;
1678 tty.c_cc[VTIME] = 0;
1680 tcsetattr (0, TCSANOW, &tty);
1682 atexit(term_exit);
1684 fcntl(0, F_SETFL, O_NONBLOCK);
1687 static CharDriverState *qemu_chr_open_stdio(void)
1689 CharDriverState *chr;
1691 if (nographic) {
1692 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1693 return NULL;
1694 chr = qemu_chr_open_fd(0, 1);
1695 chr->chr_write = stdio_write;
1696 if (stdio_nb_clients == 0)
1697 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1698 client_index = stdio_nb_clients;
1699 } else {
1700 if (stdio_nb_clients != 0)
1701 return NULL;
1702 chr = qemu_chr_open_fd(0, 1);
1704 stdio_clients[stdio_nb_clients++] = chr;
1705 if (stdio_nb_clients == 1) {
1706 /* set the terminal in raw mode */
1707 term_init();
1709 return chr;
1712 /*
1713 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1714 * The entry is <domain-path><storeString>/tty and the value is the name
1715 * of the pty associated with the device.
1716 */
1717 static int store_dev_info(char *devName, int domid,
1718 CharDriverState *cState, char *storeString)
1720 int xc_handle;
1721 struct xs_handle *xs;
1722 char *path;
1723 char *newpath;
1724 FDCharDriver *s;
1725 char *pts;
1727 /* Check for valid arguments (at least, prevent segfaults). */
1728 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1729 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1730 return EINVAL;
1733 /*
1734 * Only continue if we're talking to a pty
1735 * Actually, the following code works for any CharDriverState using
1736 * FDCharDriver, but we really only care about pty's here
1737 */
1738 if (strcmp(devName, "pty"))
1739 return 0;
1741 s = cState->opaque;
1742 if (s == NULL) {
1743 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1744 __FUNCTION__, storeString, devName);
1745 return EBADF;
1748 pts = ptsname(s->fd_in);
1749 if (pts == NULL) {
1750 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1751 "error %d (%s)\n",
1752 __FUNCTION__, storeString, devName, errno, strerror(errno));
1753 return errno;
1756 /* We now have everything we need to set the xenstore entry. */
1757 xs = xs_daemon_open();
1758 if (xs == NULL) {
1759 fprintf(logfile, "Could not contact XenStore\n");
1760 return -1;
1763 xc_handle = xc_interface_open();
1764 if (xc_handle == -1) {
1765 fprintf(logfile, "xc_interface_open() error\n");
1766 return -1;
1769 path = xs_get_domain_path(xs, domid);
1770 if (path == NULL) {
1771 fprintf(logfile, "xs_get_domain_path() error\n");
1772 return -1;
1774 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1775 strlen("/tty") + 1));
1776 if (newpath == NULL) {
1777 free(path); /* realloc errors leave old block */
1778 fprintf(logfile, "realloc error\n");
1779 return -1;
1781 path = newpath;
1783 strcat(path, storeString);
1784 strcat(path, "/tty");
1785 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1786 fprintf(logfile, "xs_write for '%s' fail", storeString);
1787 return -1;
1790 free(path);
1791 xs_daemon_close(xs);
1792 close(xc_handle);
1794 return 0;
1797 #if defined(__linux__)
1798 static CharDriverState *qemu_chr_open_pty(void)
1800 struct termios tty;
1801 int master_fd, slave_fd;
1803 /* Not satisfying */
1804 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1805 return NULL;
1808 /* Set raw attributes on the pty. */
1809 cfmakeraw(&tty);
1810 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1812 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1814 return qemu_chr_open_fd(master_fd, master_fd);
1817 static void tty_serial_init(int fd, int speed,
1818 int parity, int data_bits, int stop_bits)
1820 struct termios tty;
1821 speed_t spd;
1823 #if 0
1824 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1825 speed, parity, data_bits, stop_bits);
1826 #endif
1827 tcgetattr (fd, &tty);
1829 switch(speed) {
1830 case 50:
1831 spd = B50;
1832 break;
1833 case 75:
1834 spd = B75;
1835 break;
1836 case 300:
1837 spd = B300;
1838 break;
1839 case 600:
1840 spd = B600;
1841 break;
1842 case 1200:
1843 spd = B1200;
1844 break;
1845 case 2400:
1846 spd = B2400;
1847 break;
1848 case 4800:
1849 spd = B4800;
1850 break;
1851 case 9600:
1852 spd = B9600;
1853 break;
1854 case 19200:
1855 spd = B19200;
1856 break;
1857 case 38400:
1858 spd = B38400;
1859 break;
1860 case 57600:
1861 spd = B57600;
1862 break;
1863 default:
1864 case 115200:
1865 spd = B115200;
1866 break;
1869 cfsetispeed(&tty, spd);
1870 cfsetospeed(&tty, spd);
1872 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1873 |INLCR|IGNCR|ICRNL|IXON);
1874 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1875 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1876 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1877 switch(data_bits) {
1878 default:
1879 case 8:
1880 tty.c_cflag |= CS8;
1881 break;
1882 case 7:
1883 tty.c_cflag |= CS7;
1884 break;
1885 case 6:
1886 tty.c_cflag |= CS6;
1887 break;
1888 case 5:
1889 tty.c_cflag |= CS5;
1890 break;
1892 switch(parity) {
1893 default:
1894 case 'N':
1895 break;
1896 case 'E':
1897 tty.c_cflag |= PARENB;
1898 break;
1899 case 'O':
1900 tty.c_cflag |= PARENB | PARODD;
1901 break;
1903 if (stop_bits == 2)
1904 tty.c_cflag |= CSTOPB;
1906 tcsetattr (fd, TCSANOW, &tty);
1909 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1911 FDCharDriver *s = chr->opaque;
1913 switch(cmd) {
1914 case CHR_IOCTL_SERIAL_SET_PARAMS:
1916 QEMUSerialSetParams *ssp = arg;
1917 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1918 ssp->data_bits, ssp->stop_bits);
1920 break;
1921 case CHR_IOCTL_SERIAL_SET_BREAK:
1923 int enable = *(int *)arg;
1924 if (enable)
1925 tcsendbreak(s->fd_in, 1);
1927 break;
1928 default:
1929 return -ENOTSUP;
1931 return 0;
1934 static CharDriverState *qemu_chr_open_tty(const char *filename)
1936 CharDriverState *chr;
1937 int fd;
1939 fd = open(filename, O_RDWR | O_NONBLOCK);
1940 if (fd < 0)
1941 return NULL;
1942 fcntl(fd, F_SETFL, O_NONBLOCK);
1943 tty_serial_init(fd, 115200, 'N', 8, 1);
1944 chr = qemu_chr_open_fd(fd, fd);
1945 if (!chr)
1946 return NULL;
1947 chr->chr_ioctl = tty_serial_ioctl;
1948 qemu_chr_reset(chr);
1949 return chr;
1952 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1954 int fd = (int)chr->opaque;
1955 uint8_t b;
1957 switch(cmd) {
1958 case CHR_IOCTL_PP_READ_DATA:
1959 if (ioctl(fd, PPRDATA, &b) < 0)
1960 return -ENOTSUP;
1961 *(uint8_t *)arg = b;
1962 break;
1963 case CHR_IOCTL_PP_WRITE_DATA:
1964 b = *(uint8_t *)arg;
1965 if (ioctl(fd, PPWDATA, &b) < 0)
1966 return -ENOTSUP;
1967 break;
1968 case CHR_IOCTL_PP_READ_CONTROL:
1969 if (ioctl(fd, PPRCONTROL, &b) < 0)
1970 return -ENOTSUP;
1971 *(uint8_t *)arg = b;
1972 break;
1973 case CHR_IOCTL_PP_WRITE_CONTROL:
1974 b = *(uint8_t *)arg;
1975 if (ioctl(fd, PPWCONTROL, &b) < 0)
1976 return -ENOTSUP;
1977 break;
1978 case CHR_IOCTL_PP_READ_STATUS:
1979 if (ioctl(fd, PPRSTATUS, &b) < 0)
1980 return -ENOTSUP;
1981 *(uint8_t *)arg = b;
1982 break;
1983 default:
1984 return -ENOTSUP;
1986 return 0;
1989 static CharDriverState *qemu_chr_open_pp(const char *filename)
1991 CharDriverState *chr;
1992 int fd;
1994 fd = open(filename, O_RDWR);
1995 if (fd < 0)
1996 return NULL;
1998 if (ioctl(fd, PPCLAIM) < 0) {
1999 close(fd);
2000 return NULL;
2003 chr = qemu_mallocz(sizeof(CharDriverState));
2004 if (!chr) {
2005 close(fd);
2006 return NULL;
2008 chr->opaque = (void *)fd;
2009 chr->chr_write = null_chr_write;
2010 chr->chr_ioctl = pp_ioctl;
2012 qemu_chr_reset(chr);
2014 return chr;
2017 #else
2018 static CharDriverState *qemu_chr_open_pty(void)
2020 return NULL;
2022 #endif
2024 #endif /* !defined(_WIN32) */
2026 #ifdef _WIN32
2027 typedef struct {
2028 CharDriverState *chr;
2029 int max_size;
2030 HANDLE hcom, hrecv, hsend;
2031 OVERLAPPED orecv, osend;
2032 BOOL fpipe;
2033 DWORD len;
2034 } WinCharState;
2036 #define NSENDBUF 2048
2037 #define NRECVBUF 2048
2038 #define MAXCONNECT 1
2039 #define NTIMEOUT 5000
2041 static int win_chr_poll(void *opaque);
2042 static int win_chr_pipe_poll(void *opaque);
2044 static void win_chr_close2(WinCharState *s)
2046 if (s->hsend) {
2047 CloseHandle(s->hsend);
2048 s->hsend = NULL;
2050 if (s->hrecv) {
2051 CloseHandle(s->hrecv);
2052 s->hrecv = NULL;
2054 if (s->hcom) {
2055 CloseHandle(s->hcom);
2056 s->hcom = NULL;
2058 if (s->fpipe)
2059 qemu_del_polling_cb(win_chr_pipe_poll, s);
2060 else
2061 qemu_del_polling_cb(win_chr_poll, s);
2064 static void win_chr_close(CharDriverState *chr)
2066 WinCharState *s = chr->opaque;
2067 win_chr_close2(s);
2070 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2072 COMMCONFIG comcfg;
2073 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2074 COMSTAT comstat;
2075 DWORD size;
2076 DWORD err;
2078 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2079 if (!s->hsend) {
2080 fprintf(stderr, "Failed CreateEvent\n");
2081 goto fail;
2083 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2084 if (!s->hrecv) {
2085 fprintf(stderr, "Failed CreateEvent\n");
2086 goto fail;
2089 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2090 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2091 if (s->hcom == INVALID_HANDLE_VALUE) {
2092 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2093 s->hcom = NULL;
2094 goto fail;
2097 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2098 fprintf(stderr, "Failed SetupComm\n");
2099 goto fail;
2102 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2103 size = sizeof(COMMCONFIG);
2104 GetDefaultCommConfig(filename, &comcfg, &size);
2105 comcfg.dcb.DCBlength = sizeof(DCB);
2106 CommConfigDialog(filename, NULL, &comcfg);
2108 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2109 fprintf(stderr, "Failed SetCommState\n");
2110 goto fail;
2113 if (!SetCommMask(s->hcom, EV_ERR)) {
2114 fprintf(stderr, "Failed SetCommMask\n");
2115 goto fail;
2118 cto.ReadIntervalTimeout = MAXDWORD;
2119 if (!SetCommTimeouts(s->hcom, &cto)) {
2120 fprintf(stderr, "Failed SetCommTimeouts\n");
2121 goto fail;
2124 if (!ClearCommError(s->hcom, &err, &comstat)) {
2125 fprintf(stderr, "Failed ClearCommError\n");
2126 goto fail;
2128 s->chr = chr;
2129 qemu_add_polling_cb(win_chr_poll, s);
2130 return 0;
2132 fail:
2133 win_chr_close2(s);
2134 return -1;
2137 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2139 WinCharState *s = chr->opaque;
2140 DWORD len, ret, size, err;
2142 len = len1;
2143 ZeroMemory(&s->osend, sizeof(s->osend));
2144 s->osend.hEvent = s->hsend;
2145 while (len > 0) {
2146 if (s->hsend)
2147 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2148 else
2149 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2150 if (!ret) {
2151 err = GetLastError();
2152 if (err == ERROR_IO_PENDING) {
2153 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2154 if (ret) {
2155 buf += size;
2156 len -= size;
2157 } else {
2158 break;
2160 } else {
2161 break;
2163 } else {
2164 buf += size;
2165 len -= size;
2168 return len1 - len;
2171 static int win_chr_read_poll(WinCharState *s)
2173 s->max_size = qemu_chr_can_read(s->chr);
2174 return s->max_size;
2177 static void win_chr_readfile(WinCharState *s)
2179 int ret, err;
2180 uint8_t buf[1024];
2181 DWORD size;
2183 ZeroMemory(&s->orecv, sizeof(s->orecv));
2184 s->orecv.hEvent = s->hrecv;
2185 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2186 if (!ret) {
2187 err = GetLastError();
2188 if (err == ERROR_IO_PENDING) {
2189 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2193 if (size > 0) {
2194 qemu_chr_read(s->chr, buf, size);
2198 static void win_chr_read(WinCharState *s)
2200 if (s->len > s->max_size)
2201 s->len = s->max_size;
2202 if (s->len == 0)
2203 return;
2205 win_chr_readfile(s);
2208 static int win_chr_poll(void *opaque)
2210 WinCharState *s = opaque;
2211 COMSTAT status;
2212 DWORD comerr;
2214 ClearCommError(s->hcom, &comerr, &status);
2215 if (status.cbInQue > 0) {
2216 s->len = status.cbInQue;
2217 win_chr_read_poll(s);
2218 win_chr_read(s);
2219 return 1;
2221 return 0;
2224 static CharDriverState *qemu_chr_open_win(const char *filename)
2226 CharDriverState *chr;
2227 WinCharState *s;
2229 chr = qemu_mallocz(sizeof(CharDriverState));
2230 if (!chr)
2231 return NULL;
2232 s = qemu_mallocz(sizeof(WinCharState));
2233 if (!s) {
2234 free(chr);
2235 return NULL;
2237 chr->opaque = s;
2238 chr->chr_write = win_chr_write;
2239 chr->chr_close = win_chr_close;
2241 if (win_chr_init(s, chr, filename) < 0) {
2242 free(s);
2243 free(chr);
2244 return NULL;
2246 qemu_chr_reset(chr);
2247 return chr;
2250 static int win_chr_pipe_poll(void *opaque)
2252 WinCharState *s = opaque;
2253 DWORD size;
2255 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2256 if (size > 0) {
2257 s->len = size;
2258 win_chr_read_poll(s);
2259 win_chr_read(s);
2260 return 1;
2262 return 0;
2265 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2267 OVERLAPPED ov;
2268 int ret;
2269 DWORD size;
2270 char openname[256];
2272 s->fpipe = TRUE;
2274 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2275 if (!s->hsend) {
2276 fprintf(stderr, "Failed CreateEvent\n");
2277 goto fail;
2279 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2280 if (!s->hrecv) {
2281 fprintf(stderr, "Failed CreateEvent\n");
2282 goto fail;
2285 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2286 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2287 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2288 PIPE_WAIT,
2289 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2290 if (s->hcom == INVALID_HANDLE_VALUE) {
2291 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2292 s->hcom = NULL;
2293 goto fail;
2296 ZeroMemory(&ov, sizeof(ov));
2297 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2298 ret = ConnectNamedPipe(s->hcom, &ov);
2299 if (ret) {
2300 fprintf(stderr, "Failed ConnectNamedPipe\n");
2301 goto fail;
2304 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2305 if (!ret) {
2306 fprintf(stderr, "Failed GetOverlappedResult\n");
2307 if (ov.hEvent) {
2308 CloseHandle(ov.hEvent);
2309 ov.hEvent = NULL;
2311 goto fail;
2314 if (ov.hEvent) {
2315 CloseHandle(ov.hEvent);
2316 ov.hEvent = NULL;
2318 qemu_add_polling_cb(win_chr_pipe_poll, s);
2319 return 0;
2321 fail:
2322 win_chr_close2(s);
2323 return -1;
2327 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2329 CharDriverState *chr;
2330 WinCharState *s;
2332 chr = qemu_mallocz(sizeof(CharDriverState));
2333 if (!chr)
2334 return NULL;
2335 s = qemu_mallocz(sizeof(WinCharState));
2336 if (!s) {
2337 free(chr);
2338 return NULL;
2340 chr->opaque = s;
2341 chr->chr_write = win_chr_write;
2342 chr->chr_close = win_chr_close;
2344 if (win_chr_pipe_init(s, filename) < 0) {
2345 free(s);
2346 free(chr);
2347 return NULL;
2349 qemu_chr_reset(chr);
2350 return chr;
2353 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2355 CharDriverState *chr;
2356 WinCharState *s;
2358 chr = qemu_mallocz(sizeof(CharDriverState));
2359 if (!chr)
2360 return NULL;
2361 s = qemu_mallocz(sizeof(WinCharState));
2362 if (!s) {
2363 free(chr);
2364 return NULL;
2366 s->hcom = fd_out;
2367 chr->opaque = s;
2368 chr->chr_write = win_chr_write;
2369 qemu_chr_reset(chr);
2370 return chr;
2373 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2375 HANDLE fd_out;
2377 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2378 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2379 if (fd_out == INVALID_HANDLE_VALUE)
2380 return NULL;
2382 return qemu_chr_open_win_file(fd_out);
2384 #endif
2386 /***********************************************************/
2387 /* UDP Net console */
2389 typedef struct {
2390 int fd;
2391 struct sockaddr_in daddr;
2392 char buf[1024];
2393 int bufcnt;
2394 int bufptr;
2395 int max_size;
2396 } NetCharDriver;
2398 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2400 NetCharDriver *s = chr->opaque;
2402 return sendto(s->fd, buf, len, 0,
2403 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2406 static int udp_chr_read_poll(void *opaque)
2408 CharDriverState *chr = opaque;
2409 NetCharDriver *s = chr->opaque;
2411 s->max_size = qemu_chr_can_read(chr);
2413 /* If there were any stray characters in the queue process them
2414 * first
2415 */
2416 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2417 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2418 s->bufptr++;
2419 s->max_size = qemu_chr_can_read(chr);
2421 return s->max_size;
2424 static void udp_chr_read(void *opaque)
2426 CharDriverState *chr = opaque;
2427 NetCharDriver *s = chr->opaque;
2429 if (s->max_size == 0)
2430 return;
2431 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2432 s->bufptr = s->bufcnt;
2433 if (s->bufcnt <= 0)
2434 return;
2436 s->bufptr = 0;
2437 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2438 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2439 s->bufptr++;
2440 s->max_size = qemu_chr_can_read(chr);
2444 static void udp_chr_update_read_handler(CharDriverState *chr)
2446 NetCharDriver *s = chr->opaque;
2448 if (s->fd >= 0) {
2449 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2450 udp_chr_read, NULL, chr);
2454 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2455 #ifndef _WIN32
2456 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2457 #endif
2458 int parse_host_src_port(struct sockaddr_in *haddr,
2459 struct sockaddr_in *saddr,
2460 const char *str);
2462 static CharDriverState *qemu_chr_open_udp(const char *def)
2464 CharDriverState *chr = NULL;
2465 NetCharDriver *s = NULL;
2466 int fd = -1;
2467 struct sockaddr_in saddr;
2469 chr = qemu_mallocz(sizeof(CharDriverState));
2470 if (!chr)
2471 goto return_err;
2472 s = qemu_mallocz(sizeof(NetCharDriver));
2473 if (!s)
2474 goto return_err;
2476 fd = socket(PF_INET, SOCK_DGRAM, 0);
2477 if (fd < 0) {
2478 perror("socket(PF_INET, SOCK_DGRAM)");
2479 goto return_err;
2482 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2483 printf("Could not parse: %s\n", def);
2484 goto return_err;
2487 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2489 perror("bind");
2490 goto return_err;
2493 s->fd = fd;
2494 s->bufcnt = 0;
2495 s->bufptr = 0;
2496 chr->opaque = s;
2497 chr->chr_write = udp_chr_write;
2498 chr->chr_update_read_handler = udp_chr_update_read_handler;
2499 return chr;
2501 return_err:
2502 if (chr)
2503 free(chr);
2504 if (s)
2505 free(s);
2506 if (fd >= 0)
2507 closesocket(fd);
2508 return NULL;
2511 /***********************************************************/
2512 /* TCP Net console */
2514 typedef struct {
2515 int fd, listen_fd;
2516 int connected;
2517 int max_size;
2518 int do_telnetopt;
2519 int do_nodelay;
2520 int is_unix;
2521 } TCPCharDriver;
2523 static void tcp_chr_accept(void *opaque);
2525 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2527 TCPCharDriver *s = chr->opaque;
2528 if (s->connected) {
2529 return send_all(s->fd, buf, len);
2530 } else {
2531 /* XXX: indicate an error ? */
2532 return len;
2536 static int tcp_chr_read_poll(void *opaque)
2538 CharDriverState *chr = opaque;
2539 TCPCharDriver *s = chr->opaque;
2540 if (!s->connected)
2541 return 0;
2542 s->max_size = qemu_chr_can_read(chr);
2543 return s->max_size;
2546 #define IAC 255
2547 #define IAC_BREAK 243
2548 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2549 TCPCharDriver *s,
2550 char *buf, int *size)
2552 /* Handle any telnet client's basic IAC options to satisfy char by
2553 * char mode with no echo. All IAC options will be removed from
2554 * the buf and the do_telnetopt variable will be used to track the
2555 * state of the width of the IAC information.
2557 * IAC commands come in sets of 3 bytes with the exception of the
2558 * "IAC BREAK" command and the double IAC.
2559 */
2561 int i;
2562 int j = 0;
2564 for (i = 0; i < *size; i++) {
2565 if (s->do_telnetopt > 1) {
2566 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2567 /* Double IAC means send an IAC */
2568 if (j != i)
2569 buf[j] = buf[i];
2570 j++;
2571 s->do_telnetopt = 1;
2572 } else {
2573 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2574 /* Handle IAC break commands by sending a serial break */
2575 qemu_chr_event(chr, CHR_EVENT_BREAK);
2576 s->do_telnetopt++;
2578 s->do_telnetopt++;
2580 if (s->do_telnetopt >= 4) {
2581 s->do_telnetopt = 1;
2583 } else {
2584 if ((unsigned char)buf[i] == IAC) {
2585 s->do_telnetopt = 2;
2586 } else {
2587 if (j != i)
2588 buf[j] = buf[i];
2589 j++;
2593 *size = j;
2596 static void tcp_chr_read(void *opaque)
2598 CharDriverState *chr = opaque;
2599 TCPCharDriver *s = chr->opaque;
2600 uint8_t buf[1024];
2601 int len, size;
2603 if (!s->connected || s->max_size <= 0)
2604 return;
2605 len = sizeof(buf);
2606 if (len > s->max_size)
2607 len = s->max_size;
2608 size = recv(s->fd, buf, len, 0);
2609 if (size == 0) {
2610 /* connection closed */
2611 s->connected = 0;
2612 if (s->listen_fd >= 0) {
2613 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2615 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2616 closesocket(s->fd);
2617 s->fd = -1;
2618 } else if (size > 0) {
2619 if (s->do_telnetopt)
2620 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2621 if (size > 0)
2622 qemu_chr_read(chr, buf, size);
2626 static void tcp_chr_connect(void *opaque)
2628 CharDriverState *chr = opaque;
2629 TCPCharDriver *s = chr->opaque;
2631 s->connected = 1;
2632 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2633 tcp_chr_read, NULL, chr);
2634 qemu_chr_reset(chr);
2637 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2638 static void tcp_chr_telnet_init(int fd)
2640 char buf[3];
2641 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2642 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2643 send(fd, (char *)buf, 3, 0);
2644 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2645 send(fd, (char *)buf, 3, 0);
2646 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2647 send(fd, (char *)buf, 3, 0);
2648 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2649 send(fd, (char *)buf, 3, 0);
2652 static void socket_set_nodelay(int fd)
2654 int val = 1;
2655 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2658 static void tcp_chr_accept(void *opaque)
2660 CharDriverState *chr = opaque;
2661 TCPCharDriver *s = chr->opaque;
2662 struct sockaddr_in saddr;
2663 #ifndef _WIN32
2664 struct sockaddr_un uaddr;
2665 #endif
2666 struct sockaddr *addr;
2667 socklen_t len;
2668 int fd;
2670 for(;;) {
2671 #ifndef _WIN32
2672 if (s->is_unix) {
2673 len = sizeof(uaddr);
2674 addr = (struct sockaddr *)&uaddr;
2675 } else
2676 #endif
2678 len = sizeof(saddr);
2679 addr = (struct sockaddr *)&saddr;
2681 fd = accept(s->listen_fd, addr, &len);
2682 if (fd < 0 && errno != EINTR) {
2683 return;
2684 } else if (fd >= 0) {
2685 if (s->do_telnetopt)
2686 tcp_chr_telnet_init(fd);
2687 break;
2690 socket_set_nonblock(fd);
2691 if (s->do_nodelay)
2692 socket_set_nodelay(fd);
2693 s->fd = fd;
2694 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2695 tcp_chr_connect(chr);
2698 static void tcp_chr_close(CharDriverState *chr)
2700 TCPCharDriver *s = chr->opaque;
2701 if (s->fd >= 0)
2702 closesocket(s->fd);
2703 if (s->listen_fd >= 0)
2704 closesocket(s->listen_fd);
2705 qemu_free(s);
2708 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2709 int is_telnet,
2710 int is_unix)
2712 CharDriverState *chr = NULL;
2713 TCPCharDriver *s = NULL;
2714 int fd = -1, ret, err, val;
2715 int is_listen = 0;
2716 int is_waitconnect = 1;
2717 int do_nodelay = 0;
2718 const char *ptr;
2719 struct sockaddr_in saddr;
2720 #ifndef _WIN32
2721 struct sockaddr_un uaddr;
2722 #endif
2723 struct sockaddr *addr;
2724 socklen_t addrlen;
2726 #ifndef _WIN32
2727 if (is_unix) {
2728 addr = (struct sockaddr *)&uaddr;
2729 addrlen = sizeof(uaddr);
2730 if (parse_unix_path(&uaddr, host_str) < 0)
2731 goto fail;
2732 } else
2733 #endif
2735 addr = (struct sockaddr *)&saddr;
2736 addrlen = sizeof(saddr);
2737 if (parse_host_port(&saddr, host_str) < 0)
2738 goto fail;
2741 ptr = host_str;
2742 while((ptr = strchr(ptr,','))) {
2743 ptr++;
2744 if (!strncmp(ptr,"server",6)) {
2745 is_listen = 1;
2746 } else if (!strncmp(ptr,"nowait",6)) {
2747 is_waitconnect = 0;
2748 } else if (!strncmp(ptr,"nodelay",6)) {
2749 do_nodelay = 1;
2750 } else {
2751 printf("Unknown option: %s\n", ptr);
2752 goto fail;
2755 if (!is_listen)
2756 is_waitconnect = 0;
2758 chr = qemu_mallocz(sizeof(CharDriverState));
2759 if (!chr)
2760 goto fail;
2761 s = qemu_mallocz(sizeof(TCPCharDriver));
2762 if (!s)
2763 goto fail;
2765 #ifndef _WIN32
2766 if (is_unix)
2767 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2768 else
2769 #endif
2770 fd = socket(PF_INET, SOCK_STREAM, 0);
2772 if (fd < 0)
2773 goto fail;
2775 if (!is_waitconnect)
2776 socket_set_nonblock(fd);
2778 s->connected = 0;
2779 s->fd = -1;
2780 s->listen_fd = -1;
2781 s->is_unix = is_unix;
2782 s->do_nodelay = do_nodelay && !is_unix;
2784 chr->opaque = s;
2785 chr->chr_write = tcp_chr_write;
2786 chr->chr_close = tcp_chr_close;
2788 if (is_listen) {
2789 /* allow fast reuse */
2790 #ifndef _WIN32
2791 if (is_unix) {
2792 char path[109];
2793 strncpy(path, uaddr.sun_path, 108);
2794 path[108] = 0;
2795 unlink(path);
2796 } else
2797 #endif
2799 val = 1;
2800 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2803 ret = bind(fd, addr, addrlen);
2804 if (ret < 0)
2805 goto fail;
2807 ret = listen(fd, 0);
2808 if (ret < 0)
2809 goto fail;
2811 s->listen_fd = fd;
2812 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2813 if (is_telnet)
2814 s->do_telnetopt = 1;
2815 } else {
2816 for(;;) {
2817 ret = connect(fd, addr, addrlen);
2818 if (ret < 0) {
2819 err = socket_error();
2820 if (err == EINTR || err == EWOULDBLOCK) {
2821 } else if (err == EINPROGRESS) {
2822 break;
2823 } else {
2824 goto fail;
2826 } else {
2827 s->connected = 1;
2828 break;
2831 s->fd = fd;
2832 socket_set_nodelay(fd);
2833 if (s->connected)
2834 tcp_chr_connect(chr);
2835 else
2836 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2839 if (is_listen && is_waitconnect) {
2840 printf("QEMU waiting for connection on: %s\n", host_str);
2841 tcp_chr_accept(chr);
2842 socket_set_nonblock(s->listen_fd);
2845 return chr;
2846 fail:
2847 if (fd >= 0)
2848 closesocket(fd);
2849 qemu_free(s);
2850 qemu_free(chr);
2851 return NULL;
2854 CharDriverState *qemu_chr_open(const char *filename)
2856 const char *p;
2858 if (!strcmp(filename, "vc")) {
2859 return text_console_init(&display_state);
2860 } else if (!strcmp(filename, "null")) {
2861 return qemu_chr_open_null();
2862 } else
2863 if (strstart(filename, "tcp:", &p)) {
2864 return qemu_chr_open_tcp(p, 0, 0);
2865 } else
2866 if (strstart(filename, "telnet:", &p)) {
2867 return qemu_chr_open_tcp(p, 1, 0);
2868 } else
2869 if (strstart(filename, "udp:", &p)) {
2870 return qemu_chr_open_udp(p);
2871 } else
2872 #ifndef _WIN32
2873 if (strstart(filename, "unix:", &p)) {
2874 return qemu_chr_open_tcp(p, 0, 1);
2875 } else if (strstart(filename, "file:", &p)) {
2876 return qemu_chr_open_file_out(p);
2877 } else if (strstart(filename, "pipe:", &p)) {
2878 return qemu_chr_open_pipe(p);
2879 } else if (!strcmp(filename, "pty")) {
2880 return qemu_chr_open_pty();
2881 } else if (!strcmp(filename, "stdio")) {
2882 return qemu_chr_open_stdio();
2883 } else
2884 #endif
2885 #if defined(__linux__)
2886 if (strstart(filename, "/dev/parport", NULL)) {
2887 return qemu_chr_open_pp(filename);
2888 } else
2889 if (strstart(filename, "/dev/", NULL)) {
2890 return qemu_chr_open_tty(filename);
2891 } else
2892 #endif
2893 #ifdef _WIN32
2894 if (strstart(filename, "COM", NULL)) {
2895 return qemu_chr_open_win(filename);
2896 } else
2897 if (strstart(filename, "pipe:", &p)) {
2898 return qemu_chr_open_win_pipe(p);
2899 } else
2900 if (strstart(filename, "file:", &p)) {
2901 return qemu_chr_open_win_file_out(p);
2903 #endif
2905 return NULL;
2909 void qemu_chr_close(CharDriverState *chr)
2911 if (chr->chr_close)
2912 chr->chr_close(chr);
2915 /***********************************************************/
2916 /* network device redirectors */
2918 void hex_dump(FILE *f, const uint8_t *buf, int size)
2920 int len, i, j, c;
2922 for(i=0;i<size;i+=16) {
2923 len = size - i;
2924 if (len > 16)
2925 len = 16;
2926 fprintf(f, "%08x ", i);
2927 for(j=0;j<16;j++) {
2928 if (j < len)
2929 fprintf(f, " %02x", buf[i+j]);
2930 else
2931 fprintf(f, " ");
2933 fprintf(f, " ");
2934 for(j=0;j<len;j++) {
2935 c = buf[i+j];
2936 if (c < ' ' || c > '~')
2937 c = '.';
2938 fprintf(f, "%c", c);
2940 fprintf(f, "\n");
2944 static int parse_macaddr(uint8_t *macaddr, const char *p)
2946 int i;
2947 for(i = 0; i < 6; i++) {
2948 macaddr[i] = strtol(p, (char **)&p, 16);
2949 if (i == 5) {
2950 if (*p != '\0')
2951 return -1;
2952 } else {
2953 if (*p != ':')
2954 return -1;
2955 p++;
2958 return 0;
2961 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2963 const char *p, *p1;
2964 int len;
2965 p = *pp;
2966 p1 = strchr(p, sep);
2967 if (!p1)
2968 return -1;
2969 len = p1 - p;
2970 p1++;
2971 if (buf_size > 0) {
2972 if (len > buf_size - 1)
2973 len = buf_size - 1;
2974 memcpy(buf, p, len);
2975 buf[len] = '\0';
2977 *pp = p1;
2978 return 0;
2981 int parse_host_src_port(struct sockaddr_in *haddr,
2982 struct sockaddr_in *saddr,
2983 const char *input_str)
2985 char *str = strdup(input_str);
2986 char *host_str = str;
2987 char *src_str;
2988 char *ptr;
2990 /*
2991 * Chop off any extra arguments at the end of the string which
2992 * would start with a comma, then fill in the src port information
2993 * if it was provided else use the "any address" and "any port".
2994 */
2995 if ((ptr = strchr(str,',')))
2996 *ptr = '\0';
2998 if ((src_str = strchr(input_str,'@'))) {
2999 *src_str = '\0';
3000 src_str++;
3003 if (parse_host_port(haddr, host_str) < 0)
3004 goto fail;
3006 if (!src_str || *src_str == '\0')
3007 src_str = ":0";
3009 if (parse_host_port(saddr, src_str) < 0)
3010 goto fail;
3012 free(str);
3013 return(0);
3015 fail:
3016 free(str);
3017 return -1;
3020 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3022 char buf[512];
3023 struct hostent *he;
3024 const char *p, *r;
3025 int port;
3027 p = str;
3028 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3029 return -1;
3030 saddr->sin_family = AF_INET;
3031 if (buf[0] == '\0') {
3032 saddr->sin_addr.s_addr = 0;
3033 } else {
3034 if (isdigit(buf[0])) {
3035 if (!inet_aton(buf, &saddr->sin_addr))
3036 return -1;
3037 } else {
3038 if ((he = gethostbyname(buf)) == NULL)
3039 return - 1;
3040 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3043 port = strtol(p, (char **)&r, 0);
3044 if (r == p)
3045 return -1;
3046 saddr->sin_port = htons(port);
3047 return 0;
3050 #ifndef _WIN32
3051 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3053 const char *p;
3054 int len;
3056 len = MIN(108, strlen(str));
3057 p = strchr(str, ',');
3058 if (p)
3059 len = MIN(len, p - str);
3061 memset(uaddr, 0, sizeof(*uaddr));
3063 uaddr->sun_family = AF_UNIX;
3064 memcpy(uaddr->sun_path, str, len);
3066 return 0;
3068 #endif
3070 /* find or alloc a new VLAN */
3071 VLANState *qemu_find_vlan(int id)
3073 VLANState **pvlan, *vlan;
3074 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3075 if (vlan->id == id)
3076 return vlan;
3078 vlan = qemu_mallocz(sizeof(VLANState));
3079 if (!vlan)
3080 return NULL;
3081 vlan->id = id;
3082 vlan->next = NULL;
3083 pvlan = &first_vlan;
3084 while (*pvlan != NULL)
3085 pvlan = &(*pvlan)->next;
3086 *pvlan = vlan;
3087 return vlan;
3090 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3091 IOReadHandler *fd_read,
3092 IOCanRWHandler *fd_can_read,
3093 void *opaque)
3095 VLANClientState *vc, **pvc;
3096 vc = qemu_mallocz(sizeof(VLANClientState));
3097 if (!vc)
3098 return NULL;
3099 vc->fd_read = fd_read;
3100 vc->fd_can_read = fd_can_read;
3101 vc->opaque = opaque;
3102 vc->vlan = vlan;
3104 vc->next = NULL;
3105 pvc = &vlan->first_client;
3106 while (*pvc != NULL)
3107 pvc = &(*pvc)->next;
3108 *pvc = vc;
3109 return vc;
3112 int qemu_can_send_packet(VLANClientState *vc1)
3114 VLANState *vlan = vc1->vlan;
3115 VLANClientState *vc;
3117 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3118 if (vc != vc1) {
3119 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3120 return 0;
3123 return 1;
3126 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3128 VLANState *vlan = vc1->vlan;
3129 VLANClientState *vc;
3131 #if 0
3132 printf("vlan %d send:\n", vlan->id);
3133 hex_dump(stdout, buf, size);
3134 #endif
3135 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3136 if (vc != vc1) {
3137 vc->fd_read(vc->opaque, buf, size);
3142 #if defined(CONFIG_SLIRP)
3144 /* slirp network adapter */
3146 static int slirp_inited;
3147 static VLANClientState *slirp_vc;
3149 int slirp_can_output(void)
3151 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3154 void slirp_output(const uint8_t *pkt, int pkt_len)
3156 #if 0
3157 printf("slirp output:\n");
3158 hex_dump(stdout, pkt, pkt_len);
3159 #endif
3160 if (!slirp_vc)
3161 return;
3162 qemu_send_packet(slirp_vc, pkt, pkt_len);
3165 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3167 #if 0
3168 printf("slirp input:\n");
3169 hex_dump(stdout, buf, size);
3170 #endif
3171 slirp_input(buf, size);
3174 static int net_slirp_init(VLANState *vlan)
3176 if (!slirp_inited) {
3177 slirp_inited = 1;
3178 slirp_init();
3180 slirp_vc = qemu_new_vlan_client(vlan,
3181 slirp_receive, NULL, NULL);
3182 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3183 return 0;
3186 static void net_slirp_redir(const char *redir_str)
3188 int is_udp;
3189 char buf[256], *r;
3190 const char *p;
3191 struct in_addr guest_addr;
3192 int host_port, guest_port;
3194 if (!slirp_inited) {
3195 slirp_inited = 1;
3196 slirp_init();
3199 p = redir_str;
3200 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3201 goto fail;
3202 if (!strcmp(buf, "tcp")) {
3203 is_udp = 0;
3204 } else if (!strcmp(buf, "udp")) {
3205 is_udp = 1;
3206 } else {
3207 goto fail;
3210 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3211 goto fail;
3212 host_port = strtol(buf, &r, 0);
3213 if (r == buf)
3214 goto fail;
3216 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3217 goto fail;
3218 if (buf[0] == '\0') {
3219 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3221 if (!inet_aton(buf, &guest_addr))
3222 goto fail;
3224 guest_port = strtol(p, &r, 0);
3225 if (r == p)
3226 goto fail;
3228 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3229 fprintf(stderr, "qemu: could not set up redirection\n");
3230 exit(1);
3232 return;
3233 fail:
3234 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3235 exit(1);
3238 #ifndef _WIN32
3240 char smb_dir[1024];
3242 static void smb_exit(void)
3244 DIR *d;
3245 struct dirent *de;
3246 char filename[1024];
3248 /* erase all the files in the directory */
3249 d = opendir(smb_dir);
3250 for(;;) {
3251 de = readdir(d);
3252 if (!de)
3253 break;
3254 if (strcmp(de->d_name, ".") != 0 &&
3255 strcmp(de->d_name, "..") != 0) {
3256 snprintf(filename, sizeof(filename), "%s/%s",
3257 smb_dir, de->d_name);
3258 unlink(filename);
3261 closedir(d);
3262 rmdir(smb_dir);
3265 /* automatic user mode samba server configuration */
3266 void net_slirp_smb(const char *exported_dir)
3268 char smb_conf[1024];
3269 char smb_cmdline[1024];
3270 FILE *f;
3272 if (!slirp_inited) {
3273 slirp_inited = 1;
3274 slirp_init();
3277 /* XXX: better tmp dir construction */
3278 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3279 if (mkdir(smb_dir, 0700) < 0) {
3280 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3281 exit(1);
3283 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3285 f = fopen(smb_conf, "w");
3286 if (!f) {
3287 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3288 exit(1);
3290 fprintf(f,
3291 "[global]\n"
3292 "private dir=%s\n"
3293 "smb ports=0\n"
3294 "socket address=127.0.0.1\n"
3295 "pid directory=%s\n"
3296 "lock directory=%s\n"
3297 "log file=%s/log.smbd\n"
3298 "smb passwd file=%s/smbpasswd\n"
3299 "security = share\n"
3300 "[qemu]\n"
3301 "path=%s\n"
3302 "read only=no\n"
3303 "guest ok=yes\n",
3304 smb_dir,
3305 smb_dir,
3306 smb_dir,
3307 smb_dir,
3308 smb_dir,
3309 exported_dir
3310 );
3311 fclose(f);
3312 atexit(smb_exit);
3314 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3315 SMBD_COMMAND, smb_conf);
3317 slirp_add_exec(0, smb_cmdline, 4, 139);
3320 #endif /* !defined(_WIN32) */
3322 #endif /* CONFIG_SLIRP */
3324 #if !defined(_WIN32)
3326 typedef struct TAPState {
3327 VLANClientState *vc;
3328 int fd;
3329 } TAPState;
3331 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3333 TAPState *s = opaque;
3334 int ret;
3335 for(;;) {
3336 ret = write(s->fd, buf, size);
3337 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3338 } else {
3339 break;
3344 static void tap_send(void *opaque)
3346 TAPState *s = opaque;
3347 uint8_t buf[4096];
3348 int size;
3350 size = read(s->fd, buf, sizeof(buf));
3351 if (size > 0) {
3352 qemu_send_packet(s->vc, buf, size);
3356 /* fd support */
3358 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3360 TAPState *s;
3362 s = qemu_mallocz(sizeof(TAPState));
3363 if (!s)
3364 return NULL;
3365 s->fd = fd;
3366 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3367 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3368 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3369 return s;
3372 #ifdef _BSD
3373 static int tap_open(char *ifname, int ifname_size)
3375 int fd;
3376 char *dev;
3377 struct stat s;
3379 fd = open("/dev/tap", O_RDWR);
3380 if (fd < 0) {
3381 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3382 return -1;
3385 fstat(fd, &s);
3386 dev = devname(s.st_rdev, S_IFCHR);
3387 pstrcpy(ifname, ifname_size, dev);
3389 fcntl(fd, F_SETFL, O_NONBLOCK);
3390 return fd;
3392 #elif defined(__sun__)
3393 static int tap_open(char *ifname, int ifname_size)
3395 fprintf(stderr, "warning: tap_open not yet implemented\n");
3396 return -1;
3398 #else
3399 static int tap_open(char *ifname, int ifname_size)
3401 struct ifreq ifr;
3402 int fd, ret, retries = 0;
3404 fd = open("/dev/net/tun", O_RDWR);
3405 if (fd < 0) {
3406 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3407 return -1;
3409 memset(&ifr, 0, sizeof(ifr));
3410 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3411 if (ifname[0] != '\0')
3412 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3413 else
3414 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3415 do {
3416 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3417 } while ((ret != 0) && (retries++ < 3));
3418 if (ret != 0) {
3419 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3420 close(fd);
3421 return -1;
3423 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3424 fcntl(fd, F_SETFL, O_NONBLOCK);
3425 return fd;
3427 #endif
3429 static int net_tap_init(VLANState *vlan, const char *ifname1,
3430 const char *setup_script, const char *bridge)
3432 TAPState *s;
3433 int pid, status, fd;
3434 char *args[4];
3435 char **parg;
3436 char ifname[128];
3438 if (ifname1 != NULL)
3439 pstrcpy(ifname, sizeof(ifname), ifname1);
3440 else
3441 ifname[0] = '\0';
3442 fd = tap_open(ifname, sizeof(ifname));
3443 if (fd < 0)
3444 return -1;
3446 if (!setup_script || !strcmp(setup_script, "no"))
3447 setup_script = "";
3448 if (setup_script[0] != '\0') {
3449 /* try to launch network init script */
3450 pid = fork();
3451 if (pid >= 0) {
3452 if (pid == 0) {
3453 int open_max = sysconf(_SC_OPEN_MAX), i;
3454 for (i = 0; i < open_max; i++)
3455 if (i != STDIN_FILENO &&
3456 i != STDOUT_FILENO &&
3457 i != STDERR_FILENO &&
3458 i != fd)
3459 close(i);
3461 parg = args;
3462 *parg++ = (char *)setup_script;
3463 *parg++ = ifname;
3464 *parg++ = (char *)bridge;
3465 *parg++ = NULL;
3466 execv(setup_script, args);
3467 _exit(1);
3469 while (waitpid(pid, &status, 0) != pid);
3470 if (!WIFEXITED(status) ||
3471 WEXITSTATUS(status) != 0) {
3472 fprintf(stderr, "%s: could not launch network script\n",
3473 setup_script);
3474 return -1;
3478 s = net_tap_fd_init(vlan, fd);
3479 if (!s)
3480 return -1;
3481 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3482 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3483 return 0;
3486 #endif /* !_WIN32 */
3488 /* network connection */
3489 typedef struct NetSocketState {
3490 VLANClientState *vc;
3491 int fd;
3492 int state; /* 0 = getting length, 1 = getting data */
3493 int index;
3494 int packet_len;
3495 uint8_t buf[4096];
3496 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3497 } NetSocketState;
3499 typedef struct NetSocketListenState {
3500 VLANState *vlan;
3501 int fd;
3502 } NetSocketListenState;
3504 /* XXX: we consider we can send the whole packet without blocking */
3505 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3507 NetSocketState *s = opaque;
3508 uint32_t len;
3509 len = htonl(size);
3511 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3512 send_all(s->fd, buf, size);
3515 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3517 NetSocketState *s = opaque;
3518 sendto(s->fd, buf, size, 0,
3519 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3522 static void net_socket_send(void *opaque)
3524 NetSocketState *s = opaque;
3525 int l, size, err;
3526 uint8_t buf1[4096];
3527 const uint8_t *buf;
3529 size = recv(s->fd, buf1, sizeof(buf1), 0);
3530 if (size < 0) {
3531 err = socket_error();
3532 if (err != EWOULDBLOCK)
3533 goto eoc;
3534 } else if (size == 0) {
3535 /* end of connection */
3536 eoc:
3537 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3538 closesocket(s->fd);
3539 return;
3541 buf = buf1;
3542 while (size > 0) {
3543 /* reassemble a packet from the network */
3544 switch(s->state) {
3545 case 0:
3546 l = 4 - s->index;
3547 if (l > size)
3548 l = size;
3549 memcpy(s->buf + s->index, buf, l);
3550 buf += l;
3551 size -= l;
3552 s->index += l;
3553 if (s->index == 4) {
3554 /* got length */
3555 s->packet_len = ntohl(*(uint32_t *)s->buf);
3556 s->index = 0;
3557 s->state = 1;
3559 break;
3560 case 1:
3561 l = s->packet_len - s->index;
3562 if (l > size)
3563 l = size;
3564 memcpy(s->buf + s->index, buf, l);
3565 s->index += l;
3566 buf += l;
3567 size -= l;
3568 if (s->index >= s->packet_len) {
3569 qemu_send_packet(s->vc, s->buf, s->packet_len);
3570 s->index = 0;
3571 s->state = 0;
3573 break;
3578 static void net_socket_send_dgram(void *opaque)
3580 NetSocketState *s = opaque;
3581 int size;
3583 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3584 if (size < 0)
3585 return;
3586 if (size == 0) {
3587 /* end of connection */
3588 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3589 return;
3591 qemu_send_packet(s->vc, s->buf, size);
3594 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3596 struct ip_mreq imr;
3597 int fd;
3598 int val, ret;
3599 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3600 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3601 inet_ntoa(mcastaddr->sin_addr),
3602 (int)ntohl(mcastaddr->sin_addr.s_addr));
3603 return -1;
3606 fd = socket(PF_INET, SOCK_DGRAM, 0);
3607 if (fd < 0) {
3608 perror("socket(PF_INET, SOCK_DGRAM)");
3609 return -1;
3612 val = 1;
3613 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3614 (const char *)&val, sizeof(val));
3615 if (ret < 0) {
3616 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3617 goto fail;
3620 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3621 if (ret < 0) {
3622 perror("bind");
3623 goto fail;
3626 /* Add host to multicast group */
3627 imr.imr_multiaddr = mcastaddr->sin_addr;
3628 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3630 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3631 (const char *)&imr, sizeof(struct ip_mreq));
3632 if (ret < 0) {
3633 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3634 goto fail;
3637 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3638 val = 1;
3639 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3640 (const char *)&val, sizeof(val));
3641 if (ret < 0) {
3642 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3643 goto fail;
3646 socket_set_nonblock(fd);
3647 return fd;
3648 fail:
3649 if (fd >= 0)
3650 closesocket(fd);
3651 return -1;
3654 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3655 int is_connected)
3657 struct sockaddr_in saddr;
3658 int newfd;
3659 socklen_t saddr_len;
3660 NetSocketState *s;
3662 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3663 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3664 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3665 */
3667 if (is_connected) {
3668 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3669 /* must be bound */
3670 if (saddr.sin_addr.s_addr==0) {
3671 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3672 fd);
3673 return NULL;
3675 /* clone dgram socket */
3676 newfd = net_socket_mcast_create(&saddr);
3677 if (newfd < 0) {
3678 /* error already reported by net_socket_mcast_create() */
3679 close(fd);
3680 return NULL;
3682 /* clone newfd to fd, close newfd */
3683 dup2(newfd, fd);
3684 close(newfd);
3686 } else {
3687 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3688 fd, strerror(errno));
3689 return NULL;
3693 s = qemu_mallocz(sizeof(NetSocketState));
3694 if (!s)
3695 return NULL;
3696 s->fd = fd;
3698 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3699 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3701 /* mcast: save bound address as dst */
3702 if (is_connected) s->dgram_dst=saddr;
3704 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3705 "socket: fd=%d (%s mcast=%s:%d)",
3706 fd, is_connected? "cloned" : "",
3707 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3708 return s;
3711 static void net_socket_connect(void *opaque)
3713 NetSocketState *s = opaque;
3714 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3717 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3718 int is_connected)
3720 NetSocketState *s;
3721 s = qemu_mallocz(sizeof(NetSocketState));
3722 if (!s)
3723 return NULL;
3724 s->fd = fd;
3725 s->vc = qemu_new_vlan_client(vlan,
3726 net_socket_receive, NULL, s);
3727 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3728 "socket: fd=%d", fd);
3729 if (is_connected) {
3730 net_socket_connect(s);
3731 } else {
3732 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3734 return s;
3737 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3738 int is_connected)
3740 int so_type=-1, optlen=sizeof(so_type);
3742 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3743 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3744 return NULL;
3746 switch(so_type) {
3747 case SOCK_DGRAM:
3748 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3749 case SOCK_STREAM:
3750 return net_socket_fd_init_stream(vlan, fd, is_connected);
3751 default:
3752 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3753 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3754 return net_socket_fd_init_stream(vlan, fd, is_connected);
3756 return NULL;
3759 static void net_socket_accept(void *opaque)
3761 NetSocketListenState *s = opaque;
3762 NetSocketState *s1;
3763 struct sockaddr_in saddr;
3764 socklen_t len;
3765 int fd;
3767 for(;;) {
3768 len = sizeof(saddr);
3769 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3770 if (fd < 0 && errno != EINTR) {
3771 return;
3772 } else if (fd >= 0) {
3773 break;
3776 s1 = net_socket_fd_init(s->vlan, fd, 1);
3777 if (!s1) {
3778 closesocket(fd);
3779 } else {
3780 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3781 "socket: connection from %s:%d",
3782 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3786 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3788 NetSocketListenState *s;
3789 int fd, val, ret;
3790 struct sockaddr_in saddr;
3792 if (parse_host_port(&saddr, host_str) < 0)
3793 return -1;
3795 s = qemu_mallocz(sizeof(NetSocketListenState));
3796 if (!s)
3797 return -1;
3799 fd = socket(PF_INET, SOCK_STREAM, 0);
3800 if (fd < 0) {
3801 perror("socket");
3802 return -1;
3804 socket_set_nonblock(fd);
3806 /* allow fast reuse */
3807 val = 1;
3808 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3810 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3811 if (ret < 0) {
3812 perror("bind");
3813 return -1;
3815 ret = listen(fd, 0);
3816 if (ret < 0) {
3817 perror("listen");
3818 return -1;
3820 s->vlan = vlan;
3821 s->fd = fd;
3822 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3823 return 0;
3826 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3828 NetSocketState *s;
3829 int fd, connected, ret, err;
3830 struct sockaddr_in saddr;
3832 if (parse_host_port(&saddr, host_str) < 0)
3833 return -1;
3835 fd = socket(PF_INET, SOCK_STREAM, 0);
3836 if (fd < 0) {
3837 perror("socket");
3838 return -1;
3840 socket_set_nonblock(fd);
3842 connected = 0;
3843 for(;;) {
3844 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3845 if (ret < 0) {
3846 err = socket_error();
3847 if (err == EINTR || err == EWOULDBLOCK) {
3848 } else if (err == EINPROGRESS) {
3849 break;
3850 } else {
3851 perror("connect");
3852 closesocket(fd);
3853 return -1;
3855 } else {
3856 connected = 1;
3857 break;
3860 s = net_socket_fd_init(vlan, fd, connected);
3861 if (!s)
3862 return -1;
3863 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3864 "socket: connect to %s:%d",
3865 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3866 return 0;
3869 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3871 NetSocketState *s;
3872 int fd;
3873 struct sockaddr_in saddr;
3875 if (parse_host_port(&saddr, host_str) < 0)
3876 return -1;
3879 fd = net_socket_mcast_create(&saddr);
3880 if (fd < 0)
3881 return -1;
3883 s = net_socket_fd_init(vlan, fd, 0);
3884 if (!s)
3885 return -1;
3887 s->dgram_dst = saddr;
3889 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3890 "socket: mcast=%s:%d",
3891 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3892 return 0;
3896 static int get_param_value(char *buf, int buf_size,
3897 const char *tag, const char *str)
3899 const char *p;
3900 char *q;
3901 char option[128];
3903 p = str;
3904 for(;;) {
3905 q = option;
3906 while (*p != '\0' && *p != '=') {
3907 if ((q - option) < sizeof(option) - 1)
3908 *q++ = *p;
3909 p++;
3911 *q = '\0';
3912 if (*p != '=')
3913 break;
3914 p++;
3915 if (!strcmp(tag, option)) {
3916 q = buf;
3917 while (*p != '\0' && *p != ',') {
3918 if ((q - buf) < buf_size - 1)
3919 *q++ = *p;
3920 p++;
3922 *q = '\0';
3923 return q - buf;
3924 } else {
3925 while (*p != '\0' && *p != ',') {
3926 p++;
3929 if (*p != ',')
3930 break;
3931 p++;
3933 return 0;
3936 static int net_client_init(const char *str)
3938 const char *p;
3939 char *q;
3940 char device[64];
3941 char buf[1024];
3942 int vlan_id, ret;
3943 VLANState *vlan;
3945 p = str;
3946 q = device;
3947 while (*p != '\0' && *p != ',') {
3948 if ((q - device) < sizeof(device) - 1)
3949 *q++ = *p;
3950 p++;
3952 *q = '\0';
3953 if (*p == ',')
3954 p++;
3955 vlan_id = 0;
3956 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3957 vlan_id = strtol(buf, NULL, 0);
3959 vlan = qemu_find_vlan(vlan_id);
3960 if (!vlan) {
3961 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3962 return -1;
3964 if (!strcmp(device, "nic")) {
3965 NICInfo *nd;
3966 uint8_t *macaddr;
3968 if (nb_nics < MAX_NICS) {
3969 nd = &nd_table[nb_nics];
3970 macaddr = nd->macaddr;
3971 macaddr[0] = 0x52;
3972 macaddr[1] = 0x54;
3973 macaddr[2] = 0x00;
3974 macaddr[3] = 0x12;
3975 macaddr[4] = 0x34;
3976 macaddr[5] = 0x56 + nb_nics;
3978 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3979 if (parse_macaddr(macaddr, buf) < 0) {
3980 fprintf(stderr, "invalid syntax for ethernet address\n");
3981 return -1;
3984 if (get_param_value(buf, sizeof(buf), "model", p)) {
3985 nd->model = strdup(buf);
3987 nd->vlan = vlan;
3988 nb_nics++;
3989 } else {
3990 fprintf(stderr, "Too Many NICs\n");
3992 ret = 0;
3993 } else
3994 if (!strcmp(device, "none")) {
3995 /* does nothing. It is needed to signal that no network cards
3996 are wanted */
3997 ret = 0;
3998 } else
3999 #ifdef CONFIG_SLIRP
4000 if (!strcmp(device, "user")) {
4001 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4002 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4004 ret = net_slirp_init(vlan);
4005 } else
4006 #endif
4007 #ifdef _WIN32
4008 if (!strcmp(device, "tap")) {
4009 char ifname[64];
4010 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4011 fprintf(stderr, "tap: no interface name\n");
4012 return -1;
4014 ret = tap_win32_init(vlan, ifname);
4015 } else
4016 #else
4017 if (!strcmp(device, "tap")) {
4018 char ifname[64];
4019 char setup_script[1024];
4020 char bridge[16];
4021 int fd;
4022 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4023 fd = strtol(buf, NULL, 0);
4024 ret = -1;
4025 if (net_tap_fd_init(vlan, fd))
4026 ret = 0;
4027 } else {
4028 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4029 ifname[0] = '\0';
4031 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4032 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4034 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4035 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4037 ret = net_tap_init(vlan, ifname, setup_script, bridge);
4039 } else
4040 #endif
4041 if (!strcmp(device, "socket")) {
4042 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4043 int fd;
4044 fd = strtol(buf, NULL, 0);
4045 ret = -1;
4046 if (net_socket_fd_init(vlan, fd, 1))
4047 ret = 0;
4048 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4049 ret = net_socket_listen_init(vlan, buf);
4050 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4051 ret = net_socket_connect_init(vlan, buf);
4052 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4053 ret = net_socket_mcast_init(vlan, buf);
4054 } else {
4055 fprintf(stderr, "Unknown socket options: %s\n", p);
4056 return -1;
4058 } else
4060 fprintf(stderr, "Unknown network device: %s\n", device);
4061 return -1;
4063 if (ret < 0) {
4064 fprintf(stderr, "Could not initialize device '%s'\n", device);
4067 return ret;
4070 void do_info_network(void)
4072 VLANState *vlan;
4073 VLANClientState *vc;
4075 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4076 term_printf("VLAN %d devices:\n", vlan->id);
4077 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4078 term_printf(" %s\n", vc->info_str);
4082 /***********************************************************/
4083 /* USB devices */
4085 static USBPort *used_usb_ports;
4086 static USBPort *free_usb_ports;
4088 /* ??? Maybe change this to register a hub to keep track of the topology. */
4089 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4090 usb_attachfn attach)
4092 port->opaque = opaque;
4093 port->index = index;
4094 port->attach = attach;
4095 port->next = free_usb_ports;
4096 free_usb_ports = port;
4099 static int usb_device_add(const char *devname)
4101 const char *p;
4102 USBDevice *dev;
4103 USBPort *port;
4104 char usb_name[256] = "USB ";
4106 if (!free_usb_ports)
4107 return -1;
4109 if (strstart(devname, "host:", &p)) {
4110 dev = usb_host_device_open(p);
4111 } else if (!strcmp(devname, "mouse")) {
4112 dev = usb_mouse_init();
4113 } else if (!strcmp(devname, "tablet")) {
4114 dev = usb_tablet_init();
4115 } else if (strstart(devname, "disk:", &p)) {
4116 dev = usb_msd_init(p);
4117 } else {
4118 return -1;
4120 if (!dev)
4121 return -1;
4123 /* Find a USB port to add the device to. */
4124 port = free_usb_ports;
4125 if (!port->next) {
4126 USBDevice *hub;
4128 /* Create a new hub and chain it on. */
4129 free_usb_ports = NULL;
4130 port->next = used_usb_ports;
4131 used_usb_ports = port;
4133 hub = usb_hub_init(VM_USB_HUB_SIZE);
4134 usb_attach(port, hub);
4135 port = free_usb_ports;
4138 free_usb_ports = port->next;
4139 port->next = used_usb_ports;
4140 used_usb_ports = port;
4142 pstrcpy(usb_name + strlen(usb_name),
4143 sizeof(usb_name) - strlen(usb_name),
4144 devname);
4145 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4147 usb_attach(port, dev);
4148 return 0;
4151 static int usb_device_del(const char *devname)
4153 USBPort *port;
4154 USBPort **lastp;
4155 USBDevice *dev;
4156 int bus_num, addr;
4157 const char *p;
4159 if (!used_usb_ports)
4160 return -1;
4162 p = strchr(devname, '.');
4163 if (!p)
4164 return -1;
4165 bus_num = strtoul(devname, NULL, 0);
4166 addr = strtoul(p + 1, NULL, 0);
4167 if (bus_num != 0)
4168 return -1;
4170 lastp = &used_usb_ports;
4171 port = used_usb_ports;
4172 while (port && port->dev->addr != addr) {
4173 lastp = &port->next;
4174 port = port->next;
4177 if (!port)
4178 return -1;
4180 dev = port->dev;
4181 *lastp = port->next;
4182 usb_attach(port, NULL);
4183 dev->handle_destroy(dev);
4184 port->next = free_usb_ports;
4185 free_usb_ports = port;
4186 return 0;
4189 void do_usb_add(const char *devname)
4191 int ret;
4192 ret = usb_device_add(devname);
4193 if (ret < 0)
4194 term_printf("Could not add USB device '%s'\n", devname);
4197 void do_usb_del(const char *devname)
4199 int ret;
4200 ret = usb_device_del(devname);
4201 if (ret < 0)
4202 term_printf("Could not remove USB device '%s'\n", devname);
4205 void usb_info(void)
4207 USBDevice *dev;
4208 USBPort *port;
4209 const char *speed_str;
4211 if (!usb_enabled) {
4212 term_printf("USB support not enabled\n");
4213 return;
4216 for (port = used_usb_ports; port; port = port->next) {
4217 dev = port->dev;
4218 if (!dev)
4219 continue;
4220 switch(dev->speed) {
4221 case USB_SPEED_LOW:
4222 speed_str = "1.5";
4223 break;
4224 case USB_SPEED_FULL:
4225 speed_str = "12";
4226 break;
4227 case USB_SPEED_HIGH:
4228 speed_str = "480";
4229 break;
4230 default:
4231 speed_str = "?";
4232 break;
4234 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4235 0, dev->addr, speed_str, dev->devname);
4239 /***********************************************************/
4240 /* pid file */
4242 static char *pid_filename;
4244 /* Remove PID file. Called on normal exit */
4246 static void remove_pidfile(void)
4248 unlink (pid_filename);
4251 static void create_pidfile(const char *filename)
4253 struct stat pidstat;
4254 FILE *f;
4256 /* Try to write our PID to the named file */
4257 if (stat(filename, &pidstat) < 0) {
4258 if (errno == ENOENT) {
4259 if ((f = fopen (filename, "w")) == NULL) {
4260 perror("Opening pidfile");
4261 exit(1);
4263 fprintf(f, "%ld\n", (long)getpid());
4264 fclose(f);
4265 pid_filename = qemu_strdup(filename);
4266 if (!pid_filename) {
4267 fprintf(stderr, "Could not save PID filename");
4268 exit(1);
4270 atexit(remove_pidfile);
4272 } else {
4273 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4274 filename);
4275 exit(1);
4279 /***********************************************************/
4280 /* dumb display */
4282 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4286 static void dumb_resize(DisplayState *ds, int w, int h)
4290 static void dumb_refresh(DisplayState *ds)
4292 vga_hw_update();
4295 void dumb_display_init(DisplayState *ds)
4297 ds->data = NULL;
4298 ds->linesize = 0;
4299 ds->depth = 0;
4300 ds->dpy_update = dumb_update;
4301 ds->dpy_resize = dumb_resize;
4302 ds->dpy_refresh = dumb_refresh;
4305 /***********************************************************/
4306 /* I/O handling */
4308 #define MAX_IO_HANDLERS 64
4310 typedef struct IOHandlerRecord {
4311 int fd;
4312 IOCanRWHandler *fd_read_poll;
4313 IOHandler *fd_read;
4314 IOHandler *fd_write;
4315 void *opaque;
4316 /* temporary data */
4317 struct pollfd *ufd;
4318 struct IOHandlerRecord *next;
4319 } IOHandlerRecord;
4321 static IOHandlerRecord *first_io_handler;
4323 /* XXX: fd_read_poll should be suppressed, but an API change is
4324 necessary in the character devices to suppress fd_can_read(). */
4325 int qemu_set_fd_handler2(int fd,
4326 IOCanRWHandler *fd_read_poll,
4327 IOHandler *fd_read,
4328 IOHandler *fd_write,
4329 void *opaque)
4331 IOHandlerRecord **pioh, *ioh;
4333 if (!fd_read && !fd_write) {
4334 pioh = &first_io_handler;
4335 for(;;) {
4336 ioh = *pioh;
4337 if (ioh == NULL)
4338 break;
4339 if (ioh->fd == fd) {
4340 *pioh = ioh->next;
4341 qemu_free(ioh);
4342 break;
4344 pioh = &ioh->next;
4346 } else {
4347 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4348 if (ioh->fd == fd)
4349 goto found;
4351 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4352 if (!ioh)
4353 return -1;
4354 ioh->next = first_io_handler;
4355 first_io_handler = ioh;
4356 found:
4357 ioh->fd = fd;
4358 ioh->fd_read_poll = fd_read_poll;
4359 ioh->fd_read = fd_read;
4360 ioh->fd_write = fd_write;
4361 ioh->opaque = opaque;
4363 return 0;
4366 int qemu_set_fd_handler(int fd,
4367 IOHandler *fd_read,
4368 IOHandler *fd_write,
4369 void *opaque)
4371 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4374 /***********************************************************/
4375 /* Polling handling */
4377 typedef struct PollingEntry {
4378 PollingFunc *func;
4379 void *opaque;
4380 struct PollingEntry *next;
4381 } PollingEntry;
4383 static PollingEntry *first_polling_entry;
4385 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4387 PollingEntry **ppe, *pe;
4388 pe = qemu_mallocz(sizeof(PollingEntry));
4389 if (!pe)
4390 return -1;
4391 pe->func = func;
4392 pe->opaque = opaque;
4393 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4394 *ppe = pe;
4395 return 0;
4398 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4400 PollingEntry **ppe, *pe;
4401 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4402 pe = *ppe;
4403 if (pe->func == func && pe->opaque == opaque) {
4404 *ppe = pe->next;
4405 qemu_free(pe);
4406 break;
4411 #ifdef _WIN32
4412 /***********************************************************/
4413 /* Wait objects support */
4414 typedef struct WaitObjects {
4415 int num;
4416 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4417 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4418 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4419 } WaitObjects;
4421 static WaitObjects wait_objects = {0};
4423 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4425 WaitObjects *w = &wait_objects;
4427 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4428 return -1;
4429 w->events[w->num] = handle;
4430 w->func[w->num] = func;
4431 w->opaque[w->num] = opaque;
4432 w->num++;
4433 return 0;
4436 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4438 int i, found;
4439 WaitObjects *w = &wait_objects;
4441 found = 0;
4442 for (i = 0; i < w->num; i++) {
4443 if (w->events[i] == handle)
4444 found = 1;
4445 if (found) {
4446 w->events[i] = w->events[i + 1];
4447 w->func[i] = w->func[i + 1];
4448 w->opaque[i] = w->opaque[i + 1];
4451 if (found)
4452 w->num--;
4454 #endif
4456 /***********************************************************/
4457 /* savevm/loadvm support */
4459 #define IO_BUF_SIZE 32768
4461 struct QEMUFile {
4462 FILE *outfile;
4463 BlockDriverState *bs;
4464 int is_file;
4465 int is_writable;
4466 int64_t base_offset;
4467 int64_t buf_offset; /* start of buffer when writing, end of buffer
4468 when reading */
4469 int buf_index;
4470 int buf_size; /* 0 when writing */
4471 uint8_t buf[IO_BUF_SIZE];
4472 };
4474 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4476 QEMUFile *f;
4478 f = qemu_mallocz(sizeof(QEMUFile));
4479 if (!f)
4480 return NULL;
4481 if (!strcmp(mode, "wb")) {
4482 f->is_writable = 1;
4483 } else if (!strcmp(mode, "rb")) {
4484 f->is_writable = 0;
4485 } else {
4486 goto fail;
4488 f->outfile = fopen(filename, mode);
4489 if (!f->outfile)
4490 goto fail;
4491 f->is_file = 1;
4492 return f;
4493 fail:
4494 if (f->outfile)
4495 fclose(f->outfile);
4496 qemu_free(f);
4497 return NULL;
4500 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4502 QEMUFile *f;
4504 f = qemu_mallocz(sizeof(QEMUFile));
4505 if (!f)
4506 return NULL;
4507 f->is_file = 0;
4508 f->bs = bs;
4509 f->is_writable = is_writable;
4510 f->base_offset = offset;
4511 return f;
4514 void qemu_fflush(QEMUFile *f)
4516 if (!f->is_writable)
4517 return;
4518 if (f->buf_index > 0) {
4519 if (f->is_file) {
4520 fseek(f->outfile, f->buf_offset, SEEK_SET);
4521 fwrite(f->buf, 1, f->buf_index, f->outfile);
4522 } else {
4523 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4524 f->buf, f->buf_index);
4526 f->buf_offset += f->buf_index;
4527 f->buf_index = 0;
4531 static void qemu_fill_buffer(QEMUFile *f)
4533 int len;
4535 if (f->is_writable)
4536 return;
4537 if (f->is_file) {
4538 fseek(f->outfile, f->buf_offset, SEEK_SET);
4539 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4540 if (len < 0)
4541 len = 0;
4542 } else {
4543 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4544 f->buf, IO_BUF_SIZE);
4545 if (len < 0)
4546 len = 0;
4548 f->buf_index = 0;
4549 f->buf_size = len;
4550 f->buf_offset += len;
4553 void qemu_fclose(QEMUFile *f)
4555 if (f->is_writable)
4556 qemu_fflush(f);
4557 if (f->is_file) {
4558 fclose(f->outfile);
4560 qemu_free(f);
4563 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4565 int l;
4566 while (size > 0) {
4567 l = IO_BUF_SIZE - f->buf_index;
4568 if (l > size)
4569 l = size;
4570 memcpy(f->buf + f->buf_index, buf, l);
4571 f->buf_index += l;
4572 buf += l;
4573 size -= l;
4574 if (f->buf_index >= IO_BUF_SIZE)
4575 qemu_fflush(f);
4579 void qemu_put_byte(QEMUFile *f, int v)
4581 f->buf[f->buf_index++] = v;
4582 if (f->buf_index >= IO_BUF_SIZE)
4583 qemu_fflush(f);
4586 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4588 int size, l;
4590 size = size1;
4591 while (size > 0) {
4592 l = f->buf_size - f->buf_index;
4593 if (l == 0) {
4594 qemu_fill_buffer(f);
4595 l = f->buf_size - f->buf_index;
4596 if (l == 0)
4597 break;
4599 if (l > size)
4600 l = size;
4601 memcpy(buf, f->buf + f->buf_index, l);
4602 f->buf_index += l;
4603 buf += l;
4604 size -= l;
4606 return size1 - size;
4609 int qemu_get_byte(QEMUFile *f)
4611 if (f->buf_index >= f->buf_size) {
4612 qemu_fill_buffer(f);
4613 if (f->buf_index >= f->buf_size)
4614 return 0;
4616 return f->buf[f->buf_index++];
4619 int64_t qemu_ftell(QEMUFile *f)
4621 return f->buf_offset - f->buf_size + f->buf_index;
4624 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4626 if (whence == SEEK_SET) {
4627 /* nothing to do */
4628 } else if (whence == SEEK_CUR) {
4629 pos += qemu_ftell(f);
4630 } else {
4631 /* SEEK_END not supported */
4632 return -1;
4634 if (f->is_writable) {
4635 qemu_fflush(f);
4636 f->buf_offset = pos;
4637 } else {
4638 f->buf_offset = pos;
4639 f->buf_index = 0;
4640 f->buf_size = 0;
4642 return pos;
4645 void qemu_put_be16(QEMUFile *f, unsigned int v)
4647 qemu_put_byte(f, v >> 8);
4648 qemu_put_byte(f, v);
4651 void qemu_put_be32(QEMUFile *f, unsigned int v)
4653 qemu_put_byte(f, v >> 24);
4654 qemu_put_byte(f, v >> 16);
4655 qemu_put_byte(f, v >> 8);
4656 qemu_put_byte(f, v);
4659 void qemu_put_be64(QEMUFile *f, uint64_t v)
4661 qemu_put_be32(f, v >> 32);
4662 qemu_put_be32(f, v);
4665 unsigned int qemu_get_be16(QEMUFile *f)
4667 unsigned int v;
4668 v = qemu_get_byte(f) << 8;
4669 v |= qemu_get_byte(f);
4670 return v;
4673 unsigned int qemu_get_be32(QEMUFile *f)
4675 unsigned int v;
4676 v = qemu_get_byte(f) << 24;
4677 v |= qemu_get_byte(f) << 16;
4678 v |= qemu_get_byte(f) << 8;
4679 v |= qemu_get_byte(f);
4680 return v;
4683 uint64_t qemu_get_be64(QEMUFile *f)
4685 uint64_t v;
4686 v = (uint64_t)qemu_get_be32(f) << 32;
4687 v |= qemu_get_be32(f);
4688 return v;
4691 typedef struct SaveStateEntry {
4692 char idstr[256];
4693 int instance_id;
4694 int version_id;
4695 SaveStateHandler *save_state;
4696 LoadStateHandler *load_state;
4697 void *opaque;
4698 struct SaveStateEntry *next;
4699 } SaveStateEntry;
4701 static SaveStateEntry *first_se;
4703 int register_savevm(const char *idstr,
4704 int instance_id,
4705 int version_id,
4706 SaveStateHandler *save_state,
4707 LoadStateHandler *load_state,
4708 void *opaque)
4710 SaveStateEntry *se, **pse;
4712 se = qemu_malloc(sizeof(SaveStateEntry));
4713 if (!se)
4714 return -1;
4715 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4716 se->instance_id = instance_id;
4717 se->version_id = version_id;
4718 se->save_state = save_state;
4719 se->load_state = load_state;
4720 se->opaque = opaque;
4721 se->next = NULL;
4723 /* add at the end of list */
4724 pse = &first_se;
4725 while (*pse != NULL)
4726 pse = &(*pse)->next;
4727 *pse = se;
4728 return 0;
4731 #define QEMU_VM_FILE_MAGIC 0x5145564d
4732 #define QEMU_VM_FILE_VERSION 0x00000002
4734 int qemu_savevm_state(QEMUFile *f)
4736 SaveStateEntry *se;
4737 int len, ret;
4738 int64_t cur_pos, len_pos, total_len_pos;
4740 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4741 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4742 total_len_pos = qemu_ftell(f);
4743 qemu_put_be64(f, 0); /* total size */
4745 for(se = first_se; se != NULL; se = se->next) {
4746 /* ID string */
4747 len = strlen(se->idstr);
4748 qemu_put_byte(f, len);
4749 qemu_put_buffer(f, se->idstr, len);
4751 qemu_put_be32(f, se->instance_id);
4752 qemu_put_be32(f, se->version_id);
4754 /* record size: filled later */
4755 len_pos = qemu_ftell(f);
4756 qemu_put_be32(f, 0);
4758 se->save_state(f, se->opaque);
4760 /* fill record size */
4761 cur_pos = qemu_ftell(f);
4762 len = cur_pos - len_pos - 4;
4763 qemu_fseek(f, len_pos, SEEK_SET);
4764 qemu_put_be32(f, len);
4765 qemu_fseek(f, cur_pos, SEEK_SET);
4767 cur_pos = qemu_ftell(f);
4768 qemu_fseek(f, total_len_pos, SEEK_SET);
4769 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4770 qemu_fseek(f, cur_pos, SEEK_SET);
4772 ret = 0;
4773 return ret;
4776 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4778 SaveStateEntry *se;
4780 for(se = first_se; se != NULL; se = se->next) {
4781 if (!strcmp(se->idstr, idstr) &&
4782 instance_id == se->instance_id)
4783 return se;
4785 return NULL;
4788 int qemu_loadvm_state(QEMUFile *f)
4790 SaveStateEntry *se;
4791 int len, ret, instance_id, record_len, version_id;
4792 int64_t total_len, end_pos, cur_pos;
4793 unsigned int v;
4794 char idstr[256];
4796 v = qemu_get_be32(f);
4797 if (v != QEMU_VM_FILE_MAGIC)
4798 goto fail;
4799 v = qemu_get_be32(f);
4800 if (v != QEMU_VM_FILE_VERSION) {
4801 fail:
4802 ret = -1;
4803 goto the_end;
4805 total_len = qemu_get_be64(f);
4806 end_pos = total_len + qemu_ftell(f);
4807 for(;;) {
4808 if (qemu_ftell(f) >= end_pos)
4809 break;
4810 len = qemu_get_byte(f);
4811 qemu_get_buffer(f, idstr, len);
4812 idstr[len] = '\0';
4813 instance_id = qemu_get_be32(f);
4814 version_id = qemu_get_be32(f);
4815 record_len = qemu_get_be32(f);
4816 #if 0
4817 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4818 idstr, instance_id, version_id, record_len);
4819 #endif
4820 cur_pos = qemu_ftell(f);
4821 se = find_se(idstr, instance_id);
4822 if (!se) {
4823 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4824 instance_id, idstr);
4825 } else {
4826 ret = se->load_state(f, se->opaque, version_id);
4827 if (ret < 0) {
4828 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4829 instance_id, idstr);
4832 /* always seek to exact end of record */
4833 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4835 ret = 0;
4836 the_end:
4837 return ret;
4840 /* device can contain snapshots */
4841 static int bdrv_can_snapshot(BlockDriverState *bs)
4843 return (bs &&
4844 !bdrv_is_removable(bs) &&
4845 !bdrv_is_read_only(bs));
4848 /* device must be snapshots in order to have a reliable snapshot */
4849 static int bdrv_has_snapshot(BlockDriverState *bs)
4851 return (bs &&
4852 !bdrv_is_removable(bs) &&
4853 !bdrv_is_read_only(bs));
4856 static BlockDriverState *get_bs_snapshots(void)
4858 BlockDriverState *bs;
4859 int i;
4861 if (bs_snapshots)
4862 return bs_snapshots;
4863 for(i = 0; i <= MAX_DISKS; i++) {
4864 bs = bs_table[i];
4865 if (bdrv_can_snapshot(bs))
4866 goto ok;
4868 return NULL;
4869 ok:
4870 bs_snapshots = bs;
4871 return bs;
4874 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4875 const char *name)
4877 QEMUSnapshotInfo *sn_tab, *sn;
4878 int nb_sns, i, ret;
4880 ret = -ENOENT;
4881 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4882 if (nb_sns < 0)
4883 return ret;
4884 for(i = 0; i < nb_sns; i++) {
4885 sn = &sn_tab[i];
4886 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4887 *sn_info = *sn;
4888 ret = 0;
4889 break;
4892 qemu_free(sn_tab);
4893 return ret;
4896 #ifdef CONFIG_DM
4897 /* We use simpler state save/load functions for Xen */
4898 void do_savevm(const char *name)
4900 QEMUFile *f;
4901 int saved_vm_running, ret;
4903 f = qemu_fopen(name, "wb");
4905 /* ??? Should this occur after vm_stop? */
4906 qemu_aio_flush();
4908 saved_vm_running = vm_running;
4909 vm_stop(0);
4911 if (!f) {
4912 fprintf(logfile, "Failed to open savevm file '%s'\n", name);
4913 goto the_end;
4916 ret = qemu_savevm_state(f);
4917 qemu_fclose(f);
4919 if (ret < 0)
4920 fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
4921 ret, name);
4923 the_end:
4924 if (saved_vm_running)
4925 vm_start();
4927 return;
4929 void do_loadvm(const char *name)
4931 QEMUFile *f;
4932 int saved_vm_running, ret;
4934 /* Flush all IO requests so they don't interfere with the new state. */
4935 qemu_aio_flush();
4937 saved_vm_running = vm_running;
4938 vm_stop(0);
4940 /* restore the VM state */
4941 f = qemu_fopen(name, "rb");
4942 if (!f) {
4943 fprintf(logfile, "Could not open VM state file\n");
4944 goto the_end;
4947 ret = qemu_loadvm_state(f);
4948 qemu_fclose(f);
4949 if (ret < 0) {
4950 fprintf(logfile, "Error %d while loading savevm file '%s'\n",
4951 ret, name);
4952 goto the_end;
4955 #if 0
4956 /* del tmp file */
4957 if (unlink(name) == -1)
4958 fprintf(stderr, "delete tmp qemu state file failed.\n");
4959 #endif
4962 the_end:
4963 if (saved_vm_running)
4964 vm_start();
4966 #else
4967 void do_savevm(const char *name)
4969 BlockDriverState *bs, *bs1;
4970 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4971 int must_delete, ret, i;
4972 BlockDriverInfo bdi1, *bdi = &bdi1;
4973 QEMUFile *f;
4974 int saved_vm_running;
4975 #ifdef _WIN32
4976 struct _timeb tb;
4977 #else
4978 struct timeval tv;
4979 #endif
4981 bs = get_bs_snapshots();
4982 if (!bs) {
4983 term_printf("No block device can accept snapshots\n");
4984 return;
4987 /* ??? Should this occur after vm_stop? */
4988 qemu_aio_flush();
4990 saved_vm_running = vm_running;
4991 vm_stop(0);
4993 must_delete = 0;
4994 if (name) {
4995 ret = bdrv_snapshot_find(bs, old_sn, name);
4996 if (ret >= 0) {
4997 must_delete = 1;
5000 memset(sn, 0, sizeof(*sn));
5001 if (must_delete) {
5002 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5003 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5004 } else {
5005 if (name)
5006 pstrcpy(sn->name, sizeof(sn->name), name);
5009 /* fill auxiliary fields */
5010 #ifdef _WIN32
5011 _ftime(&tb);
5012 sn->date_sec = tb.time;
5013 sn->date_nsec = tb.millitm * 1000000;
5014 #else
5015 gettimeofday(&tv, NULL);
5016 sn->date_sec = tv.tv_sec;
5017 sn->date_nsec = tv.tv_usec * 1000;
5018 #endif
5019 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5021 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5022 term_printf("Device %s does not support VM state snapshots\n",
5023 bdrv_get_device_name(bs));
5024 goto the_end;
5027 /* save the VM state */
5028 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5029 if (!f) {
5030 term_printf("Could not open VM state file\n");
5031 goto the_end;
5033 ret = qemu_savevm_state(f);
5034 sn->vm_state_size = qemu_ftell(f);
5035 qemu_fclose(f);
5036 if (ret < 0) {
5037 term_printf("Error %d while writing VM\n", ret);
5038 goto the_end;
5041 /* create the snapshots */
5043 for(i = 0; i < MAX_DISKS; i++) {
5044 bs1 = bs_table[i];
5045 if (bdrv_has_snapshot(bs1)) {
5046 if (must_delete) {
5047 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5048 if (ret < 0) {
5049 term_printf("Error while deleting snapshot on '%s'\n",
5050 bdrv_get_device_name(bs1));
5053 ret = bdrv_snapshot_create(bs1, sn);
5054 if (ret < 0) {
5055 term_printf("Error while creating snapshot on '%s'\n",
5056 bdrv_get_device_name(bs1));
5061 the_end:
5062 if (saved_vm_running)
5063 vm_start();
5066 void do_loadvm(const char *name)
5068 BlockDriverState *bs, *bs1;
5069 BlockDriverInfo bdi1, *bdi = &bdi1;
5070 QEMUFile *f;
5071 int i, ret;
5072 int saved_vm_running;
5074 bs = get_bs_snapshots();
5075 if (!bs) {
5076 term_printf("No block device supports snapshots\n");
5077 return;
5080 /* Flush all IO requests so they don't interfere with the new state. */
5081 qemu_aio_flush();
5083 saved_vm_running = vm_running;
5084 vm_stop(0);
5086 for(i = 0; i <= MAX_DISKS; i++) {
5087 bs1 = bs_table[i];
5088 if (bdrv_has_snapshot(bs1)) {
5089 ret = bdrv_snapshot_goto(bs1, name);
5090 if (ret < 0) {
5091 if (bs != bs1)
5092 term_printf("Warning: ");
5093 switch(ret) {
5094 case -ENOTSUP:
5095 term_printf("Snapshots not supported on device '%s'\n",
5096 bdrv_get_device_name(bs1));
5097 break;
5098 case -ENOENT:
5099 term_printf("Could not find snapshot '%s' on device '%s'\n",
5100 name, bdrv_get_device_name(bs1));
5101 break;
5102 default:
5103 term_printf("Error %d while activating snapshot on '%s'\n",
5104 ret, bdrv_get_device_name(bs1));
5105 break;
5107 /* fatal on snapshot block device */
5108 if (bs == bs1)
5109 goto the_end;
5114 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5115 term_printf("Device %s does not support VM state snapshots\n",
5116 bdrv_get_device_name(bs));
5117 return;
5120 /* restore the VM state */
5121 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5122 if (!f) {
5123 term_printf("Could not open VM state file\n");
5124 goto the_end;
5126 ret = qemu_loadvm_state(f);
5127 qemu_fclose(f);
5128 if (ret < 0) {
5129 term_printf("Error %d while loading VM state\n", ret);
5132 /* del tmp file */
5133 if (unlink(name) == -1)
5134 fprintf(stderr, "delete tmp qemu state file failed.\n");
5136 the_end:
5137 if (saved_vm_running)
5138 vm_start();
5140 #endif
5142 void do_delvm(const char *name)
5144 BlockDriverState *bs, *bs1;
5145 int i, ret;
5147 bs = get_bs_snapshots();
5148 if (!bs) {
5149 term_printf("No block device supports snapshots\n");
5150 return;
5153 for(i = 0; i <= MAX_DISKS; i++) {
5154 bs1 = bs_table[i];
5155 if (bdrv_has_snapshot(bs1)) {
5156 ret = bdrv_snapshot_delete(bs1, name);
5157 if (ret < 0) {
5158 if (ret == -ENOTSUP)
5159 term_printf("Snapshots not supported on device '%s'\n",
5160 bdrv_get_device_name(bs1));
5161 else
5162 term_printf("Error %d while deleting snapshot on '%s'\n",
5163 ret, bdrv_get_device_name(bs1));
5169 void do_info_snapshots(void)
5171 BlockDriverState *bs, *bs1;
5172 QEMUSnapshotInfo *sn_tab, *sn;
5173 int nb_sns, i;
5174 char buf[256];
5176 bs = get_bs_snapshots();
5177 if (!bs) {
5178 term_printf("No available block device supports snapshots\n");
5179 return;
5181 term_printf("Snapshot devices:");
5182 for(i = 0; i <= MAX_DISKS; i++) {
5183 bs1 = bs_table[i];
5184 if (bdrv_has_snapshot(bs1)) {
5185 if (bs == bs1)
5186 term_printf(" %s", bdrv_get_device_name(bs1));
5189 term_printf("\n");
5191 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5192 if (nb_sns < 0) {
5193 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5194 return;
5196 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5197 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5198 for(i = 0; i < nb_sns; i++) {
5199 sn = &sn_tab[i];
5200 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5202 qemu_free(sn_tab);
5205 #ifndef CONFIG_DM
5206 /***********************************************************/
5207 /* cpu save/restore */
5209 #if defined(TARGET_I386)
5211 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5213 qemu_put_be32(f, dt->selector);
5214 qemu_put_betl(f, dt->base);
5215 qemu_put_be32(f, dt->limit);
5216 qemu_put_be32(f, dt->flags);
5219 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5221 dt->selector = qemu_get_be32(f);
5222 dt->base = qemu_get_betl(f);
5223 dt->limit = qemu_get_be32(f);
5224 dt->flags = qemu_get_be32(f);
5227 void cpu_save(QEMUFile *f, void *opaque)
5229 CPUState *env = opaque;
5230 uint16_t fptag, fpus, fpuc, fpregs_format;
5231 uint32_t hflags;
5232 int i;
5234 for(i = 0; i < CPU_NB_REGS; i++)
5235 qemu_put_betls(f, &env->regs[i]);
5236 qemu_put_betls(f, &env->eip);
5237 qemu_put_betls(f, &env->eflags);
5238 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5239 qemu_put_be32s(f, &hflags);
5241 /* FPU */
5242 fpuc = env->fpuc;
5243 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5244 fptag = 0;
5245 for(i = 0; i < 8; i++) {
5246 fptag |= ((!env->fptags[i]) << i);
5249 qemu_put_be16s(f, &fpuc);
5250 qemu_put_be16s(f, &fpus);
5251 qemu_put_be16s(f, &fptag);
5253 #ifdef USE_X86LDOUBLE
5254 fpregs_format = 0;
5255 #else
5256 fpregs_format = 1;
5257 #endif
5258 qemu_put_be16s(f, &fpregs_format);
5260 for(i = 0; i < 8; i++) {
5261 #ifdef USE_X86LDOUBLE
5263 uint64_t mant;
5264 uint16_t exp;
5265 /* we save the real CPU data (in case of MMX usage only 'mant'
5266 contains the MMX register */
5267 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5268 qemu_put_be64(f, mant);
5269 qemu_put_be16(f, exp);
5271 #else
5272 /* if we use doubles for float emulation, we save the doubles to
5273 avoid losing information in case of MMX usage. It can give
5274 problems if the image is restored on a CPU where long
5275 doubles are used instead. */
5276 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5277 #endif
5280 for(i = 0; i < 6; i++)
5281 cpu_put_seg(f, &env->segs[i]);
5282 cpu_put_seg(f, &env->ldt);
5283 cpu_put_seg(f, &env->tr);
5284 cpu_put_seg(f, &env->gdt);
5285 cpu_put_seg(f, &env->idt);
5287 qemu_put_be32s(f, &env->sysenter_cs);
5288 qemu_put_be32s(f, &env->sysenter_esp);
5289 qemu_put_be32s(f, &env->sysenter_eip);
5291 qemu_put_betls(f, &env->cr[0]);
5292 qemu_put_betls(f, &env->cr[2]);
5293 qemu_put_betls(f, &env->cr[3]);
5294 qemu_put_betls(f, &env->cr[4]);
5296 for(i = 0; i < 8; i++)
5297 qemu_put_betls(f, &env->dr[i]);
5299 /* MMU */
5300 qemu_put_be32s(f, &env->a20_mask);
5302 /* XMM */
5303 qemu_put_be32s(f, &env->mxcsr);
5304 for(i = 0; i < CPU_NB_REGS; i++) {
5305 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5306 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5309 #ifdef TARGET_X86_64
5310 qemu_put_be64s(f, &env->efer);
5311 qemu_put_be64s(f, &env->star);
5312 qemu_put_be64s(f, &env->lstar);
5313 qemu_put_be64s(f, &env->cstar);
5314 qemu_put_be64s(f, &env->fmask);
5315 qemu_put_be64s(f, &env->kernelgsbase);
5316 #endif
5317 qemu_put_be32s(f, &env->smbase);
5320 #ifdef USE_X86LDOUBLE
5321 /* XXX: add that in a FPU generic layer */
5322 union x86_longdouble {
5323 uint64_t mant;
5324 uint16_t exp;
5325 };
5327 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5328 #define EXPBIAS1 1023
5329 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5330 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5332 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5334 int e;
5335 /* mantissa */
5336 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5337 /* exponent + sign */
5338 e = EXPD1(temp) - EXPBIAS1 + 16383;
5339 e |= SIGND1(temp) >> 16;
5340 p->exp = e;
5342 #endif
5344 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5346 CPUState *env = opaque;
5347 int i, guess_mmx;
5348 uint32_t hflags;
5349 uint16_t fpus, fpuc, fptag, fpregs_format;
5351 if (version_id != 3 && version_id != 4)
5352 return -EINVAL;
5353 for(i = 0; i < CPU_NB_REGS; i++)
5354 qemu_get_betls(f, &env->regs[i]);
5355 qemu_get_betls(f, &env->eip);
5356 qemu_get_betls(f, &env->eflags);
5357 qemu_get_be32s(f, &hflags);
5359 qemu_get_be16s(f, &fpuc);
5360 qemu_get_be16s(f, &fpus);
5361 qemu_get_be16s(f, &fptag);
5362 qemu_get_be16s(f, &fpregs_format);
5364 /* NOTE: we cannot always restore the FPU state if the image come
5365 from a host with a different 'USE_X86LDOUBLE' define. We guess
5366 if we are in an MMX state to restore correctly in that case. */
5367 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5368 for(i = 0; i < 8; i++) {
5369 uint64_t mant;
5370 uint16_t exp;
5372 switch(fpregs_format) {
5373 case 0:
5374 mant = qemu_get_be64(f);
5375 exp = qemu_get_be16(f);
5376 #ifdef USE_X86LDOUBLE
5377 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5378 #else
5379 /* difficult case */
5380 if (guess_mmx)
5381 env->fpregs[i].mmx.MMX_Q(0) = mant;
5382 else
5383 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5384 #endif
5385 break;
5386 case 1:
5387 mant = qemu_get_be64(f);
5388 #ifdef USE_X86LDOUBLE
5390 union x86_longdouble *p;
5391 /* difficult case */
5392 p = (void *)&env->fpregs[i];
5393 if (guess_mmx) {
5394 p->mant = mant;
5395 p->exp = 0xffff;
5396 } else {
5397 fp64_to_fp80(p, mant);
5400 #else
5401 env->fpregs[i].mmx.MMX_Q(0) = mant;
5402 #endif
5403 break;
5404 default:
5405 return -EINVAL;
5409 env->fpuc = fpuc;
5410 /* XXX: restore FPU round state */
5411 env->fpstt = (fpus >> 11) & 7;
5412 env->fpus = fpus & ~0x3800;
5413 fptag ^= 0xff;
5414 for(i = 0; i < 8; i++) {
5415 env->fptags[i] = (fptag >> i) & 1;
5418 for(i = 0; i < 6; i++)
5419 cpu_get_seg(f, &env->segs[i]);
5420 cpu_get_seg(f, &env->ldt);
5421 cpu_get_seg(f, &env->tr);
5422 cpu_get_seg(f, &env->gdt);
5423 cpu_get_seg(f, &env->idt);
5425 qemu_get_be32s(f, &env->sysenter_cs);
5426 qemu_get_be32s(f, &env->sysenter_esp);
5427 qemu_get_be32s(f, &env->sysenter_eip);
5429 qemu_get_betls(f, &env->cr[0]);
5430 qemu_get_betls(f, &env->cr[2]);
5431 qemu_get_betls(f, &env->cr[3]);
5432 qemu_get_betls(f, &env->cr[4]);
5434 for(i = 0; i < 8; i++)
5435 qemu_get_betls(f, &env->dr[i]);
5437 /* MMU */
5438 qemu_get_be32s(f, &env->a20_mask);
5440 qemu_get_be32s(f, &env->mxcsr);
5441 for(i = 0; i < CPU_NB_REGS; i++) {
5442 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5443 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5446 #ifdef TARGET_X86_64
5447 qemu_get_be64s(f, &env->efer);
5448 qemu_get_be64s(f, &env->star);
5449 qemu_get_be64s(f, &env->lstar);
5450 qemu_get_be64s(f, &env->cstar);
5451 qemu_get_be64s(f, &env->fmask);
5452 qemu_get_be64s(f, &env->kernelgsbase);
5453 #endif
5454 if (version_id >= 4)
5455 qemu_get_be32s(f, &env->smbase);
5457 /* XXX: compute hflags from scratch, except for CPL and IIF */
5458 env->hflags = hflags;
5459 tlb_flush(env, 1);
5460 return 0;
5463 #elif defined(TARGET_PPC)
5464 void cpu_save(QEMUFile *f, void *opaque)
5468 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5470 return 0;
5473 #elif defined(TARGET_MIPS)
5474 void cpu_save(QEMUFile *f, void *opaque)
5478 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5480 return 0;
5483 #elif defined(TARGET_SPARC)
5484 void cpu_save(QEMUFile *f, void *opaque)
5486 CPUState *env = opaque;
5487 int i;
5488 uint32_t tmp;
5490 for(i = 0; i < 8; i++)
5491 qemu_put_betls(f, &env->gregs[i]);
5492 for(i = 0; i < NWINDOWS * 16; i++)
5493 qemu_put_betls(f, &env->regbase[i]);
5495 /* FPU */
5496 for(i = 0; i < TARGET_FPREGS; i++) {
5497 union {
5498 float32 f;
5499 uint32_t i;
5500 } u;
5501 u.f = env->fpr[i];
5502 qemu_put_be32(f, u.i);
5505 qemu_put_betls(f, &env->pc);
5506 qemu_put_betls(f, &env->npc);
5507 qemu_put_betls(f, &env->y);
5508 tmp = GET_PSR(env);
5509 qemu_put_be32(f, tmp);
5510 qemu_put_betls(f, &env->fsr);
5511 qemu_put_betls(f, &env->tbr);
5512 #ifndef TARGET_SPARC64
5513 qemu_put_be32s(f, &env->wim);
5514 /* MMU */
5515 for(i = 0; i < 16; i++)
5516 qemu_put_be32s(f, &env->mmuregs[i]);
5517 #endif
5520 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5522 CPUState *env = opaque;
5523 int i;
5524 uint32_t tmp;
5526 for(i = 0; i < 8; i++)
5527 qemu_get_betls(f, &env->gregs[i]);
5528 for(i = 0; i < NWINDOWS * 16; i++)
5529 qemu_get_betls(f, &env->regbase[i]);
5531 /* FPU */
5532 for(i = 0; i < TARGET_FPREGS; i++) {
5533 union {
5534 float32 f;
5535 uint32_t i;
5536 } u;
5537 u.i = qemu_get_be32(f);
5538 env->fpr[i] = u.f;
5541 qemu_get_betls(f, &env->pc);
5542 qemu_get_betls(f, &env->npc);
5543 qemu_get_betls(f, &env->y);
5544 tmp = qemu_get_be32(f);
5545 env->cwp = 0; /* needed to ensure that the wrapping registers are
5546 correctly updated */
5547 PUT_PSR(env, tmp);
5548 qemu_get_betls(f, &env->fsr);
5549 qemu_get_betls(f, &env->tbr);
5550 #ifndef TARGET_SPARC64
5551 qemu_get_be32s(f, &env->wim);
5552 /* MMU */
5553 for(i = 0; i < 16; i++)
5554 qemu_get_be32s(f, &env->mmuregs[i]);
5555 #endif
5556 tlb_flush(env, 1);
5557 return 0;
5560 #elif defined(TARGET_ARM)
5562 /* ??? Need to implement these. */
5563 void cpu_save(QEMUFile *f, void *opaque)
5567 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5569 return 0;
5572 #else
5574 #warning No CPU save/restore functions
5576 #endif
5578 /***********************************************************/
5579 /* ram save/restore */
5581 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5583 int v;
5585 v = qemu_get_byte(f);
5586 switch(v) {
5587 case 0:
5588 if (qemu_get_buffer(f, buf, len) != len)
5589 return -EIO;
5590 break;
5591 case 1:
5592 v = qemu_get_byte(f);
5593 memset(buf, v, len);
5594 break;
5595 default:
5596 return -EINVAL;
5598 return 0;
5601 static int ram_load_v1(QEMUFile *f, void *opaque)
5603 int i, ret;
5605 if (qemu_get_be32(f) != phys_ram_size)
5606 return -EINVAL;
5607 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5608 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5609 if (ret)
5610 return ret;
5612 return 0;
5615 #define BDRV_HASH_BLOCK_SIZE 1024
5616 #define IOBUF_SIZE 4096
5617 #define RAM_CBLOCK_MAGIC 0xfabe
5619 typedef struct RamCompressState {
5620 z_stream zstream;
5621 QEMUFile *f;
5622 uint8_t buf[IOBUF_SIZE];
5623 } RamCompressState;
5625 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5627 int ret;
5628 memset(s, 0, sizeof(*s));
5629 s->f = f;
5630 ret = deflateInit2(&s->zstream, 1,
5631 Z_DEFLATED, 15,
5632 9, Z_DEFAULT_STRATEGY);
5633 if (ret != Z_OK)
5634 return -1;
5635 s->zstream.avail_out = IOBUF_SIZE;
5636 s->zstream.next_out = s->buf;
5637 return 0;
5640 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5642 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5643 qemu_put_be16(s->f, len);
5644 qemu_put_buffer(s->f, buf, len);
5647 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5649 int ret;
5651 s->zstream.avail_in = len;
5652 s->zstream.next_in = (uint8_t *)buf;
5653 while (s->zstream.avail_in > 0) {
5654 ret = deflate(&s->zstream, Z_NO_FLUSH);
5655 if (ret != Z_OK)
5656 return -1;
5657 if (s->zstream.avail_out == 0) {
5658 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5659 s->zstream.avail_out = IOBUF_SIZE;
5660 s->zstream.next_out = s->buf;
5663 return 0;
5666 static void ram_compress_close(RamCompressState *s)
5668 int len, ret;
5670 /* compress last bytes */
5671 for(;;) {
5672 ret = deflate(&s->zstream, Z_FINISH);
5673 if (ret == Z_OK || ret == Z_STREAM_END) {
5674 len = IOBUF_SIZE - s->zstream.avail_out;
5675 if (len > 0) {
5676 ram_put_cblock(s, s->buf, len);
5678 s->zstream.avail_out = IOBUF_SIZE;
5679 s->zstream.next_out = s->buf;
5680 if (ret == Z_STREAM_END)
5681 break;
5682 } else {
5683 goto fail;
5686 fail:
5687 deflateEnd(&s->zstream);
5690 typedef struct RamDecompressState {
5691 z_stream zstream;
5692 QEMUFile *f;
5693 uint8_t buf[IOBUF_SIZE];
5694 } RamDecompressState;
5696 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5698 int ret;
5699 memset(s, 0, sizeof(*s));
5700 s->f = f;
5701 ret = inflateInit(&s->zstream);
5702 if (ret != Z_OK)
5703 return -1;
5704 return 0;
5707 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5709 int ret, clen;
5711 s->zstream.avail_out = len;
5712 s->zstream.next_out = buf;
5713 while (s->zstream.avail_out > 0) {
5714 if (s->zstream.avail_in == 0) {
5715 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5716 return -1;
5717 clen = qemu_get_be16(s->f);
5718 if (clen > IOBUF_SIZE)
5719 return -1;
5720 qemu_get_buffer(s->f, s->buf, clen);
5721 s->zstream.avail_in = clen;
5722 s->zstream.next_in = s->buf;
5724 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5725 if (ret != Z_OK && ret != Z_STREAM_END) {
5726 return -1;
5729 return 0;
5732 static void ram_decompress_close(RamDecompressState *s)
5734 inflateEnd(&s->zstream);
5737 static void ram_save(QEMUFile *f, void *opaque)
5739 int i;
5740 RamCompressState s1, *s = &s1;
5741 uint8_t buf[10];
5743 qemu_put_be32(f, phys_ram_size);
5744 if (ram_compress_open(s, f) < 0)
5745 return;
5746 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5747 #if 0
5748 if (tight_savevm_enabled) {
5749 int64_t sector_num;
5750 int j;
5752 /* find if the memory block is available on a virtual
5753 block device */
5754 sector_num = -1;
5755 for(j = 0; j < MAX_DISKS; j++) {
5756 if (bs_table[j]) {
5757 sector_num = bdrv_hash_find(bs_table[j],
5758 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5759 if (sector_num >= 0)
5760 break;
5763 if (j == MAX_DISKS)
5764 goto normal_compress;
5765 buf[0] = 1;
5766 buf[1] = j;
5767 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5768 ram_compress_buf(s, buf, 10);
5769 } else
5770 #endif
5772 // normal_compress:
5773 buf[0] = 0;
5774 ram_compress_buf(s, buf, 1);
5775 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5778 ram_compress_close(s);
5781 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5783 RamDecompressState s1, *s = &s1;
5784 uint8_t buf[10];
5785 int i;
5787 if (version_id == 1)
5788 return ram_load_v1(f, opaque);
5789 if (version_id != 2)
5790 return -EINVAL;
5791 if (qemu_get_be32(f) != phys_ram_size)
5792 return -EINVAL;
5793 if (ram_decompress_open(s, f) < 0)
5794 return -EINVAL;
5795 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5796 if (ram_decompress_buf(s, buf, 1) < 0) {
5797 fprintf(stderr, "Error while reading ram block header\n");
5798 goto error;
5800 if (buf[0] == 0) {
5801 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5802 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5803 goto error;
5805 } else
5806 #if 0
5807 if (buf[0] == 1) {
5808 int bs_index;
5809 int64_t sector_num;
5811 ram_decompress_buf(s, buf + 1, 9);
5812 bs_index = buf[1];
5813 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5814 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5815 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5816 goto error;
5818 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5819 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5820 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5821 bs_index, sector_num);
5822 goto error;
5824 } else
5825 #endif
5827 error:
5828 printf("Error block header\n");
5829 return -EINVAL;
5832 ram_decompress_close(s);
5833 return 0;
5835 #else /* CONFIG_DM */
5836 void cpu_save(QEMUFile *f, void *opaque)
5840 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5842 return 0;
5845 static void ram_save(QEMUFile *f, void *opaque)
5849 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5851 return 0;
5853 #endif /* CONFIG_DM */
5855 /***********************************************************/
5856 /* bottom halves (can be seen as timers which expire ASAP) */
5858 struct QEMUBH {
5859 QEMUBHFunc *cb;
5860 void *opaque;
5861 int scheduled;
5862 QEMUBH *next;
5863 };
5865 static QEMUBH *first_bh = NULL;
5867 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5869 QEMUBH *bh;
5870 bh = qemu_mallocz(sizeof(QEMUBH));
5871 if (!bh)
5872 return NULL;
5873 bh->cb = cb;
5874 bh->opaque = opaque;
5875 return bh;
5878 int qemu_bh_poll(void)
5880 QEMUBH *bh, **pbh;
5881 int ret;
5883 ret = 0;
5884 for(;;) {
5885 pbh = &first_bh;
5886 bh = *pbh;
5887 if (!bh)
5888 break;
5889 ret = 1;
5890 *pbh = bh->next;
5891 bh->scheduled = 0;
5892 bh->cb(bh->opaque);
5894 return ret;
5897 void qemu_bh_schedule(QEMUBH *bh)
5899 CPUState *env = cpu_single_env;
5900 if (bh->scheduled)
5901 return;
5902 bh->scheduled = 1;
5903 bh->next = first_bh;
5904 first_bh = bh;
5906 /* stop the currently executing CPU to execute the BH ASAP */
5907 if (env) {
5908 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5912 void qemu_bh_cancel(QEMUBH *bh)
5914 QEMUBH **pbh;
5915 if (bh->scheduled) {
5916 pbh = &first_bh;
5917 while (*pbh != bh)
5918 pbh = &(*pbh)->next;
5919 *pbh = bh->next;
5920 bh->scheduled = 0;
5924 void qemu_bh_delete(QEMUBH *bh)
5926 qemu_bh_cancel(bh);
5927 qemu_free(bh);
5930 /***********************************************************/
5931 /* machine registration */
5933 QEMUMachine *first_machine = NULL;
5935 int qemu_register_machine(QEMUMachine *m)
5937 QEMUMachine **pm;
5938 pm = &first_machine;
5939 while (*pm != NULL)
5940 pm = &(*pm)->next;
5941 m->next = NULL;
5942 *pm = m;
5943 return 0;
5946 QEMUMachine *find_machine(const char *name)
5948 QEMUMachine *m;
5950 for(m = first_machine; m != NULL; m = m->next) {
5951 if (!strcmp(m->name, name))
5952 return m;
5954 return NULL;
5957 /***********************************************************/
5958 /* main execution loop */
5960 void gui_update(void *opaque)
5962 display_state.dpy_refresh(&display_state);
5963 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5966 struct vm_change_state_entry {
5967 VMChangeStateHandler *cb;
5968 void *opaque;
5969 LIST_ENTRY (vm_change_state_entry) entries;
5970 };
5972 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5974 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5975 void *opaque)
5977 VMChangeStateEntry *e;
5979 e = qemu_mallocz(sizeof (*e));
5980 if (!e)
5981 return NULL;
5983 e->cb = cb;
5984 e->opaque = opaque;
5985 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5986 return e;
5989 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5991 LIST_REMOVE (e, entries);
5992 qemu_free (e);
5995 static void vm_state_notify(int running)
5997 VMChangeStateEntry *e;
5999 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6000 e->cb(e->opaque, running);
6004 /* XXX: support several handlers */
6005 static VMStopHandler *vm_stop_cb;
6006 static void *vm_stop_opaque;
6008 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6010 vm_stop_cb = cb;
6011 vm_stop_opaque = opaque;
6012 return 0;
6015 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6017 vm_stop_cb = NULL;
6020 void vm_start(void)
6022 if (!vm_running) {
6023 cpu_enable_ticks();
6024 vm_running = 1;
6025 vm_state_notify(1);
6029 void vm_stop(int reason)
6031 if (vm_running) {
6032 cpu_disable_ticks();
6033 vm_running = 0;
6034 if (reason != 0) {
6035 if (vm_stop_cb) {
6036 vm_stop_cb(vm_stop_opaque, reason);
6039 vm_state_notify(0);
6043 /* reset/shutdown handler */
6045 typedef struct QEMUResetEntry {
6046 QEMUResetHandler *func;
6047 void *opaque;
6048 struct QEMUResetEntry *next;
6049 } QEMUResetEntry;
6051 static QEMUResetEntry *first_reset_entry;
6052 int reset_requested;
6053 int shutdown_requested;
6054 int suspend_requested;
6055 static int powerdown_requested;
6057 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6059 QEMUResetEntry **pre, *re;
6061 pre = &first_reset_entry;
6062 while (*pre != NULL)
6063 pre = &(*pre)->next;
6064 re = qemu_mallocz(sizeof(QEMUResetEntry));
6065 re->func = func;
6066 re->opaque = opaque;
6067 re->next = NULL;
6068 *pre = re;
6071 void qemu_system_reset(void)
6073 QEMUResetEntry *re;
6075 /* reset all devices */
6076 for(re = first_reset_entry; re != NULL; re = re->next) {
6077 re->func(re->opaque);
6081 void qemu_system_reset_request(void)
6083 if (no_reboot) {
6084 shutdown_requested = 1;
6085 } else {
6086 reset_requested = 1;
6088 if (cpu_single_env)
6089 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6092 void qemu_system_shutdown_request(void)
6094 shutdown_requested = 1;
6095 if (cpu_single_env)
6096 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6099 void qemu_system_powerdown_request(void)
6101 powerdown_requested = 1;
6102 if (cpu_single_env)
6103 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6106 void main_loop_wait(int timeout)
6108 IOHandlerRecord *ioh, *ioh_next;
6109 fd_set rfds, wfds, xfds;
6110 int ret, nfds;
6111 struct timeval tv;
6112 PollingEntry *pe;
6115 /* XXX: need to suppress polling by better using win32 events */
6116 ret = 0;
6117 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6118 ret |= pe->func(pe->opaque);
6120 #ifdef _WIN32
6121 if (ret == 0 && timeout > 0) {
6122 int err;
6123 WaitObjects *w = &wait_objects;
6125 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6126 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6127 if (w->func[ret - WAIT_OBJECT_0])
6128 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6129 } else if (ret == WAIT_TIMEOUT) {
6130 } else {
6131 err = GetLastError();
6132 fprintf(stderr, "Wait error %d %d\n", ret, err);
6135 #endif
6136 /* poll any events */
6137 /* XXX: separate device handlers from system ones */
6138 nfds = -1;
6139 FD_ZERO(&rfds);
6140 FD_ZERO(&wfds);
6141 FD_ZERO(&xfds);
6142 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6143 if (ioh->fd_read &&
6144 (!ioh->fd_read_poll ||
6145 ioh->fd_read_poll(ioh->opaque) != 0)) {
6146 FD_SET(ioh->fd, &rfds);
6147 if (ioh->fd > nfds)
6148 nfds = ioh->fd;
6150 if (ioh->fd_write) {
6151 FD_SET(ioh->fd, &wfds);
6152 if (ioh->fd > nfds)
6153 nfds = ioh->fd;
6157 tv.tv_sec = 0;
6158 #ifdef _WIN32
6159 tv.tv_usec = 0;
6160 #else
6161 tv.tv_usec = timeout * 1000;
6162 #endif
6163 #if defined(CONFIG_SLIRP)
6164 if (slirp_inited) {
6165 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6167 #endif
6168 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6169 if (ret > 0) {
6170 /* XXX: better handling of removal */
6171 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
6172 ioh_next = ioh->next;
6173 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6174 ioh->fd_read(ioh->opaque);
6176 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6177 ioh->fd_write(ioh->opaque);
6181 #if defined(CONFIG_SLIRP)
6182 if (slirp_inited) {
6183 if (ret < 0) {
6184 FD_ZERO(&rfds);
6185 FD_ZERO(&wfds);
6186 FD_ZERO(&xfds);
6188 slirp_select_poll(&rfds, &wfds, &xfds);
6190 #endif
6191 qemu_aio_poll();
6192 qemu_bh_poll();
6194 if (vm_running) {
6195 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6196 qemu_get_clock(vm_clock));
6197 /* run dma transfers, if any */
6198 DMA_run();
6201 /* real time timers */
6202 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6203 qemu_get_clock(rt_clock));
6206 #ifndef CONFIG_DM
6207 static CPUState *cur_cpu;
6209 int main_loop(void)
6211 int ret, timeout;
6212 #ifdef CONFIG_PROFILER
6213 int64_t ti;
6214 #endif
6215 CPUState *env;
6217 cur_cpu = first_cpu;
6218 for(;;) {
6219 if (vm_running) {
6221 env = cur_cpu;
6222 for(;;) {
6223 /* get next cpu */
6224 env = env->next_cpu;
6225 if (!env)
6226 env = first_cpu;
6227 #ifdef CONFIG_PROFILER
6228 ti = profile_getclock();
6229 #endif
6230 ret = cpu_exec(env);
6231 #ifdef CONFIG_PROFILER
6232 qemu_time += profile_getclock() - ti;
6233 #endif
6234 if (ret != EXCP_HALTED)
6235 break;
6236 /* all CPUs are halted ? */
6237 if (env == cur_cpu) {
6238 ret = EXCP_HLT;
6239 break;
6242 cur_cpu = env;
6244 if (shutdown_requested) {
6245 ret = EXCP_INTERRUPT;
6246 break;
6248 if (reset_requested) {
6249 reset_requested = 0;
6250 qemu_system_reset();
6251 ret = EXCP_INTERRUPT;
6253 if (powerdown_requested) {
6254 powerdown_requested = 0;
6255 qemu_system_powerdown();
6256 ret = EXCP_INTERRUPT;
6258 if (ret == EXCP_DEBUG) {
6259 vm_stop(EXCP_DEBUG);
6261 /* if hlt instruction, we wait until the next IRQ */
6262 /* XXX: use timeout computed from timers */
6263 if (ret == EXCP_HLT)
6264 timeout = 10;
6265 else
6266 timeout = 0;
6267 } else {
6268 timeout = 10;
6270 #ifdef CONFIG_PROFILER
6271 ti = profile_getclock();
6272 #endif
6273 main_loop_wait(timeout);
6274 #ifdef CONFIG_PROFILER
6275 dev_time += profile_getclock() - ti;
6276 #endif
6278 cpu_disable_ticks();
6279 return ret;
6281 #endif /* !CONFIG_DM */
6283 void help(void)
6285 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6286 "usage: %s [options] [disk_image]\n"
6287 "\n"
6288 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6289 "\n"
6290 "Standard options:\n"
6291 "-M machine select emulated machine (-M ? for list)\n"
6292 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6293 #ifndef CONFIG_DM
6294 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6295 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6296 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6297 #endif /* !CONFIG_DM */
6298 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6299 "-snapshot write to temporary files instead of disk image files\n"
6300 #ifdef CONFIG_SDL
6301 "-no-quit disable SDL window close capability\n"
6302 #endif
6303 #ifdef TARGET_I386
6304 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6305 #endif
6306 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6307 "-smp n set the number of CPUs to 'n' [default=1]\n"
6308 "-nographic disable graphical output and redirect serial I/Os to console\n"
6309 "-vcpus set CPU number of guest platform\n"
6310 #ifndef _WIN32
6311 "-k language use keyboard layout (for example \"fr\" for French)\n"
6312 #endif
6313 #ifdef HAS_AUDIO
6314 "-audio-help print list of audio drivers and their options\n"
6315 "-soundhw c1,... enable audio support\n"
6316 " and only specified sound cards (comma separated list)\n"
6317 " use -soundhw ? to get the list of supported cards\n"
6318 " use -soundhw all to enable all of them\n"
6319 #endif
6320 "-localtime set the real time clock to local time [default=utc]\n"
6321 "-full-screen start in full screen\n"
6322 #ifdef TARGET_I386
6323 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6324 #endif
6325 "-usb enable the USB driver (will be the default soon)\n"
6326 "-usbdevice name add the host or guest USB device 'name'\n"
6327 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6328 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6329 #endif
6330 "\n"
6331 "Network options:\n"
6332 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6333 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6334 #ifdef CONFIG_SLIRP
6335 "-net user[,vlan=n][,hostname=host]\n"
6336 " connect the user mode network stack to VLAN 'n' and send\n"
6337 " hostname 'host' to DHCP clients\n"
6338 #endif
6339 #ifdef _WIN32
6340 "-net tap[,vlan=n],ifname=name\n"
6341 " connect the host TAP network interface to VLAN 'n'\n"
6342 #else
6343 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6344 " connect the host TAP network interface to VLAN 'n' and use\n"
6345 " the network script 'file' (default=%s);\n"
6346 " use 'script=no' to disable script execution;\n"
6347 " use 'fd=h' to connect to an already opened TAP interface\n"
6348 #endif
6349 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6350 " connect the vlan 'n' to another VLAN using a socket connection\n"
6351 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6352 " connect the vlan 'n' to multicast maddr and port\n"
6353 "-net none use it alone to have zero network devices; if no -net option\n"
6354 " is provided, the default is '-net nic -net user'\n"
6355 "\n"
6356 #ifdef CONFIG_SLIRP
6357 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6358 #ifndef _WIN32
6359 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6360 #endif
6361 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6362 " redirect TCP or UDP connections from host to guest [-net user]\n"
6363 #endif
6364 "\n"
6365 "Linux boot specific:\n"
6366 "-kernel bzImage use 'bzImage' as kernel image\n"
6367 "-append cmdline use 'cmdline' as kernel command line\n"
6368 "-initrd file use 'file' as initial ram disk\n"
6369 "\n"
6370 "Debug/Expert options:\n"
6371 "-monitor dev redirect the monitor to char device 'dev'\n"
6372 "-serial dev redirect the serial port to char device 'dev'\n"
6373 "-parallel dev redirect the parallel port to char device 'dev'\n"
6374 "-pidfile file Write PID to 'file'\n"
6375 "-S freeze CPU at startup (use 'c' to start execution)\n"
6376 "-s wait gdb connection to port %d\n"
6377 "-p port change gdb connection port\n"
6378 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
6379 "-d domain domain that we're serving\n"
6380 "-domain-name domain name that we're serving\n"
6381 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6382 " translation (t=none or lba) (usually qemu can guess them)\n"
6383 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6384 #ifdef USE_KQEMU
6385 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6386 "-no-kqemu disable KQEMU kernel module usage\n"
6387 #endif
6388 #ifdef USE_CODE_COPY
6389 "-no-code-copy disable code copy acceleration\n"
6390 #endif
6391 #ifdef TARGET_I386
6392 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6393 " (default is CL-GD5446 PCI VGA)\n"
6394 "-no-acpi disable ACPI\n"
6395 #endif
6396 "-no-reboot exit instead of rebooting\n"
6397 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6398 "-vnc display start a VNC server on display\n"
6399 "-vncviewer start a vncviewer process for this domain\n"
6400 "-vncunused bind the VNC server to an unused port\n"
6401 #ifndef _WIN32
6402 "-daemonize daemonize QEMU after initializing\n"
6403 #endif
6404 "-option-rom rom load a file, rom, into the option ROM space\n"
6405 "-acpi disable or enable ACPI of HVM domain \n"
6406 "\n"
6407 "During emulation, the following keys are useful:\n"
6408 "ctrl-alt-f toggle full screen\n"
6409 "ctrl-alt-n switch to virtual console 'n'\n"
6410 "ctrl-alt toggle mouse and keyboard grab\n"
6411 "\n"
6412 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6414 "qemu",
6415 DEFAULT_RAM_SIZE,
6416 #ifndef _WIN32
6417 DEFAULT_NETWORK_SCRIPT,
6418 #endif
6419 DEFAULT_GDBSTUB_PORT,
6420 "/tmp/qemu.log");
6421 exit(1);
6424 #define HAS_ARG 0x0001
6426 enum {
6427 QEMU_OPTION_h,
6429 QEMU_OPTION_M,
6430 QEMU_OPTION_fda,
6431 QEMU_OPTION_fdb,
6432 #ifndef CONFIG_DM
6433 QEMU_OPTION_hda,
6434 QEMU_OPTION_hdb,
6435 QEMU_OPTION_hdc,
6436 QEMU_OPTION_hdd,
6437 QEMU_OPTION_cdrom,
6438 #endif /* !CONFIG_DM */
6439 QEMU_OPTION_boot,
6440 QEMU_OPTION_snapshot,
6441 #ifdef TARGET_I386
6442 QEMU_OPTION_no_fd_bootchk,
6443 #endif
6444 QEMU_OPTION_m,
6445 QEMU_OPTION_nographic,
6446 #ifdef HAS_AUDIO
6447 QEMU_OPTION_audio_help,
6448 QEMU_OPTION_soundhw,
6449 #endif
6451 QEMU_OPTION_net,
6452 QEMU_OPTION_tftp,
6453 QEMU_OPTION_smb,
6454 QEMU_OPTION_redir,
6456 QEMU_OPTION_kernel,
6457 QEMU_OPTION_append,
6458 QEMU_OPTION_initrd,
6460 QEMU_OPTION_S,
6461 QEMU_OPTION_s,
6462 QEMU_OPTION_p,
6463 QEMU_OPTION_l,
6464 QEMU_OPTION_hdachs,
6465 QEMU_OPTION_L,
6466 #ifdef USE_CODE_COPY
6467 QEMU_OPTION_no_code_copy,
6468 #endif
6469 QEMU_OPTION_k,
6470 QEMU_OPTION_localtime,
6471 QEMU_OPTION_cirrusvga,
6472 QEMU_OPTION_g,
6473 QEMU_OPTION_std_vga,
6474 QEMU_OPTION_monitor,
6475 QEMU_OPTION_domainname,
6476 QEMU_OPTION_serial,
6477 QEMU_OPTION_parallel,
6478 QEMU_OPTION_loadvm,
6479 QEMU_OPTION_full_screen,
6480 QEMU_OPTION_no_quit,
6481 QEMU_OPTION_pidfile,
6482 QEMU_OPTION_no_kqemu,
6483 QEMU_OPTION_kernel_kqemu,
6484 QEMU_OPTION_win2k_hack,
6485 QEMU_OPTION_usb,
6486 QEMU_OPTION_usbdevice,
6487 QEMU_OPTION_smp,
6488 QEMU_OPTION_vnc,
6489 QEMU_OPTION_no_acpi,
6490 QEMU_OPTION_no_reboot,
6491 QEMU_OPTION_daemonize,
6492 QEMU_OPTION_option_rom,
6493 QEMU_OPTION_semihosting
6495 QEMU_OPTION_d,
6496 QEMU_OPTION_vcpus,
6497 QEMU_OPTION_acpi,
6498 QEMU_OPTION_vncviewer,
6499 QEMU_OPTION_vncunused,
6500 };
6502 typedef struct QEMUOption {
6503 const char *name;
6504 int flags;
6505 int index;
6506 } QEMUOption;
6508 const QEMUOption qemu_options[] = {
6509 { "h", 0, QEMU_OPTION_h },
6510 { "help", 0, QEMU_OPTION_h },
6512 { "M", HAS_ARG, QEMU_OPTION_M },
6513 { "fda", HAS_ARG, QEMU_OPTION_fda },
6514 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6515 #ifndef CONFIG_DM
6516 { "hda", HAS_ARG, QEMU_OPTION_hda },
6517 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6518 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6519 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6520 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6521 #endif /* !CONFIG_DM */
6522 { "boot", HAS_ARG, QEMU_OPTION_boot },
6523 { "snapshot", 0, QEMU_OPTION_snapshot },
6524 #ifdef TARGET_I386
6525 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6526 #endif
6527 { "m", HAS_ARG, QEMU_OPTION_m },
6528 { "nographic", 0, QEMU_OPTION_nographic },
6529 { "k", HAS_ARG, QEMU_OPTION_k },
6530 #ifdef HAS_AUDIO
6531 { "audio-help", 0, QEMU_OPTION_audio_help },
6532 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6533 #endif
6535 { "net", HAS_ARG, QEMU_OPTION_net},
6536 #ifdef CONFIG_SLIRP
6537 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6538 #ifndef _WIN32
6539 { "smb", HAS_ARG, QEMU_OPTION_smb },
6540 #endif
6541 { "redir", HAS_ARG, QEMU_OPTION_redir },
6542 #endif
6544 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6545 { "append", HAS_ARG, QEMU_OPTION_append },
6546 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6548 { "S", 0, QEMU_OPTION_S },
6549 { "s", 0, QEMU_OPTION_s },
6550 { "p", HAS_ARG, QEMU_OPTION_p },
6551 { "l", HAS_ARG, QEMU_OPTION_l },
6552 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6553 { "L", HAS_ARG, QEMU_OPTION_L },
6554 #ifdef USE_CODE_COPY
6555 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6556 #endif
6557 #ifdef USE_KQEMU
6558 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6559 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6560 #endif
6561 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6562 { "g", 1, QEMU_OPTION_g },
6563 #endif
6564 { "localtime", 0, QEMU_OPTION_localtime },
6565 { "std-vga", 0, QEMU_OPTION_std_vga },
6566 { "monitor", 1, QEMU_OPTION_monitor },
6567 { "domain-name", 1, QEMU_OPTION_domainname },
6568 { "serial", 1, QEMU_OPTION_serial },
6569 { "parallel", 1, QEMU_OPTION_parallel },
6570 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6571 { "full-screen", 0, QEMU_OPTION_full_screen },
6572 #ifdef CONFIG_SDL
6573 { "no-quit", 0, QEMU_OPTION_no_quit },
6574 #endif
6575 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6576 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6577 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6578 { "smp", HAS_ARG, QEMU_OPTION_smp },
6579 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6580 { "vncviewer", 0, QEMU_OPTION_vncviewer },
6581 { "vncunused", 0, QEMU_OPTION_vncunused },
6583 /* temporary options */
6584 { "usb", 0, QEMU_OPTION_usb },
6585 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6586 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6587 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6588 { "daemonize", 0, QEMU_OPTION_daemonize },
6589 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6590 #if defined(TARGET_ARM)
6591 { "semihosting", 0, QEMU_OPTION_semihosting },
6592 #endif
6594 { "d", HAS_ARG, QEMU_OPTION_d },
6595 { "vcpus", 1, QEMU_OPTION_vcpus },
6596 { "acpi", 0, QEMU_OPTION_acpi },
6597 { NULL },
6598 };
6600 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6602 /* this stack is only used during signal handling */
6603 #define SIGNAL_STACK_SIZE 32768
6605 static uint8_t *signal_stack;
6607 #endif
6609 /* password input */
6611 static BlockDriverState *get_bdrv(int index)
6613 BlockDriverState *bs;
6615 if (index < 4) {
6616 bs = bs_table[index];
6617 } else if (index < 6) {
6618 bs = fd_table[index - 4];
6619 } else {
6620 bs = NULL;
6622 return bs;
6625 static void read_passwords(void)
6627 BlockDriverState *bs;
6628 int i, j;
6629 char password[256];
6631 for(i = 0; i < 6; i++) {
6632 bs = get_bdrv(i);
6633 if (bs && bdrv_is_encrypted(bs)) {
6634 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6635 for(j = 0; j < 3; j++) {
6636 monitor_readline("Password: ",
6637 1, password, sizeof(password));
6638 if (bdrv_set_key(bs, password) == 0)
6639 break;
6640 term_printf("invalid password\n");
6646 /* XXX: currently we cannot use simultaneously different CPUs */
6647 void register_machines(void)
6649 #if defined(TARGET_I386)
6650 qemu_register_machine(&pc_machine);
6651 qemu_register_machine(&isapc_machine);
6652 #elif defined(TARGET_PPC)
6653 qemu_register_machine(&heathrow_machine);
6654 qemu_register_machine(&core99_machine);
6655 qemu_register_machine(&prep_machine);
6656 #elif defined(TARGET_MIPS)
6657 qemu_register_machine(&mips_machine);
6658 qemu_register_machine(&mips_malta_machine);
6659 #elif defined(TARGET_SPARC)
6660 #ifdef TARGET_SPARC64
6661 qemu_register_machine(&sun4u_machine);
6662 #else
6663 qemu_register_machine(&sun4m_machine);
6664 #endif
6665 #elif defined(TARGET_ARM)
6666 qemu_register_machine(&integratorcp926_machine);
6667 qemu_register_machine(&integratorcp1026_machine);
6668 qemu_register_machine(&versatilepb_machine);
6669 qemu_register_machine(&versatileab_machine);
6670 qemu_register_machine(&realview_machine);
6671 #elif defined(TARGET_SH4)
6672 qemu_register_machine(&shix_machine);
6673 #else
6674 #error unsupported CPU
6675 #endif
6678 #ifdef HAS_AUDIO
6679 struct soundhw soundhw[] = {
6680 #ifndef CONFIG_DM
6681 #ifdef TARGET_I386
6683 "pcspk",
6684 "PC speaker",
6685 0,
6686 1,
6687 { .init_isa = pcspk_audio_init }
6688 },
6689 #endif
6690 #endif /* !CONFIG_DM */
6692 "sb16",
6693 "Creative Sound Blaster 16",
6694 0,
6695 1,
6696 { .init_isa = SB16_init }
6697 },
6699 #ifdef CONFIG_ADLIB
6701 "adlib",
6702 #ifdef HAS_YMF262
6703 "Yamaha YMF262 (OPL3)",
6704 #else
6705 "Yamaha YM3812 (OPL2)",
6706 #endif
6707 0,
6708 1,
6709 { .init_isa = Adlib_init }
6710 },
6711 #endif
6713 #ifdef CONFIG_GUS
6715 "gus",
6716 "Gravis Ultrasound GF1",
6717 0,
6718 1,
6719 { .init_isa = GUS_init }
6720 },
6721 #endif
6724 "es1370",
6725 "ENSONIQ AudioPCI ES1370",
6726 0,
6727 0,
6728 { .init_pci = es1370_init }
6729 },
6731 { NULL, NULL, 0, 0, { NULL } }
6732 };
6734 static void select_soundhw (const char *optarg)
6736 struct soundhw *c;
6738 if (*optarg == '?') {
6739 show_valid_cards:
6741 printf ("Valid sound card names (comma separated):\n");
6742 for (c = soundhw; c->name; ++c) {
6743 printf ("%-11s %s\n", c->name, c->descr);
6745 printf ("\n-soundhw all will enable all of the above\n");
6746 exit (*optarg != '?');
6748 else {
6749 size_t l;
6750 const char *p;
6751 char *e;
6752 int bad_card = 0;
6754 if (!strcmp (optarg, "all")) {
6755 for (c = soundhw; c->name; ++c) {
6756 c->enabled = 1;
6758 return;
6761 p = optarg;
6762 while (*p) {
6763 e = strchr (p, ',');
6764 l = !e ? strlen (p) : (size_t) (e - p);
6766 for (c = soundhw; c->name; ++c) {
6767 if (!strncmp (c->name, p, l)) {
6768 c->enabled = 1;
6769 break;
6773 if (!c->name) {
6774 if (l > 80) {
6775 fprintf (stderr,
6776 "Unknown sound card name (too big to show)\n");
6778 else {
6779 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6780 (int) l, p);
6782 bad_card = 1;
6784 p += l + (e != NULL);
6787 if (bad_card)
6788 goto show_valid_cards;
6791 #endif
6793 #ifdef _WIN32
6794 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6796 exit(STATUS_CONTROL_C_EXIT);
6797 return TRUE;
6799 #endif
6801 #define MAX_NET_CLIENTS 32
6803 #include <xg_private.h>
6805 /* FIXME Flush the shadow page */
6806 int unset_mm_mapping(int xc_handle, uint32_t domid,
6807 unsigned long nr_pages, unsigned int address_bits,
6808 xen_pfn_t *extent_start)
6810 int err = 0;
6811 xc_dominfo_t info;
6813 xc_domain_getinfo(xc_handle, domid, 1, &info);
6814 if ((info.nr_pages - nr_pages) <= 0) {
6815 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
6816 err = -1;
6819 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
6820 nr_pages, 0, extent_start);
6821 if (err)
6822 fprintf(stderr, "Failed to decrease physmap\n");
6825 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
6826 PAGE_SIZE/1024) != 0) {
6827 fprintf(logfile, "set maxmem returned error %d\n", errno);
6828 err = -1;
6831 return err;
6834 int set_mm_mapping(int xc_handle, uint32_t domid,
6835 unsigned long nr_pages, unsigned int address_bits,
6836 xen_pfn_t *extent_start)
6838 xc_dominfo_t info;
6839 int err = 0;
6841 xc_domain_getinfo(xc_handle, domid, 1, &info);
6843 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
6844 nr_pages * PAGE_SIZE/1024) != 0) {
6845 fprintf(logfile, "set maxmem returned error %d\n", errno);
6846 return -1;
6849 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
6850 address_bits, extent_start);
6851 if (err) {
6852 fprintf(stderr, "Failed to populate physmap\n");
6853 return -1;
6856 return 0;
6859 void suspend(int sig)
6861 fprintf(logfile, "suspend sig handler called with requested=%d!\n",
6862 suspend_requested);
6863 if (sig != SIGUSR1)
6864 fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
6865 suspend_requested = 1;
6868 #if defined(MAPCACHE)
6870 #if defined(__i386__)
6871 #define MAX_MCACHE_SIZE 0x40000000 /* 1GB max for x86 */
6872 #define MCACHE_BUCKET_SHIFT 16
6873 #elif defined(__x86_64__)
6874 #define MAX_MCACHE_SIZE 0x1000000000 /* 64GB max for x86_64 */
6875 #define MCACHE_BUCKET_SHIFT 20
6876 #endif
6878 #define MCACHE_BUCKET_SIZE (1UL << MCACHE_BUCKET_SHIFT)
6880 #define BITS_PER_LONG (sizeof(long)*8)
6881 #define BITS_TO_LONGS(bits) \
6882 (((bits)+BITS_PER_LONG-1)/BITS_PER_LONG)
6883 #define DECLARE_BITMAP(name,bits) \
6884 unsigned long name[BITS_TO_LONGS(bits)]
6885 #define test_bit(bit,map) \
6886 (!!((map)[(bit)/BITS_PER_LONG] & (1UL << ((bit)%BITS_PER_LONG))))
6888 struct map_cache {
6889 unsigned long paddr_index;
6890 uint8_t *vaddr_base;
6891 DECLARE_BITMAP(valid_mapping, MCACHE_BUCKET_SIZE>>PAGE_SHIFT);
6892 };
6894 static struct map_cache *mapcache_entry;
6895 static unsigned long nr_buckets;
6897 /* For most cases (>99.9%), the page address is the same. */
6898 static unsigned long last_address_index = ~0UL;
6899 static uint8_t *last_address_vaddr;
6901 static int qemu_map_cache_init(void)
6903 unsigned long size;
6905 nr_buckets = (((MAX_MCACHE_SIZE >> PAGE_SHIFT) +
6906 (1UL << (MCACHE_BUCKET_SHIFT - PAGE_SHIFT)) - 1) >>
6907 (MCACHE_BUCKET_SHIFT - PAGE_SHIFT));
6908 fprintf(logfile, "qemu_map_cache_init nr_buckets = %lx\n", nr_buckets);
6910 /*
6911 * Use mmap() directly: lets us allocate a big hash table with no up-front
6912 * cost in storage space. The OS will allocate memory only for the buckets
6913 * that we actually use. All others will contain all zeroes.
6914 */
6915 size = nr_buckets * sizeof(struct map_cache);
6916 size = (size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
6917 mapcache_entry = mmap(NULL, size, PROT_READ|PROT_WRITE,
6918 MAP_SHARED|MAP_ANONYMOUS, 0, 0);
6919 if (mapcache_entry == MAP_FAILED) {
6920 errno = ENOMEM;
6921 return -1;
6924 return 0;
6927 static void qemu_remap_bucket(struct map_cache *entry,
6928 unsigned long address_index)
6930 uint8_t *vaddr_base;
6931 unsigned long pfns[MCACHE_BUCKET_SIZE >> PAGE_SHIFT];
6932 unsigned int i, j;
6934 if (entry->vaddr_base != NULL) {
6935 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
6936 if (errno) {
6937 fprintf(logfile, "unmap fails %d\n", errno);
6938 exit(-1);
6942 for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i++)
6943 pfns[i] = (address_index << (MCACHE_BUCKET_SHIFT-PAGE_SHIFT)) + i;
6945 vaddr_base = xc_map_foreign_batch(xc_handle, domid, PROT_READ|PROT_WRITE,
6946 pfns, MCACHE_BUCKET_SIZE >> PAGE_SHIFT);
6947 if (vaddr_base == NULL) {
6948 fprintf(logfile, "xc_map_foreign_batch error %d\n", errno);
6949 exit(-1);
6952 entry->vaddr_base = vaddr_base;
6953 entry->paddr_index = address_index;
6955 for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i += BITS_PER_LONG) {
6956 unsigned long word = 0;
6957 j = ((i + BITS_PER_LONG) > (MCACHE_BUCKET_SIZE >> PAGE_SHIFT)) ?
6958 (MCACHE_BUCKET_SIZE >> PAGE_SHIFT) % BITS_PER_LONG : BITS_PER_LONG;
6959 while (j > 0)
6960 word = (word << 1) | !(pfns[i + --j] & 0xF0000000UL);
6961 entry->valid_mapping[i / BITS_PER_LONG] = word;
6965 uint8_t *qemu_map_cache(target_phys_addr_t phys_addr)
6967 struct map_cache *entry;
6968 unsigned long address_index = phys_addr >> MCACHE_BUCKET_SHIFT;
6969 unsigned long address_offset = phys_addr & (MCACHE_BUCKET_SIZE-1);
6971 if (address_index == last_address_index)
6972 return last_address_vaddr + address_offset;
6974 entry = &mapcache_entry[address_index % nr_buckets];
6976 if (entry->vaddr_base == NULL || entry->paddr_index != address_index ||
6977 !test_bit(address_offset>>PAGE_SHIFT, entry->valid_mapping))
6978 qemu_remap_bucket(entry, address_index);
6980 if (!test_bit(address_offset>>PAGE_SHIFT, entry->valid_mapping))
6981 return NULL;
6983 last_address_index = address_index;
6984 last_address_vaddr = entry->vaddr_base;
6986 return last_address_vaddr + address_offset;
6989 void qemu_invalidate_map_cache(void)
6991 unsigned long i;
6993 mapcache_lock();
6995 for (i = 0; i < nr_buckets; i++) {
6996 struct map_cache *entry = &mapcache_entry[i];
6998 if (entry->vaddr_base == NULL)
6999 continue;
7001 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
7002 if (errno) {
7003 fprintf(logfile, "unmap fails %d\n", errno);
7004 exit(-1);
7007 entry->paddr_index = 0;
7008 entry->vaddr_base = NULL;
7011 last_address_index = ~0UL;
7012 last_address_vaddr = NULL;
7014 mapcache_unlock();
7017 #endif /* defined(MAPCACHE) */
7019 int main(int argc, char **argv)
7021 #ifdef CONFIG_GDBSTUB
7022 int use_gdbstub, gdbstub_port;
7023 #endif
7024 int i;
7025 #ifndef CONFIG_DM
7026 int cdrom_index;
7027 #endif /* !CONFIG_DM */
7028 int snapshot, linux_boot;
7029 const char *initrd_filename;
7030 #ifndef CONFIG_DM
7031 const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
7032 #endif /* !CONFIG_DM */
7033 const char *fd_filename[MAX_FD];
7034 const char *kernel_filename, *kernel_cmdline;
7035 DisplayState *ds = &display_state;
7036 int cyls, heads, secs, translation;
7037 char net_clients[MAX_NET_CLIENTS][256];
7038 int nb_net_clients;
7039 int optind;
7040 const char *r, *optarg;
7041 CharDriverState *monitor_hd;
7042 char monitor_device[128];
7043 char serial_devices[MAX_SERIAL_PORTS][128];
7044 int serial_device_index;
7045 char parallel_devices[MAX_PARALLEL_PORTS][128];
7046 int parallel_device_index;
7047 const char *loadvm = NULL;
7048 QEMUMachine *machine;
7049 char usb_devices[MAX_USB_CMDLINE][128];
7050 int usb_devices_index;
7051 int fds[2];
7052 unsigned long ioreq_pfn;
7053 extern void *shared_page;
7054 extern void *buffered_io_page;
7055 #ifdef __ia64__
7056 unsigned long nr_pages;
7057 xen_pfn_t *page_array;
7058 extern void *buffered_pio_page;
7059 #endif
7061 char qemu_dm_logfilename[128];
7063 LIST_INIT (&vm_change_state_head);
7064 #ifndef _WIN32
7066 struct sigaction act;
7067 sigfillset(&act.sa_mask);
7068 act.sa_flags = 0;
7069 act.sa_handler = SIG_IGN;
7070 sigaction(SIGPIPE, &act, NULL);
7072 #else
7073 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7074 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7075 QEMU to run on a single CPU */
7077 HANDLE h;
7078 DWORD mask, smask;
7079 int i;
7080 h = GetCurrentProcess();
7081 if (GetProcessAffinityMask(h, &mask, &smask)) {
7082 for(i = 0; i < 32; i++) {
7083 if (mask & (1 << i))
7084 break;
7086 if (i != 32) {
7087 mask = 1 << i;
7088 SetProcessAffinityMask(h, mask);
7092 #endif
7094 register_machines();
7095 machine = first_machine;
7096 initrd_filename = NULL;
7097 for(i = 0; i < MAX_FD; i++)
7098 fd_filename[i] = NULL;
7099 #ifndef CONFIG_DM
7100 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7101 hd_filename[i] = NULL;
7102 #endif /* !CONFIG_DM */
7103 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7104 vga_ram_size = VGA_RAM_SIZE;
7105 bios_size = BIOS_SIZE;
7106 #ifdef CONFIG_GDBSTUB
7107 use_gdbstub = 0;
7108 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7109 #endif
7110 snapshot = 0;
7111 nographic = 0;
7112 vncviewer = 0;
7113 vncunused = 0;
7114 kernel_filename = NULL;
7115 kernel_cmdline = "";
7116 *vncpasswd = '\0';
7117 #ifndef CONFIG_DM
7118 #ifdef TARGET_PPC
7119 cdrom_index = 1;
7120 #else
7121 cdrom_index = 2;
7122 #endif
7123 #endif /* !CONFIG_DM */
7124 cyls = heads = secs = 0;
7125 translation = BIOS_ATA_TRANSLATION_AUTO;
7126 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7128 for(i = 0; i < MAX_SERIAL_PORTS; i++)
7129 serial_devices[i][0] = '\0';
7130 serial_device_index = 0;
7132 #ifndef CONFIG_DM
7133 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7134 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7135 #else
7136 /* Xen steals IRQ7 for PCI. Disable LPT1 by default. */
7137 for(i = 0; i < MAX_PARALLEL_PORTS; i++)
7138 #endif
7139 parallel_devices[i][0] = '\0';
7140 parallel_device_index = 0;
7142 usb_devices_index = 0;
7144 nb_net_clients = 0;
7146 nb_nics = 0;
7147 /* default mac address of the first network interface */
7149 /* Init logs to stderr to start with */
7150 cpu_set_log(0);
7152 optind = 1;
7153 for(;;) {
7154 if (optind >= argc)
7155 break;
7156 r = argv[optind];
7157 if (r[0] != '-') {
7158 #ifndef CONFIG_DM
7159 hd_filename[0] = argv[optind++];
7160 #else
7161 help();
7162 #endif /* !CONFIG_DM */
7163 } else {
7164 const QEMUOption *popt;
7166 optind++;
7167 /* Treat --foo the same as -foo. */
7168 if (r[1] == '-')
7169 r++;
7170 popt = qemu_options;
7171 for(;;) {
7172 if (!popt->name) {
7173 fprintf(stderr, "%s: invalid option -- '%s'\n",
7174 argv[0], r);
7175 exit(1);
7177 if (!strcmp(popt->name, r + 1))
7178 break;
7179 popt++;
7181 if (popt->flags & HAS_ARG) {
7182 if (optind >= argc) {
7183 fprintf(stderr, "%s: option '%s' requires an argument\n",
7184 argv[0], r);
7185 exit(1);
7187 optarg = argv[optind++];
7188 } else {
7189 optarg = NULL;
7192 switch(popt->index) {
7193 case QEMU_OPTION_M:
7194 machine = find_machine(optarg);
7195 if (!machine) {
7196 QEMUMachine *m;
7197 printf("Supported machines are:\n");
7198 for(m = first_machine; m != NULL; m = m->next) {
7199 printf("%-10s %s%s\n",
7200 m->name, m->desc,
7201 m == first_machine ? " (default)" : "");
7203 exit(1);
7205 break;
7206 case QEMU_OPTION_initrd:
7207 initrd_filename = optarg;
7208 break;
7209 #ifndef CONFIG_DM
7210 case QEMU_OPTION_hda:
7211 case QEMU_OPTION_hdb:
7212 case QEMU_OPTION_hdc:
7213 case QEMU_OPTION_hdd:
7215 int hd_index;
7216 hd_index = popt->index - QEMU_OPTION_hda;
7217 hd_filename[hd_index] = optarg;
7218 if (hd_index == cdrom_index)
7219 cdrom_index = -1;
7221 break;
7222 #endif /* !CONFIG_DM */
7223 case QEMU_OPTION_snapshot:
7224 snapshot = 1;
7225 break;
7226 case QEMU_OPTION_hdachs:
7228 const char *p;
7229 p = optarg;
7230 cyls = strtol(p, (char **)&p, 0);
7231 if (cyls < 1 || cyls > 16383)
7232 goto chs_fail;
7233 if (*p != ',')
7234 goto chs_fail;
7235 p++;
7236 heads = strtol(p, (char **)&p, 0);
7237 if (heads < 1 || heads > 16)
7238 goto chs_fail;
7239 if (*p != ',')
7240 goto chs_fail;
7241 p++;
7242 secs = strtol(p, (char **)&p, 0);
7243 if (secs < 1 || secs > 63)
7244 goto chs_fail;
7245 if (*p == ',') {
7246 p++;
7247 if (!strcmp(p, "none"))
7248 translation = BIOS_ATA_TRANSLATION_NONE;
7249 else if (!strcmp(p, "lba"))
7250 translation = BIOS_ATA_TRANSLATION_LBA;
7251 else if (!strcmp(p, "auto"))
7252 translation = BIOS_ATA_TRANSLATION_AUTO;
7253 else
7254 goto chs_fail;
7255 } else if (*p != '\0') {
7256 chs_fail:
7257 fprintf(stderr, "qemu: invalid physical CHS format\n");
7258 exit(1);
7261 break;
7262 case QEMU_OPTION_nographic:
7263 if(!strcmp(monitor_device, "vc"))
7264 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7265 if(!strcmp(serial_devices[0], "vc"))
7266 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7267 "null");
7268 nographic = 1;
7269 break;
7270 case QEMU_OPTION_kernel:
7271 kernel_filename = optarg;
7272 break;
7273 case QEMU_OPTION_append:
7274 kernel_cmdline = optarg;
7275 break;
7276 #ifndef CONFIG_DM
7277 case QEMU_OPTION_cdrom:
7278 if (cdrom_index >= 0) {
7279 hd_filename[cdrom_index] = optarg;
7281 break;
7282 #endif /* !CONFIG_DM */
7283 case QEMU_OPTION_boot:
7284 boot_device = strdup(optarg);
7285 if (strspn(boot_device, "a"
7286 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7287 // Network boot
7288 "n"
7289 #endif
7290 "cd") != strlen(boot_device)) {
7291 fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7292 exit(1);
7294 break;
7295 case QEMU_OPTION_fda:
7296 fd_filename[0] = optarg;
7297 break;
7298 case QEMU_OPTION_fdb:
7299 fd_filename[1] = optarg;
7300 break;
7301 #ifdef TARGET_I386
7302 case QEMU_OPTION_no_fd_bootchk:
7303 fd_bootchk = 0;
7304 break;
7305 #endif
7306 #ifdef USE_CODE_COPY
7307 case QEMU_OPTION_no_code_copy:
7308 code_copy_enabled = 0;
7309 break;
7310 #endif
7311 case QEMU_OPTION_net:
7312 if (nb_net_clients >= MAX_NET_CLIENTS) {
7313 fprintf(stderr, "qemu: too many network clients\n");
7314 exit(1);
7316 pstrcpy(net_clients[nb_net_clients],
7317 sizeof(net_clients[0]),
7318 optarg);
7319 nb_net_clients++;
7320 break;
7321 #ifdef CONFIG_SLIRP
7322 case QEMU_OPTION_tftp:
7323 tftp_prefix = optarg;
7324 break;
7325 #ifndef _WIN32
7326 case QEMU_OPTION_smb:
7327 net_slirp_smb(optarg);
7328 break;
7329 #endif
7330 case QEMU_OPTION_redir:
7331 net_slirp_redir(optarg);
7332 break;
7333 #endif
7334 #ifdef HAS_AUDIO
7335 case QEMU_OPTION_audio_help:
7336 AUD_help ();
7337 exit (0);
7338 break;
7339 case QEMU_OPTION_soundhw:
7340 select_soundhw (optarg);
7341 break;
7342 #endif
7343 case QEMU_OPTION_h:
7344 help();
7345 break;
7346 case QEMU_OPTION_m:
7347 ram_size = atol(optarg) * 1024 * 1024;
7348 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7349 if (ram_size <= 0)
7350 help();
7351 #ifndef CONFIG_DM
7352 if (ram_size > PHYS_RAM_MAX_SIZE) {
7353 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7354 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7355 exit(1);
7357 #endif /* !CONFIG_DM */
7358 break;
7359 case QEMU_OPTION_l:
7361 int mask;
7362 CPULogItem *item;
7364 mask = cpu_str_to_log_mask(optarg);
7365 if (!mask) {
7366 printf("Log items (comma separated):\n");
7367 for(item = cpu_log_items; item->mask != 0; item++) {
7368 printf("%-10s %s\n", item->name, item->help);
7370 exit(1);
7372 cpu_set_log(mask);
7374 break;
7375 #ifdef CONFIG_GDBSTUB
7376 case QEMU_OPTION_s:
7377 use_gdbstub = 1;
7378 break;
7379 case QEMU_OPTION_p:
7380 gdbstub_port = atoi(optarg);
7381 break;
7382 #endif
7383 case QEMU_OPTION_L:
7384 bios_dir = optarg;
7385 break;
7386 case QEMU_OPTION_S:
7387 autostart = 0;
7388 break;
7389 case QEMU_OPTION_k:
7390 keyboard_layout = optarg;
7391 break;
7392 case QEMU_OPTION_localtime:
7393 rtc_utc = 0;
7394 break;
7395 case QEMU_OPTION_cirrusvga:
7396 cirrus_vga_enabled = 1;
7397 break;
7398 case QEMU_OPTION_std_vga:
7399 cirrus_vga_enabled = 0;
7400 break;
7401 case QEMU_OPTION_g:
7403 const char *p;
7404 int w, h, depth;
7405 p = optarg;
7406 w = strtol(p, (char **)&p, 10);
7407 if (w <= 0) {
7408 graphic_error:
7409 fprintf(stderr, "qemu: invalid resolution or depth\n");
7410 exit(1);
7412 if (*p != 'x')
7413 goto graphic_error;
7414 p++;
7415 h = strtol(p, (char **)&p, 10);
7416 if (h <= 0)
7417 goto graphic_error;
7418 if (*p == 'x') {
7419 p++;
7420 depth = strtol(p, (char **)&p, 10);
7421 if (depth != 8 && depth != 15 && depth != 16 &&
7422 depth != 24 && depth != 32)
7423 goto graphic_error;
7424 } else if (*p == '\0') {
7425 depth = graphic_depth;
7426 } else {
7427 goto graphic_error;
7430 graphic_width = w;
7431 graphic_height = h;
7432 graphic_depth = depth;
7434 break;
7435 case QEMU_OPTION_monitor:
7436 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7437 break;
7438 case QEMU_OPTION_serial:
7439 if (serial_device_index >= MAX_SERIAL_PORTS) {
7440 fprintf(stderr, "qemu: too many serial ports\n");
7441 exit(1);
7443 pstrcpy(serial_devices[serial_device_index],
7444 sizeof(serial_devices[0]), optarg);
7445 serial_device_index++;
7446 break;
7447 case QEMU_OPTION_parallel:
7448 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7449 fprintf(stderr, "qemu: too many parallel ports\n");
7450 exit(1);
7452 pstrcpy(parallel_devices[parallel_device_index],
7453 sizeof(parallel_devices[0]), optarg);
7454 parallel_device_index++;
7455 break;
7456 case QEMU_OPTION_loadvm:
7457 loadvm = optarg;
7458 break;
7459 case QEMU_OPTION_full_screen:
7460 full_screen = 1;
7461 break;
7462 #ifdef CONFIG_SDL
7463 case QEMU_OPTION_no_quit:
7464 no_quit = 1;
7465 break;
7466 #endif
7467 case QEMU_OPTION_pidfile:
7468 create_pidfile(optarg);
7469 break;
7470 #ifdef TARGET_I386
7471 case QEMU_OPTION_win2k_hack:
7472 win2k_install_hack = 1;
7473 break;
7474 #endif
7475 #ifdef USE_KQEMU
7476 case QEMU_OPTION_no_kqemu:
7477 kqemu_allowed = 0;
7478 break;
7479 case QEMU_OPTION_kernel_kqemu:
7480 kqemu_allowed = 2;
7481 break;
7482 #endif
7483 case QEMU_OPTION_usb:
7484 usb_enabled = 1;
7485 break;
7486 case QEMU_OPTION_usbdevice:
7487 usb_enabled = 1;
7488 if (usb_devices_index >= MAX_USB_CMDLINE) {
7489 fprintf(stderr, "Too many USB devices\n");
7490 exit(1);
7492 pstrcpy(usb_devices[usb_devices_index],
7493 sizeof(usb_devices[usb_devices_index]),
7494 optarg);
7495 usb_devices_index++;
7496 break;
7497 case QEMU_OPTION_smp:
7498 smp_cpus = atoi(optarg);
7499 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7500 fprintf(stderr, "Invalid number of CPUs\n");
7501 exit(1);
7503 break;
7504 case QEMU_OPTION_vnc:
7505 vnc_display = optarg;
7506 break;
7507 case QEMU_OPTION_no_acpi:
7508 acpi_enabled = 0;
7509 break;
7510 case QEMU_OPTION_no_reboot:
7511 no_reboot = 1;
7512 break;
7513 case QEMU_OPTION_daemonize:
7514 daemonize = 1;
7515 break;
7516 case QEMU_OPTION_option_rom:
7517 if (nb_option_roms >= MAX_OPTION_ROMS) {
7518 fprintf(stderr, "Too many option ROMs\n");
7519 exit(1);
7521 option_rom[nb_option_roms] = optarg;
7522 nb_option_roms++;
7523 break;
7524 case QEMU_OPTION_semihosting:
7525 semihosting_enabled = 1;
7526 break;
7527 case QEMU_OPTION_domainname:
7528 strncpy(domain_name, optarg, sizeof(domain_name));
7529 domain_name[sizeof(domain_name)-1] = '\0';
7530 break;
7531 case QEMU_OPTION_d:
7532 domid = atoi(optarg);
7533 fprintf(logfile, "domid: %d\n", domid);
7534 break;
7535 case QEMU_OPTION_vcpus:
7536 vcpus = atoi(optarg);
7537 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7538 break;
7539 case QEMU_OPTION_acpi:
7540 acpi_enabled = 1;
7541 break;
7542 case QEMU_OPTION_vncviewer:
7543 vncviewer++;
7544 break;
7545 case QEMU_OPTION_vncunused:
7546 vncunused++;
7547 break;
7552 /* Now send logs to our named config */
7553 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm-%s.log", domain_name);
7554 cpu_set_log_filename(qemu_dm_logfilename);
7556 #ifndef _WIN32
7557 if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7558 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7559 daemonize = 0;
7562 if (daemonize) {
7563 pid_t pid;
7565 if (pipe(fds) == -1)
7566 exit(1);
7568 pid = fork();
7569 if (pid > 0) {
7570 uint8_t status;
7571 ssize_t len;
7573 close(fds[1]);
7575 again:
7576 len = read(fds[0], &status, 1);
7577 if (len == -1 && (errno == EINTR))
7578 goto again;
7580 if (len != 1 || status != 0)
7581 exit(1);
7582 else
7583 exit(0);
7584 } else if (pid < 0)
7585 exit(1);
7587 setsid();
7589 pid = fork();
7590 if (pid > 0)
7591 exit(0);
7592 else if (pid < 0)
7593 exit(1);
7595 umask(027);
7596 chdir("/");
7598 signal(SIGTSTP, SIG_IGN);
7599 signal(SIGTTOU, SIG_IGN);
7600 signal(SIGTTIN, SIG_IGN);
7602 #endif
7604 #ifdef CONFIG_DM
7605 bdrv_init();
7606 xenstore_parse_domain_config(domid);
7607 #endif /* CONFIG_DM */
7609 #ifdef USE_KQEMU
7610 if (smp_cpus > 1)
7611 kqemu_allowed = 0;
7612 #endif
7613 linux_boot = (kernel_filename != NULL);
7615 #ifndef CONFIG_DM
7616 if (!linux_boot &&
7617 hd_filename[0] == '\0' &&
7618 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7619 fd_filename[0] == '\0')
7620 help();
7622 /* boot to floppy or the default cd if no hard disk defined yet */
7623 if (hd_filename[0] == '\0' && boot_device == 'c') {
7624 if (fd_filename[0] != '\0')
7625 boot_device = 'a';
7626 else
7627 boot_device = 'd';
7629 #endif /* !CONFIG_DM */
7631 setvbuf(stdout, NULL, _IOLBF, 0);
7633 init_timers();
7634 init_timer_alarm();
7635 qemu_aio_init();
7637 #ifdef _WIN32
7638 socket_init();
7639 #endif
7641 #ifndef CONFIG_DM
7642 /* init network clients */
7643 if (nb_net_clients == 0) {
7644 /* if no clients, we use a default config */
7645 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7646 "nic");
7647 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7648 "user");
7649 nb_net_clients = 2;
7651 #endif /* !CONFIG_DM */
7653 for(i = 0;i < nb_net_clients; i++) {
7654 if (net_client_init(net_clients[i]) < 0)
7655 exit(1);
7658 #ifndef CONFIG_DM
7659 #ifdef TARGET_I386
7660 if (boot_device == 'n') {
7661 for (i = 0; i < nb_nics; i++) {
7662 const char *model = nd_table[i].model;
7663 char buf[1024];
7664 if (model == NULL)
7665 model = "ne2k_pci";
7666 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7667 if (get_image_size(buf) > 0) {
7668 option_rom[nb_option_roms] = strdup(buf);
7669 nb_option_roms++;
7670 break;
7673 if (i == nb_nics) {
7674 fprintf(stderr, "No valid PXE rom found for network device\n");
7675 exit(1);
7677 boot_device = 'c'; /* to prevent confusion by the BIOS */
7679 #endif
7680 #endif /* !CONFIG_DM */
7682 #if defined (__ia64__)
7683 if (ram_size > MMIO_START)
7684 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
7685 #endif
7687 /* init the memory */
7688 phys_ram_size = ram_size + vga_ram_size + bios_size;
7690 #ifndef CONFIG_DM
7691 for (i = 0; i < nb_option_roms; i++) {
7692 int ret = get_image_size(option_rom[i]);
7693 if (ret == -1) {
7694 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7695 exit(1);
7697 phys_ram_size += ret;
7699 #endif /* !CONFIG_DM */
7701 #ifdef CONFIG_DM
7703 xc_handle = xc_interface_open();
7705 #if defined(__i386__) || defined(__x86_64__)
7707 if (qemu_map_cache_init()) {
7708 fprintf(logfile, "qemu_map_cache_init returned: error %d\n", errno);
7709 exit(-1);
7712 xc_get_hvm_param(xc_handle, domid, HVM_PARAM_IOREQ_PFN, &ioreq_pfn);
7713 fprintf(logfile, "shared page at pfn %lx\n", ioreq_pfn);
7714 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
7715 PROT_READ|PROT_WRITE, ioreq_pfn);
7716 if (shared_page == NULL) {
7717 fprintf(logfile, "map shared IO page returned error %d\n", errno);
7718 exit(-1);
7721 xc_get_hvm_param(xc_handle, domid, HVM_PARAM_BUFIOREQ_PFN, &ioreq_pfn);
7722 fprintf(logfile, "buffered io page at pfn %lx\n", ioreq_pfn);
7723 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
7724 PROT_READ|PROT_WRITE, ioreq_pfn);
7725 if (buffered_io_page == NULL) {
7726 fprintf(logfile, "map buffered IO page returned error %d\n", errno);
7727 exit(-1);
7730 #elif defined(__ia64__)
7732 nr_pages = ram_size/PAGE_SIZE;
7734 page_array = (xen_pfn_t *)malloc(nr_pages * sizeof(xen_pfn_t));
7735 if (page_array == NULL) {
7736 fprintf(logfile, "malloc returned error %d\n", errno);
7737 exit(-1);
7740 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
7741 PROT_READ|PROT_WRITE,
7742 IO_PAGE_START >> PAGE_SHIFT);
7744 buffered_io_page =xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
7745 PROT_READ|PROT_WRITE,
7746 BUFFER_IO_PAGE_START >> PAGE_SHIFT);
7748 buffered_pio_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
7749 PROT_READ|PROT_WRITE,
7750 BUFFER_PIO_PAGE_START >> PAGE_SHIFT);
7752 for (i = 0; i < nr_pages; i++)
7753 page_array[i] = i;
7755 /* VTI will not use memory between 3G~4G, so we just pass a legal pfn
7756 to make QEMU map continuous virtual memory space */
7757 if (ram_size > MMIO_START) {
7758 for (i = 0 ; i < (MEM_G >> PAGE_SHIFT); i++)
7759 page_array[(MMIO_START >> PAGE_SHIFT) + i] =
7760 (STORE_PAGE_START >> PAGE_SHIFT);
7763 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
7764 PROT_READ|PROT_WRITE,
7765 page_array, nr_pages);
7766 if (phys_ram_base == 0) {
7767 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
7768 exit(-1);
7770 free(page_array);
7771 #endif
7773 timeoffset_get();
7775 #else /* !CONFIG_DM */
7777 phys_ram_base = qemu_vmalloc(phys_ram_size);
7778 if (!phys_ram_base) {
7779 fprintf(stderr, "Could not allocate physical memory\n");
7780 exit(1);
7783 #endif /* !CONFIG_DM */
7785 #ifndef CONFIG_DM
7786 /* we always create the cdrom drive, even if no disk is there */
7787 bdrv_init();
7788 if (cdrom_index >= 0) {
7789 bs_table[cdrom_index] = bdrv_new("cdrom");
7790 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7793 /* open the virtual block devices */
7794 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
7795 if (hd_filename[i]) {
7796 if (!bs_table[i]) {
7797 char buf[64];
7798 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7799 bs_table[i] = bdrv_new(buf);
7801 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7802 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7803 hd_filename[i]);
7804 exit(1);
7806 if (i == 0 && cyls != 0) {
7807 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7808 bdrv_set_translation_hint(bs_table[i], translation);
7812 #endif /* !CONFIG_DM */
7814 /* we always create at least one floppy disk */
7815 fd_table[0] = bdrv_new("fda");
7816 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7818 for(i = 0; i < MAX_FD; i++) {
7819 if (fd_filename[i]) {
7820 if (!fd_table[i]) {
7821 char buf[64];
7822 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7823 fd_table[i] = bdrv_new(buf);
7824 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7826 if (fd_filename[i] != '\0') {
7827 if (bdrv_open(fd_table[i], fd_filename[i],
7828 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7829 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7830 fd_filename[i]);
7831 exit(1);
7837 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7838 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7840 init_ioports();
7842 /* read vncpasswd from xenstore */
7843 if (0 > xenstore_read_vncpasswd(domid))
7844 exit(1);
7846 /* terminal init */
7847 if (nographic) {
7848 dumb_display_init(ds);
7849 } else if (vnc_display != NULL || vncunused != 0) {
7850 int vnc_display_port;
7851 vnc_display_port = vnc_display_init(ds, vnc_display, vncunused);
7852 if (vncviewer)
7853 vnc_start_viewer(vnc_display_port);
7854 xenstore_write_vncport(vnc_display_port);
7855 } else {
7856 #if defined(CONFIG_SDL)
7857 sdl_display_init(ds, full_screen);
7858 #elif defined(CONFIG_COCOA)
7859 cocoa_display_init(ds, full_screen);
7860 #else
7861 dumb_display_init(ds);
7862 #endif
7865 monitor_hd = qemu_chr_open(monitor_device);
7866 if (!monitor_hd) {
7867 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7868 exit(1);
7870 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
7871 monitor_init(monitor_hd, !nographic);
7873 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7874 const char *devname = serial_devices[i];
7875 if (devname[0] != '\0' && strcmp(devname, "none")) {
7876 char buf[16];
7877 serial_hds[i] = qemu_chr_open(devname);
7878 if (!serial_hds[i]) {
7879 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7880 devname);
7881 exit(1);
7883 snprintf(buf, sizeof(buf), "/serial/%d", i);
7884 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
7885 if (i == 0) /* serial 0 is also called the console */
7886 store_dev_info(serial_devices[i], domid,
7887 serial_hds[i], "/console");
7888 if (!strcmp(devname, "vc"))
7889 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7893 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7894 const char *devname = parallel_devices[i];
7895 if (devname[0] != '\0' && strcmp(devname, "none")) {
7896 char buf[16];
7897 parallel_hds[i] = qemu_chr_open(devname);
7898 if (!parallel_hds[i]) {
7899 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7900 devname);
7901 exit(1);
7903 snprintf(buf, sizeof(buf), "/parallel/%d", i);
7904 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
7905 if (!strcmp(devname, "vc"))
7906 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7910 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
7912 machine->init(ram_size, vga_ram_size, boot_device,
7913 ds, fd_filename, snapshot,
7914 kernel_filename, kernel_cmdline, initrd_filename);
7915 free(boot_device);
7917 /* init USB devices */
7918 if (usb_enabled) {
7919 for(i = 0; i < usb_devices_index; i++) {
7920 if (usb_device_add(usb_devices[i]) < 0) {
7921 fprintf(stderr, "Warning: could not add USB device %s\n",
7922 usb_devices[i]);
7927 if (vnc_display == NULL && vncunused == 0) {
7928 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7929 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7932 #ifdef CONFIG_GDBSTUB
7933 if (use_gdbstub) {
7934 /* XXX: use standard host:port notation and modify options
7935 accordingly. */
7936 if (gdbserver_start_port(gdbstub_port) < 0) {
7937 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7938 gdbstub_port);
7939 exit(1);
7941 } else
7942 #endif
7943 if (loadvm)
7944 do_loadvm(loadvm);
7947 /* XXX: simplify init */
7948 read_passwords();
7949 if (autostart) {
7950 vm_start();
7954 if (daemonize) {
7955 uint8_t status = 0;
7956 ssize_t len;
7957 int fd;
7959 again1:
7960 len = write(fds[1], &status, 1);
7961 if (len == -1 && (errno == EINTR))
7962 goto again1;
7964 if (len != 1)
7965 exit(1);
7967 fd = open("/dev/null", O_RDWR);
7968 if (fd == -1)
7969 exit(1);
7971 dup2(fd, 0);
7972 dup2(fd, 1);
7973 dup2(fd, 2);
7975 close(fd);
7978 /* register signal for the suspend request when save */
7980 struct sigaction act;
7981 sigset_t set;
7982 act.sa_handler = suspend;
7983 act.sa_flags = SA_RESTART;
7984 sigemptyset(&act.sa_mask);
7986 sigaction(SIGUSR1, &act, NULL);
7988 /* control panel mask some signals when spawn qemu, need unmask here*/
7989 sigemptyset(&set);
7990 sigaddset(&set, SIGUSR1);
7991 sigaddset(&set, SIGTERM);
7992 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
7993 fprintf(stderr, "unblock signal fail, possible issue for HVM save!\n");
7997 main_loop();
7998 quit_timers();
7999 return 0;