ia64/xen-unstable

view tools/ioemu/vl.c @ 16638:28921e83000b

Fix master/slave handling in xenconsoled and qemu

Fix a number of problems with the pty handling:

- make openpty() implementation work on Solaris
- set raw on the slave fd, not the master, as the master doesn't
have a line discipline pushed on Solaris
- make sure we don't leak the slave fd returned from openpty()
- don't use the 'name' argument of openpty() as it's a security risk
- note behaviour of a zero read of the master on Solaris
- remove pointless tcget/setattr

Signed-off-by: John Levon <john.levon@sun.com>
Signed-off-by: Samuel Thibault <samuel.thibault@citrix.com>
author Keir Fraser <keir.fraser@citrix.com>
date Wed Dec 19 14:45:45 2007 +0000 (2007-12-19)
parents bf21e00155b7
children d0052f37363c
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 <stdlib.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <time.h>
31 #include <errno.h>
32 #include <sys/time.h>
33 #include <zlib.h>
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/poll.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <net/if.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
48 #endif
49 #if defined(__linux__) || defined(__Linux__)
50 #include <linux/if_tun.h>
51 #endif
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #ifdef _BSD
56 #include <sys/stat.h>
57 #ifndef _BSD
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #else
63 #ifndef __sun__
64 #include <pty.h>
65 #include <linux/rtc.h>
66 #include <linux/ppdev.h>
67 #endif
68 #endif
69 #if defined(__sun__)
70 #include <stropts.h>
71 #endif
72 #endif
74 #if defined(CONFIG_SLIRP)
75 #include "libslirp.h"
76 #endif
78 #ifdef _WIN32
79 #include <sys/timeb.h>
80 #include <windows.h>
81 #define getopt_long_only getopt_long
82 #define memalign(align, size) malloc(size)
83 #endif
85 #include "qemu_socket.h"
87 #ifdef CONFIG_SDL
88 #ifdef __APPLE__
89 #include <SDL/SDL.h>
90 #endif
91 #endif /* CONFIG_SDL */
93 #ifdef CONFIG_COCOA
94 #undef main
95 #define main qemu_main
96 #endif /* CONFIG_COCOA */
98 #include "disas.h"
100 #include "exec-all.h"
102 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
103 #ifdef _BSD
104 #define DEFAULT_BRIDGE "bridge0"
105 #else
106 #define DEFAULT_BRIDGE "xenbr0"
107 #endif
108 #ifdef __sun__
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110 #else
111 #define SMBD_COMMAND "/usr/sbin/smbd"
112 #endif
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
119 #ifdef TARGET_PPC
120 #define DEFAULT_RAM_SIZE 144
121 #else
122 #define DEFAULT_RAM_SIZE 128
123 #endif
124 /* in ms */
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
141 /* point to the block driver where the snapshots are managed */
142 BlockDriverState *bs_snapshots;
143 int vga_ram_size;
144 int bios_size;
145 static DisplayState display_state;
146 int nographic;
147 int vncviewer;
148 int vncunused;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 char *boot_device = NULL;
152 uint64_t ram_size;
153 int pit_min_timer_count = 0;
154 int nb_nics;
155 NICInfo nd_table[MAX_NICS];
156 QEMUTimer *gui_timer;
157 int vm_running;
158 int rtc_utc = 1;
159 int cirrus_vga_enabled = 1;
160 #ifdef TARGET_SPARC
161 int graphic_width = 1024;
162 int graphic_height = 768;
163 #else
164 int graphic_width = 800;
165 int graphic_height = 600;
166 #endif
167 int graphic_depth = 15;
168 int full_screen = 0;
169 int no_quit = 0;
170 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
171 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
172 #ifdef TARGET_I386
173 int win2k_install_hack = 0;
174 #endif
175 int usb_enabled = 0;
176 static VLANState *first_vlan;
177 int smp_cpus = 1;
178 const char *vnc_display;
179 #if defined(TARGET_SPARC)
180 #define MAX_CPUS 16
181 #elif defined(TARGET_I386)
182 #define MAX_CPUS 255
183 #else
184 #define MAX_CPUS 1
185 #endif
186 int acpi_enabled = 0;
187 int fd_bootchk = 1;
188 int no_reboot = 0;
189 int daemonize = 0;
190 const char *option_rom[MAX_OPTION_ROMS];
191 int nb_option_roms;
192 int semihosting_enabled = 0;
193 int autostart = 1;
195 extern int vcpus;
197 int xc_handle;
199 char domain_name[64] = "Xen-no-name";
200 extern int domid;
202 /***********************************************************/
203 /* x86 ISA bus support */
205 target_phys_addr_t isa_mem_base = 0;
206 PicState2 *isa_pic;
208 uint32_t default_ioport_readb(void *opaque, uint32_t address)
209 {
210 #ifdef DEBUG_UNUSED_IOPORT
211 fprintf(stderr, "inb: port=0x%04x\n", address);
212 #endif
213 return 0xff;
214 }
216 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
217 {
218 #ifdef DEBUG_UNUSED_IOPORT
219 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
220 #endif
221 }
223 /* default is to make two byte accesses */
224 uint32_t default_ioport_readw(void *opaque, uint32_t address)
225 {
226 uint32_t data;
227 data = ioport_read_table[0][address](ioport_opaque[address], address);
228 address = (address + 1) & (MAX_IOPORTS - 1);
229 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
230 return data;
231 }
233 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
234 {
235 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
236 address = (address + 1) & (MAX_IOPORTS - 1);
237 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
238 }
240 uint32_t default_ioport_readl(void *opaque, uint32_t address)
241 {
242 #ifdef DEBUG_UNUSED_IOPORT
243 fprintf(stderr, "inl: port=0x%04x\n", address);
244 #endif
245 return 0xffffffff;
246 }
248 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
249 {
250 #ifdef DEBUG_UNUSED_IOPORT
251 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
252 #endif
253 }
255 void init_ioports(void)
256 {
257 int i;
259 for(i = 0; i < MAX_IOPORTS; i++) {
260 ioport_read_table[0][i] = default_ioport_readb;
261 ioport_write_table[0][i] = default_ioport_writeb;
262 ioport_read_table[1][i] = default_ioport_readw;
263 ioport_write_table[1][i] = default_ioport_writew;
264 ioport_read_table[2][i] = default_ioport_readl;
265 ioport_write_table[2][i] = default_ioport_writel;
266 }
267 }
269 /* size is the word size in byte */
270 int register_ioport_read(int start, int length, int size,
271 IOPortReadFunc *func, void *opaque)
272 {
273 int i, bsize;
275 if (size == 1) {
276 bsize = 0;
277 } else if (size == 2) {
278 bsize = 1;
279 } else if (size == 4) {
280 bsize = 2;
281 } else {
282 hw_error("register_ioport_read: invalid size");
283 return -1;
284 }
285 for(i = start; i < start + length; i += size) {
286 ioport_read_table[bsize][i] = func;
287 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
288 hw_error("register_ioport_write: invalid opaque");
289 ioport_opaque[i] = opaque;
290 }
291 return 0;
292 }
294 /* size is the word size in byte */
295 int register_ioport_write(int start, int length, int size,
296 IOPortWriteFunc *func, void *opaque)
297 {
298 int i, bsize;
300 if (size == 1) {
301 bsize = 0;
302 } else if (size == 2) {
303 bsize = 1;
304 } else if (size == 4) {
305 bsize = 2;
306 } else {
307 hw_error("register_ioport_write: invalid size");
308 return -1;
309 }
310 for(i = start; i < start + length; i += size) {
311 ioport_write_table[bsize][i] = func;
312 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
313 hw_error("register_ioport_write: invalid opaque");
314 ioport_opaque[i] = opaque;
315 }
316 return 0;
317 }
319 void isa_unassign_ioport(int start, int length)
320 {
321 int i;
323 for(i = start; i < start + length; i++) {
324 ioport_read_table[0][i] = default_ioport_readb;
325 ioport_read_table[1][i] = default_ioport_readw;
326 ioport_read_table[2][i] = default_ioport_readl;
328 ioport_write_table[0][i] = default_ioport_writeb;
329 ioport_write_table[1][i] = default_ioport_writew;
330 ioport_write_table[2][i] = default_ioport_writel;
331 }
332 }
334 /***********************************************************/
336 void cpu_outb(CPUState *env, int addr, int val)
337 {
338 #ifdef DEBUG_IOPORT
339 if (loglevel & CPU_LOG_IOPORT)
340 fprintf(logfile, "outb: %04x %02x\n", addr, val);
341 #endif
342 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
343 #ifdef USE_KQEMU
344 if (env)
345 env->last_io_time = cpu_get_time_fast();
346 #endif
347 }
349 void cpu_outw(CPUState *env, int addr, int val)
350 {
351 #ifdef DEBUG_IOPORT
352 if (loglevel & CPU_LOG_IOPORT)
353 fprintf(logfile, "outw: %04x %04x\n", addr, val);
354 #endif
355 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
356 #ifdef USE_KQEMU
357 if (env)
358 env->last_io_time = cpu_get_time_fast();
359 #endif
360 }
362 void cpu_outl(CPUState *env, int addr, int val)
363 {
364 #ifdef DEBUG_IOPORT
365 if (loglevel & CPU_LOG_IOPORT)
366 fprintf(logfile, "outl: %04x %08x\n", addr, val);
367 #endif
368 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
369 #ifdef USE_KQEMU
370 if (env)
371 env->last_io_time = cpu_get_time_fast();
372 #endif
373 }
375 int cpu_inb(CPUState *env, int addr)
376 {
377 int val;
378 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
379 #ifdef DEBUG_IOPORT
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "inb : %04x %02x\n", addr, val);
382 #endif
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
387 return val;
388 }
390 int cpu_inw(CPUState *env, int addr)
391 {
392 int val;
393 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
394 #ifdef DEBUG_IOPORT
395 if (loglevel & CPU_LOG_IOPORT)
396 fprintf(logfile, "inw : %04x %04x\n", addr, val);
397 #endif
398 #ifdef USE_KQEMU
399 if (env)
400 env->last_io_time = cpu_get_time_fast();
401 #endif
402 return val;
403 }
405 int cpu_inl(CPUState *env, int addr)
406 {
407 int val;
408 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "inl : %04x %08x\n", addr, val);
412 #endif
413 #ifdef USE_KQEMU
414 if (env)
415 env->last_io_time = cpu_get_time_fast();
416 #endif
417 return val;
418 }
420 /***********************************************************/
421 void hw_error(const char *fmt, ...)
422 {
423 va_list ap;
424 #ifndef CONFIG_DM
425 CPUState *env;
426 #endif /* !CONFIG_DM */
428 va_start(ap, fmt);
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 #ifndef CONFIG_DM
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 #ifdef TARGET_I386
436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 #else
438 cpu_dump_state(env, stderr, fprintf, 0);
439 #endif
440 }
441 #endif /* !CONFIG_DM */
442 va_end(ap);
443 abort();
444 }
446 /***********************************************************/
447 /* keyboard/mouse */
449 static QEMUPutKBDEvent *qemu_put_kbd_event;
450 static void *qemu_put_kbd_event_opaque;
451 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
452 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
454 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
455 {
456 qemu_put_kbd_event_opaque = opaque;
457 qemu_put_kbd_event = func;
458 }
460 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
461 void *opaque, int absolute,
462 const char *name)
463 {
464 QEMUPutMouseEntry *s, *cursor;
466 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
467 if (!s)
468 return NULL;
470 s->qemu_put_mouse_event = func;
471 s->qemu_put_mouse_event_opaque = opaque;
472 s->qemu_put_mouse_event_absolute = absolute;
473 s->qemu_put_mouse_event_name = qemu_strdup(name);
474 s->next = NULL;
476 if (!qemu_put_mouse_event_head) {
477 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
478 return s;
479 }
481 cursor = qemu_put_mouse_event_head;
482 while (cursor->next != NULL)
483 cursor = cursor->next;
485 cursor->next = s;
486 qemu_put_mouse_event_current = s;
488 return s;
489 }
491 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
492 {
493 QEMUPutMouseEntry *prev = NULL, *cursor;
495 if (!qemu_put_mouse_event_head || entry == NULL)
496 return;
498 cursor = qemu_put_mouse_event_head;
499 while (cursor != NULL && cursor != entry) {
500 prev = cursor;
501 cursor = cursor->next;
502 }
504 if (cursor == NULL) // does not exist or list empty
505 return;
506 else if (prev == NULL) { // entry is head
507 qemu_put_mouse_event_head = cursor->next;
508 if (qemu_put_mouse_event_current == entry)
509 qemu_put_mouse_event_current = cursor->next;
510 qemu_free(entry->qemu_put_mouse_event_name);
511 qemu_free(entry);
512 return;
513 }
515 prev->next = entry->next;
517 if (qemu_put_mouse_event_current == entry)
518 qemu_put_mouse_event_current = prev;
520 qemu_free(entry->qemu_put_mouse_event_name);
521 qemu_free(entry);
522 }
524 void kbd_put_keycode(int keycode)
525 {
526 if (qemu_put_kbd_event) {
527 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
528 }
529 }
531 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
532 {
533 QEMUPutMouseEvent *mouse_event;
534 void *mouse_event_opaque;
536 if (!qemu_put_mouse_event_current) {
537 return;
538 }
540 mouse_event =
541 qemu_put_mouse_event_current->qemu_put_mouse_event;
542 mouse_event_opaque =
543 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
545 if (mouse_event) {
546 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
547 }
548 }
550 int kbd_mouse_is_absolute(void)
551 {
552 if (!qemu_put_mouse_event_current)
553 return 0;
555 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
556 }
558 void do_info_mice(void)
559 {
560 QEMUPutMouseEntry *cursor;
561 int index = 0;
563 if (!qemu_put_mouse_event_head) {
564 term_printf("No mouse devices connected\n");
565 return;
566 }
568 term_printf("Mouse devices available:\n");
569 cursor = qemu_put_mouse_event_head;
570 while (cursor != NULL) {
571 term_printf("%c Mouse #%d: %s\n",
572 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
573 index, cursor->qemu_put_mouse_event_name);
574 index++;
575 cursor = cursor->next;
576 }
577 }
579 void do_mouse_set(int index)
580 {
581 QEMUPutMouseEntry *cursor;
582 int i = 0;
584 if (!qemu_put_mouse_event_head) {
585 term_printf("No mouse devices connected\n");
586 return;
587 }
589 cursor = qemu_put_mouse_event_head;
590 while (cursor != NULL && index != i) {
591 i++;
592 cursor = cursor->next;
593 }
595 if (cursor != NULL)
596 qemu_put_mouse_event_current = cursor;
597 else
598 term_printf("Mouse at given index not found\n");
599 }
601 /* compute with 96 bit intermediate result: (a*b)/c */
602 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
603 {
604 union {
605 uint64_t ll;
606 struct {
607 #ifdef WORDS_BIGENDIAN
608 uint32_t high, low;
609 #else
610 uint32_t low, high;
611 #endif
612 } l;
613 } u, res;
614 uint64_t rl, rh;
616 u.ll = a;
617 rl = (uint64_t)u.l.low * (uint64_t)b;
618 rh = (uint64_t)u.l.high * (uint64_t)b;
619 rh += (rl >> 32);
620 res.l.high = rh / c;
621 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
622 return res.ll;
623 }
625 /***********************************************************/
626 /* real time host monotonic timer */
628 #define QEMU_TIMER_BASE 1000000000LL
630 #ifdef WIN32
632 static int64_t clock_freq;
634 static void init_get_clock(void)
635 {
636 LARGE_INTEGER freq;
637 int ret;
638 ret = QueryPerformanceFrequency(&freq);
639 if (ret == 0) {
640 fprintf(stderr, "Could not calibrate ticks\n");
641 exit(1);
642 }
643 clock_freq = freq.QuadPart;
644 }
646 static int64_t get_clock(void)
647 {
648 LARGE_INTEGER ti;
649 QueryPerformanceCounter(&ti);
650 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
651 }
653 #else
655 static int use_rt_clock;
657 static void init_get_clock(void)
658 {
659 use_rt_clock = 0;
660 #if defined(__linux__)
661 {
662 struct timespec ts;
663 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
664 use_rt_clock = 1;
665 }
666 }
667 #endif
668 }
670 static int64_t get_clock(void)
671 {
672 #if defined(__linux__)
673 if (use_rt_clock) {
674 struct timespec ts;
675 clock_gettime(CLOCK_MONOTONIC, &ts);
676 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
677 } else
678 #endif
679 {
680 /* XXX: using gettimeofday leads to problems if the date
681 changes, so it should be avoided. */
682 struct timeval tv;
683 gettimeofday(&tv, NULL);
684 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
685 }
686 }
688 #endif
690 /***********************************************************/
691 /* guest cycle counter */
693 static int64_t cpu_ticks_prev;
694 static int64_t cpu_ticks_offset;
695 static int64_t cpu_clock_offset;
696 static int cpu_ticks_enabled;
698 /* return the host CPU cycle counter and handle stop/restart */
699 int64_t cpu_get_ticks(void)
700 {
701 if (!cpu_ticks_enabled) {
702 return cpu_ticks_offset;
703 } else {
704 int64_t ticks;
705 ticks = cpu_get_real_ticks();
706 if (cpu_ticks_prev > ticks) {
707 /* Note: non increasing ticks may happen if the host uses
708 software suspend */
709 cpu_ticks_offset += cpu_ticks_prev - ticks;
710 }
711 cpu_ticks_prev = ticks;
712 return ticks + cpu_ticks_offset;
713 }
714 }
716 /* return the host CPU monotonic timer and handle stop/restart */
717 static int64_t cpu_get_clock(void)
718 {
719 int64_t ti;
720 if (!cpu_ticks_enabled) {
721 return cpu_clock_offset;
722 } else {
723 ti = get_clock();
724 return ti + cpu_clock_offset;
725 }
726 }
728 /* enable cpu_get_ticks() */
729 void cpu_enable_ticks(void)
730 {
731 if (!cpu_ticks_enabled) {
732 cpu_ticks_offset -= cpu_get_real_ticks();
733 cpu_clock_offset -= get_clock();
734 cpu_ticks_enabled = 1;
735 }
736 }
738 /* disable cpu_get_ticks() : the clock is stopped. You must not call
739 cpu_get_ticks() after that. */
740 void cpu_disable_ticks(void)
741 {
742 if (cpu_ticks_enabled) {
743 cpu_ticks_offset = cpu_get_ticks();
744 cpu_clock_offset = cpu_get_clock();
745 cpu_ticks_enabled = 0;
746 }
747 }
749 /***********************************************************/
750 /* timers */
752 #define QEMU_TIMER_REALTIME 0
753 #define QEMU_TIMER_VIRTUAL 1
755 struct QEMUClock {
756 int type;
757 /* XXX: add frequency */
758 };
760 struct QEMUTimer {
761 QEMUClock *clock;
762 int64_t expire_time;
763 QEMUTimerCB *cb;
764 void *opaque;
765 struct QEMUTimer *next;
766 };
768 QEMUClock *rt_clock;
769 QEMUClock *vm_clock;
771 static QEMUTimer *active_timers[2];
772 #ifdef _WIN32
773 static MMRESULT timerID;
774 static HANDLE host_alarm = NULL;
775 static unsigned int period = 1;
776 #else
777 /* frequency of the times() clock tick */
778 static int timer_freq;
779 #endif
781 QEMUClock *qemu_new_clock(int type)
782 {
783 QEMUClock *clock;
784 clock = qemu_mallocz(sizeof(QEMUClock));
785 if (!clock)
786 return NULL;
787 clock->type = type;
788 return clock;
789 }
791 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
792 {
793 QEMUTimer *ts;
795 ts = qemu_mallocz(sizeof(QEMUTimer));
796 ts->clock = clock;
797 ts->cb = cb;
798 ts->opaque = opaque;
799 return ts;
800 }
802 void qemu_free_timer(QEMUTimer *ts)
803 {
804 qemu_free(ts);
805 }
807 /* stop a timer, but do not dealloc it */
808 void qemu_del_timer(QEMUTimer *ts)
809 {
810 QEMUTimer **pt, *t;
812 /* NOTE: this code must be signal safe because
813 qemu_timer_expired() can be called from a signal. */
814 pt = &active_timers[ts->clock->type];
815 for(;;) {
816 t = *pt;
817 if (!t)
818 break;
819 if (t == ts) {
820 *pt = t->next;
821 break;
822 }
823 pt = &t->next;
824 }
825 }
827 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
828 {
829 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
830 qemu_mod_timer(ts, expire_time);
831 }
833 /* modify the current timer so that it will be fired when current_time
834 >= expire_time. The corresponding callback will be called. */
835 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
836 {
837 QEMUTimer **pt, *t;
839 qemu_del_timer(ts);
841 /* add the timer in the sorted list */
842 /* NOTE: this code must be signal safe because
843 qemu_timer_expired() can be called from a signal. */
844 pt = &active_timers[ts->clock->type];
845 for(;;) {
846 t = *pt;
847 if (!t)
848 break;
849 if (t->expire_time > expire_time)
850 break;
851 pt = &t->next;
852 }
853 ts->expire_time = expire_time;
854 ts->next = *pt;
855 *pt = ts;
856 }
858 int qemu_timer_pending(QEMUTimer *ts)
859 {
860 QEMUTimer *t;
861 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
862 if (t == ts)
863 return 1;
864 }
865 return 0;
866 }
868 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
869 {
870 if (!timer_head)
871 return 0;
872 return (timer_head->expire_time <= current_time);
873 }
875 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
876 {
877 QEMUTimer *ts;
879 for(;;) {
880 ts = *ptimer_head;
881 if (!ts || ts->expire_time > current_time)
882 break;
883 /* remove timer from the list before calling the callback */
884 *ptimer_head = ts->next;
885 ts->next = NULL;
887 /* run the callback (the timer list can be modified) */
888 ts->cb(ts->opaque);
889 }
890 }
892 int64_t qemu_get_clock(QEMUClock *clock)
893 {
894 switch(clock->type) {
895 case QEMU_TIMER_REALTIME:
896 return get_clock() / 1000000;
897 default:
898 case QEMU_TIMER_VIRTUAL:
899 return cpu_get_clock();
900 }
901 }
903 static void init_timers(void)
904 {
905 init_get_clock();
906 ticks_per_sec = QEMU_TIMER_BASE;
907 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
908 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
909 }
911 /* save a timer */
912 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
913 {
914 uint64_t expire_time;
916 if (qemu_timer_pending(ts)) {
917 expire_time = ts->expire_time;
918 } else {
919 expire_time = -1;
920 }
921 qemu_put_be64(f, expire_time);
922 }
924 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
925 {
926 uint64_t expire_time;
928 expire_time = qemu_get_be64(f);
929 if (expire_time != -1) {
930 qemu_mod_timer(ts, expire_time);
931 } else {
932 qemu_del_timer(ts);
933 }
934 }
936 #ifdef CONFIG_DM
937 static void timer_save(QEMUFile *f, void *opaque)
938 {
939 /* need timer for save/restoe qemu_timer in usb_uhci */
940 if (cpu_ticks_enabled) {
941 hw_error("cannot save state if virtual timers are running");
942 }
943 qemu_put_be64s(f, &cpu_clock_offset);
944 }
946 static int timer_load(QEMUFile *f, void *opaque, int version_id)
947 {
948 if (version_id != 1 && version_id != 2)
949 return -EINVAL;
950 if (cpu_ticks_enabled) {
951 return -EINVAL;
952 }
954 qemu_get_be64s(f, &cpu_clock_offset);
955 return 0;
956 }
957 #else /* !CONFIG_DM */
958 static void timer_save(QEMUFile *f, void *opaque)
959 {
960 if (cpu_ticks_enabled) {
961 hw_error("cannot save state if virtual timers are running");
962 }
963 qemu_put_be64s(f, &cpu_ticks_offset);
964 qemu_put_be64s(f, &ticks_per_sec);
965 qemu_put_be64s(f, &cpu_clock_offset);
966 }
968 static int timer_load(QEMUFile *f, void *opaque, int version_id)
969 {
970 if (version_id != 1 && version_id != 2)
971 return -EINVAL;
972 if (cpu_ticks_enabled) {
973 return -EINVAL;
974 }
975 qemu_get_be64s(f, &cpu_ticks_offset);
976 qemu_get_be64s(f, &ticks_per_sec);
977 if (version_id == 2) {
978 qemu_get_be64s(f, &cpu_clock_offset);
979 }
980 return 0;
981 }
983 #ifdef _WIN32
984 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
985 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
986 #else
987 static void host_alarm_handler(int host_signum)
988 #endif
989 {
990 #if 0
991 #define DISP_FREQ 1000
992 {
993 static int64_t delta_min = INT64_MAX;
994 static int64_t delta_max, delta_cum, last_clock, delta, ti;
995 static int count;
996 ti = qemu_get_clock(vm_clock);
997 if (last_clock != 0) {
998 delta = ti - last_clock;
999 if (delta < delta_min)
1000 delta_min = delta;
1001 if (delta > delta_max)
1002 delta_max = delta;
1003 delta_cum += delta;
1004 if (++count == DISP_FREQ) {
1005 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1006 muldiv64(delta_min, 1000000, ticks_per_sec),
1007 muldiv64(delta_max, 1000000, ticks_per_sec),
1008 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1009 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1010 count = 0;
1011 delta_min = INT64_MAX;
1012 delta_max = 0;
1013 delta_cum = 0;
1016 last_clock = ti;
1018 #endif
1019 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1020 qemu_get_clock(vm_clock)) ||
1021 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1022 qemu_get_clock(rt_clock))) {
1023 #ifdef _WIN32
1024 SetEvent(host_alarm);
1025 #endif
1026 CPUState *env = cpu_single_env;
1027 if (env) {
1028 /* stop the currently executing cpu because a timer occured */
1029 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1030 #ifdef USE_KQEMU
1031 if (env->kqemu_enabled) {
1032 kqemu_cpu_interrupt(env);
1034 #endif
1039 #ifndef _WIN32
1041 #if defined(__linux__)
1043 #define RTC_FREQ 1024
1045 static int rtc_fd;
1047 static int start_rtc_timer(void)
1049 rtc_fd = open("/dev/rtc", O_RDONLY);
1050 if (rtc_fd < 0)
1051 return -1;
1052 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1053 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1054 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1055 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1056 goto fail;
1058 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1059 fail:
1060 close(rtc_fd);
1061 return -1;
1063 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1064 return 0;
1067 #else
1069 static int start_rtc_timer(void)
1071 return -1;
1074 #endif /* !defined(__linux__) */
1076 #endif /* !defined(_WIN32) */
1078 #endif /* !CONFIG_DM */
1080 static void init_timer_alarm(void)
1082 #ifdef _WIN32
1084 int count=0;
1085 TIMECAPS tc;
1087 ZeroMemory(&tc, sizeof(TIMECAPS));
1088 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1089 if (period < tc.wPeriodMin)
1090 period = tc.wPeriodMin;
1091 timeBeginPeriod(period);
1092 timerID = timeSetEvent(1, // interval (ms)
1093 period, // resolution
1094 host_alarm_handler, // function
1095 (DWORD)&count, // user parameter
1096 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1097 if( !timerID ) {
1098 perror("failed timer alarm");
1099 exit(1);
1101 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1102 if (!host_alarm) {
1103 perror("failed CreateEvent");
1104 exit(1);
1106 qemu_add_wait_object(host_alarm, NULL, NULL);
1108 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1109 #else
1111 #ifndef CONFIG_DM
1112 struct sigaction act;
1113 struct itimerval itv;
1114 #endif
1116 /* get times() syscall frequency */
1117 timer_freq = sysconf(_SC_CLK_TCK);
1119 #ifndef CONFIG_DM
1120 /* timer signal */
1121 sigfillset(&act.sa_mask);
1122 act.sa_flags = 0;
1123 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1124 act.sa_flags |= SA_ONSTACK;
1125 #endif
1126 act.sa_handler = host_alarm_handler;
1127 sigaction(SIGALRM, &act, NULL);
1129 itv.it_interval.tv_sec = 0;
1130 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1131 itv.it_value.tv_sec = 0;
1132 itv.it_value.tv_usec = 10 * 1000;
1133 setitimer(ITIMER_REAL, &itv, NULL);
1134 /* we probe the tick duration of the kernel to inform the user if
1135 the emulated kernel requested a too high timer frequency */
1136 getitimer(ITIMER_REAL, &itv);
1138 #if defined(__linux__)
1139 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1140 have timers with 1 ms resolution. The correct solution will
1141 be to use the POSIX real time timers available in recent
1142 2.6 kernels */
1143 if (itv.it_interval.tv_usec > 1000 || 1) {
1144 /* try to use /dev/rtc to have a faster timer */
1145 if (start_rtc_timer() < 0)
1146 goto use_itimer;
1147 /* disable itimer */
1148 itv.it_interval.tv_sec = 0;
1149 itv.it_interval.tv_usec = 0;
1150 itv.it_value.tv_sec = 0;
1151 itv.it_value.tv_usec = 0;
1152 setitimer(ITIMER_REAL, &itv, NULL);
1154 /* use the RTC */
1155 sigaction(SIGIO, &act, NULL);
1156 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1157 fcntl(rtc_fd, F_SETOWN, getpid());
1158 } else
1159 #endif /* defined(__linux__) */
1161 use_itimer:
1162 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1163 PIT_FREQ) / 1000000;
1165 #endif /* CONFIG_DM */
1167 #endif
1170 void quit_timers(void)
1172 #ifdef _WIN32
1173 timeKillEvent(timerID);
1174 timeEndPeriod(period);
1175 if (host_alarm) {
1176 CloseHandle(host_alarm);
1177 host_alarm = NULL;
1179 #endif
1182 /***********************************************************/
1183 /* character device */
1185 static void qemu_chr_event(CharDriverState *s, int event)
1187 if (!s->chr_event)
1188 return;
1189 s->chr_event(s->handler_opaque, event);
1192 static void qemu_chr_reset_bh(void *opaque)
1194 CharDriverState *s = opaque;
1195 qemu_chr_event(s, CHR_EVENT_RESET);
1196 qemu_bh_delete(s->bh);
1197 s->bh = NULL;
1200 void qemu_chr_reset(CharDriverState *s)
1202 if (s->bh == NULL) {
1203 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1204 qemu_bh_schedule(s->bh);
1208 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1210 return s->chr_write(s, buf, len);
1213 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1215 if (!s->chr_ioctl)
1216 return -ENOTSUP;
1217 return s->chr_ioctl(s, cmd, arg);
1220 int qemu_chr_can_read(CharDriverState *s)
1222 if (!s->chr_can_read)
1223 return 0;
1224 return s->chr_can_read(s->handler_opaque);
1227 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1229 s->chr_read(s->handler_opaque, buf, len);
1233 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1235 char buf[4096];
1236 va_list ap;
1237 va_start(ap, fmt);
1238 vsnprintf(buf, sizeof(buf), fmt, ap);
1239 qemu_chr_write(s, buf, strlen(buf));
1240 va_end(ap);
1243 void qemu_chr_send_event(CharDriverState *s, int event)
1245 if (s->chr_send_event)
1246 s->chr_send_event(s, event);
1249 void qemu_chr_add_handlers(CharDriverState *s,
1250 IOCanRWHandler *fd_can_read,
1251 IOReadHandler *fd_read,
1252 IOEventHandler *fd_event,
1253 void *opaque)
1255 s->chr_can_read = fd_can_read;
1256 s->chr_read = fd_read;
1257 s->chr_event = fd_event;
1258 s->handler_opaque = opaque;
1259 if (s->chr_update_read_handler)
1260 s->chr_update_read_handler(s);
1263 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1265 return len;
1268 static CharDriverState *qemu_chr_open_null(void)
1270 CharDriverState *chr;
1272 chr = qemu_mallocz(sizeof(CharDriverState));
1273 if (!chr)
1274 return NULL;
1275 chr->chr_write = null_chr_write;
1276 return chr;
1279 #ifdef _WIN32
1281 static void socket_cleanup(void)
1283 WSACleanup();
1286 static int socket_init(void)
1288 WSADATA Data;
1289 int ret, err;
1291 ret = WSAStartup(MAKEWORD(2,2), &Data);
1292 if (ret != 0) {
1293 err = WSAGetLastError();
1294 fprintf(stderr, "WSAStartup: %d\n", err);
1295 return -1;
1297 atexit(socket_cleanup);
1298 return 0;
1301 static int send_all(int fd, const uint8_t *buf, int len1)
1303 int ret, len;
1305 len = len1;
1306 while (len > 0) {
1307 ret = send(fd, buf, len, 0);
1308 if (ret < 0) {
1309 int errno;
1310 errno = WSAGetLastError();
1311 if (errno != WSAEWOULDBLOCK) {
1312 return -1;
1314 } else if (ret == 0) {
1315 break;
1316 } else {
1317 buf += ret;
1318 len -= ret;
1321 return len1 - len;
1324 void socket_set_nonblock(int fd)
1326 unsigned long opt = 1;
1327 ioctlsocket(fd, FIONBIO, &opt);
1330 #else
1332 static int unix_write(int fd, const uint8_t *buf, int len1)
1334 int ret, sel_ret, len;
1335 int max_fd;
1336 fd_set writefds;
1337 struct timeval timeout;
1339 max_fd = fd;
1341 len = len1;
1342 while (len > 0) {
1343 FD_ZERO(&writefds);
1344 FD_SET(fd, &writefds);
1345 timeout.tv_sec = 0;
1346 timeout.tv_usec = 0;
1347 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1348 if (sel_ret <= 0) {
1349 /* Timeout or select error */
1350 return -1;
1351 } else {
1352 ret = write(fd, buf, len);
1353 if (ret < 0) {
1354 if (errno != EINTR && errno != EAGAIN)
1355 return -1;
1356 } else if (ret == 0) {
1357 break;
1358 } else {
1359 buf += ret;
1360 len -= ret;
1364 return len1 - len;
1367 static inline int send_all(int fd, const uint8_t *buf, int len1)
1369 return unix_write(fd, buf, len1);
1372 void socket_set_nonblock(int fd)
1374 fcntl(fd, F_SETFL, O_NONBLOCK);
1376 #endif /* !_WIN32 */
1378 #ifndef _WIN32
1380 typedef struct {
1381 int fd_in, fd_out;
1382 int max_size;
1383 } FDCharDriver;
1385 #define STDIO_MAX_CLIENTS 2
1387 static int stdio_nb_clients;
1388 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1390 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1392 FDCharDriver *s = chr->opaque;
1393 return unix_write(s->fd_out, buf, len);
1396 static int fd_chr_read_poll(void *opaque)
1398 CharDriverState *chr = opaque;
1399 FDCharDriver *s = chr->opaque;
1401 s->max_size = qemu_chr_can_read(chr);
1402 return s->max_size;
1405 static void fd_chr_read(void *opaque)
1407 CharDriverState *chr = opaque;
1408 FDCharDriver *s = chr->opaque;
1409 int size, len;
1410 uint8_t buf[1024];
1412 len = sizeof(buf);
1413 if (len > s->max_size)
1414 len = s->max_size;
1415 if (len == 0)
1416 return;
1417 size = read(s->fd_in, buf, len);
1418 if (size == 0) {
1419 /* FD has been closed. Remove it from the active list. */
1420 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1421 return;
1423 if (size > 0) {
1424 qemu_chr_read(chr, buf, size);
1428 static void fd_chr_update_read_handler(CharDriverState *chr)
1430 FDCharDriver *s = chr->opaque;
1432 if (s->fd_in >= 0) {
1433 if (nographic && s->fd_in == 0) {
1434 } else {
1435 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1436 fd_chr_read, NULL, chr);
1441 /* open a character device to a unix fd */
1442 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1444 CharDriverState *chr;
1445 FDCharDriver *s;
1447 chr = qemu_mallocz(sizeof(CharDriverState));
1448 if (!chr)
1449 return NULL;
1450 s = qemu_mallocz(sizeof(FDCharDriver));
1451 if (!s) {
1452 free(chr);
1453 return NULL;
1455 s->fd_in = fd_in;
1456 s->fd_out = fd_out;
1457 chr->opaque = s;
1458 chr->chr_write = fd_chr_write;
1459 chr->chr_update_read_handler = fd_chr_update_read_handler;
1461 qemu_chr_reset(chr);
1463 return chr;
1466 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1468 int fd_out;
1470 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1471 if (fd_out < 0)
1472 return NULL;
1473 return qemu_chr_open_fd(-1, fd_out);
1476 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1478 int fd_in, fd_out;
1479 char filename_in[256], filename_out[256];
1481 snprintf(filename_in, 256, "%s.in", filename);
1482 snprintf(filename_out, 256, "%s.out", filename);
1483 fd_in = open(filename_in, O_RDWR | O_BINARY);
1484 fd_out = open(filename_out, O_RDWR | O_BINARY);
1485 if (fd_in < 0 || fd_out < 0) {
1486 if (fd_in >= 0)
1487 close(fd_in);
1488 if (fd_out >= 0)
1489 close(fd_out);
1490 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1491 if (fd_in < 0)
1492 return NULL;
1494 return qemu_chr_open_fd(fd_in, fd_out);
1498 /* for STDIO, we handle the case where several clients use it
1499 (nographic mode) */
1501 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1503 #define TERM_FIFO_MAX_SIZE 1
1505 static int term_got_escape, client_index;
1506 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1507 static int term_fifo_size;
1508 static int term_timestamps;
1509 static int64_t term_timestamps_start;
1511 void term_print_help(void)
1513 printf("\n"
1514 "C-a h print this help\n"
1515 "C-a x exit emulator\n"
1516 "C-a s save disk data back to file (if -snapshot)\n"
1517 "C-a b send break (magic sysrq)\n"
1518 "C-a t toggle console timestamps\n"
1519 "C-a c switch between console and monitor\n"
1520 "C-a C-a send C-a\n"
1521 );
1524 /* called when a char is received */
1525 static void stdio_received_byte(int ch)
1527 if (term_got_escape) {
1528 term_got_escape = 0;
1529 switch(ch) {
1530 case 'h':
1531 term_print_help();
1532 break;
1533 case 'x':
1534 exit(0);
1535 break;
1536 case 's':
1538 int i;
1539 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1540 if (bs_table[i])
1541 bdrv_commit(bs_table[i]);
1544 break;
1545 case 'b':
1546 if (client_index < stdio_nb_clients) {
1547 CharDriverState *chr;
1548 FDCharDriver *s;
1550 chr = stdio_clients[client_index];
1551 s = chr->opaque;
1552 qemu_chr_event(chr, CHR_EVENT_BREAK);
1554 break;
1555 case 'c':
1556 client_index++;
1557 if (client_index >= stdio_nb_clients)
1558 client_index = 0;
1559 if (client_index == 0) {
1560 /* send a new line in the monitor to get the prompt */
1561 ch = '\r';
1562 goto send_char;
1564 break;
1565 case 't':
1566 term_timestamps = !term_timestamps;
1567 term_timestamps_start = -1;
1568 break;
1569 case TERM_ESCAPE:
1570 goto send_char;
1572 } else if (ch == TERM_ESCAPE) {
1573 term_got_escape = 1;
1574 } else {
1575 send_char:
1576 if (client_index < stdio_nb_clients) {
1577 uint8_t buf[1];
1578 CharDriverState *chr;
1580 chr = stdio_clients[client_index];
1581 if (qemu_chr_can_read(chr) > 0) {
1582 buf[0] = ch;
1583 qemu_chr_read(chr, buf, 1);
1584 } else if (term_fifo_size == 0) {
1585 term_fifo[term_fifo_size++] = ch;
1591 static int stdio_read_poll(void *opaque)
1593 CharDriverState *chr;
1595 if (client_index < stdio_nb_clients) {
1596 chr = stdio_clients[client_index];
1597 /* try to flush the queue if needed */
1598 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1599 qemu_chr_read(chr, term_fifo, 1);
1600 term_fifo_size = 0;
1602 /* see if we can absorb more chars */
1603 if (term_fifo_size == 0)
1604 return 1;
1605 else
1606 return 0;
1607 } else {
1608 return 1;
1612 static void stdio_read(void *opaque)
1614 int size;
1615 uint8_t buf[1];
1617 size = read(0, buf, 1);
1618 if (size == 0) {
1619 /* stdin has been closed. Remove it from the active list. */
1620 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1621 return;
1623 if (size > 0)
1624 stdio_received_byte(buf[0]);
1627 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1629 FDCharDriver *s = chr->opaque;
1630 if (!term_timestamps) {
1631 return unix_write(s->fd_out, buf, len);
1632 } else {
1633 int i;
1634 char buf1[64];
1636 for(i = 0; i < len; i++) {
1637 unix_write(s->fd_out, buf + i, 1);
1638 if (buf[i] == '\n') {
1639 int64_t ti;
1640 int secs;
1642 ti = get_clock();
1643 if (term_timestamps_start == -1)
1644 term_timestamps_start = ti;
1645 ti -= term_timestamps_start;
1646 secs = ti / 1000000000;
1647 snprintf(buf1, sizeof(buf1),
1648 "[%02d:%02d:%02d.%03d] ",
1649 secs / 3600,
1650 (secs / 60) % 60,
1651 secs % 60,
1652 (int)((ti / 1000000) % 1000));
1653 unix_write(s->fd_out, buf1, strlen(buf1));
1656 return len;
1660 /* init terminal so that we can grab keys */
1661 static struct termios oldtty;
1662 static int old_fd0_flags;
1664 static void term_exit(void)
1666 tcsetattr (0, TCSANOW, &oldtty);
1667 fcntl(0, F_SETFL, old_fd0_flags);
1670 static void term_init(void)
1672 struct termios tty;
1674 tcgetattr (0, &tty);
1675 oldtty = tty;
1676 old_fd0_flags = fcntl(0, F_GETFL);
1678 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1679 |INLCR|IGNCR|ICRNL|IXON);
1680 tty.c_oflag |= OPOST;
1681 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1682 /* if graphical mode, we allow Ctrl-C handling */
1683 if (nographic)
1684 tty.c_lflag &= ~ISIG;
1685 tty.c_cflag &= ~(CSIZE|PARENB);
1686 tty.c_cflag |= CS8;
1687 tty.c_cc[VMIN] = 1;
1688 tty.c_cc[VTIME] = 0;
1690 tcsetattr (0, TCSANOW, &tty);
1692 atexit(term_exit);
1694 fcntl(0, F_SETFL, O_NONBLOCK);
1697 static CharDriverState *qemu_chr_open_stdio(void)
1699 CharDriverState *chr;
1701 if (nographic) {
1702 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1703 return NULL;
1704 chr = qemu_chr_open_fd(0, 1);
1705 chr->chr_write = stdio_write;
1706 if (stdio_nb_clients == 0)
1707 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1708 client_index = stdio_nb_clients;
1709 } else {
1710 if (stdio_nb_clients != 0)
1711 return NULL;
1712 chr = qemu_chr_open_fd(0, 1);
1714 stdio_clients[stdio_nb_clients++] = chr;
1715 if (stdio_nb_clients == 1) {
1716 /* set the terminal in raw mode */
1717 term_init();
1719 return chr;
1722 /*
1723 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1724 * The entry is <domain-path><storeString>/tty and the value is the name
1725 * of the pty associated with the device.
1726 */
1727 static int store_dev_info(char *devName, int domid,
1728 CharDriverState *cState, char *storeString)
1730 int xc_handle;
1731 struct xs_handle *xs;
1732 char *path;
1733 char *newpath;
1734 FDCharDriver *s;
1735 char *pts;
1737 /* Check for valid arguments (at least, prevent segfaults). */
1738 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1739 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1740 return EINVAL;
1743 /*
1744 * Only continue if we're talking to a pty
1745 * Actually, the following code works for any CharDriverState using
1746 * FDCharDriver, but we really only care about pty's here
1747 */
1748 if (strcmp(devName, "pty"))
1749 return 0;
1751 s = cState->opaque;
1752 if (s == NULL) {
1753 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1754 __FUNCTION__, storeString, devName);
1755 return EBADF;
1758 pts = ptsname(s->fd_in);
1759 if (pts == NULL) {
1760 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1761 "error %d (%s)\n",
1762 __FUNCTION__, storeString, devName, errno, strerror(errno));
1763 return errno;
1766 /* We now have everything we need to set the xenstore entry. */
1767 xs = xs_daemon_open();
1768 if (xs == NULL) {
1769 fprintf(logfile, "Could not contact XenStore\n");
1770 return -1;
1773 xc_handle = xc_interface_open();
1774 if (xc_handle == -1) {
1775 fprintf(logfile, "xc_interface_open() error\n");
1776 return -1;
1779 path = xs_get_domain_path(xs, domid);
1780 if (path == NULL) {
1781 fprintf(logfile, "xs_get_domain_path() error\n");
1782 return -1;
1784 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1785 strlen("/tty") + 1));
1786 if (newpath == NULL) {
1787 free(path); /* realloc errors leave old block */
1788 fprintf(logfile, "realloc error\n");
1789 return -1;
1791 path = newpath;
1793 strcat(path, storeString);
1794 strcat(path, "/tty");
1795 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1796 fprintf(logfile, "xs_write for '%s' fail", storeString);
1797 return -1;
1800 free(path);
1801 xs_daemon_close(xs);
1802 close(xc_handle);
1804 return 0;
1807 #ifdef __sun__
1808 /* Once Solaris has openpty(), this is going to be removed. */
1809 int openpty(int *amaster, int *aslave, char *name,
1810 struct termios *termp, struct winsize *winp)
1812 const char *slave;
1813 int mfd = -1, sfd = -1;
1815 *amaster = *aslave = -1;
1817 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
1818 if (mfd < 0)
1819 goto err;
1821 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
1822 goto err;
1824 if ((slave = ptsname(mfd)) == NULL)
1825 goto err;
1827 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1828 goto err;
1830 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1831 (termp != NULL && tcgetattr(sfd, termp) < 0))
1832 goto err;
1834 if (amaster)
1835 *amaster = mfd;
1836 if (aslave)
1837 *aslave = sfd;
1838 if (winp)
1839 ioctl(sfd, TIOCSWINSZ, winp);
1841 return 0;
1843 err:
1844 if (sfd != -1)
1845 close(sfd);
1846 close(mfd);
1847 return -1;
1850 void cfmakeraw (struct termios *termios_p)
1852 termios_p->c_iflag &=
1853 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1854 termios_p->c_oflag &= ~OPOST;
1855 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1856 termios_p->c_cflag &= ~(CSIZE|PARENB);
1857 termios_p->c_cflag |= CS8;
1859 termios_p->c_cc[VMIN] = 0;
1860 termios_p->c_cc[VTIME] = 0;
1863 #endif
1865 #if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun__)
1866 static CharDriverState *qemu_chr_open_pty(void)
1868 struct termios tty;
1869 int master_fd, slave_fd;
1871 /* Not satisfying */
1872 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1873 return NULL;
1876 /* Set raw attributes on the pty. */
1877 cfmakeraw(&tty);
1878 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1880 close(slave_fd);
1882 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1884 return qemu_chr_open_fd(master_fd, master_fd);
1887 static void tty_serial_init(int fd, int speed,
1888 int parity, int data_bits, int stop_bits)
1890 struct termios tty;
1891 speed_t spd;
1893 #if 0
1894 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1895 speed, parity, data_bits, stop_bits);
1896 #endif
1897 tcgetattr (fd, &tty);
1899 switch(speed) {
1900 case 50:
1901 spd = B50;
1902 break;
1903 case 75:
1904 spd = B75;
1905 break;
1906 case 300:
1907 spd = B300;
1908 break;
1909 case 600:
1910 spd = B600;
1911 break;
1912 case 1200:
1913 spd = B1200;
1914 break;
1915 case 2400:
1916 spd = B2400;
1917 break;
1918 case 4800:
1919 spd = B4800;
1920 break;
1921 case 9600:
1922 spd = B9600;
1923 break;
1924 case 19200:
1925 spd = B19200;
1926 break;
1927 case 38400:
1928 spd = B38400;
1929 break;
1930 case 57600:
1931 spd = B57600;
1932 break;
1933 default:
1934 case 115200:
1935 spd = B115200;
1936 break;
1939 cfsetispeed(&tty, spd);
1940 cfsetospeed(&tty, spd);
1942 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1943 |INLCR|IGNCR|ICRNL|IXON);
1944 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1945 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1946 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1947 switch(data_bits) {
1948 default:
1949 case 8:
1950 tty.c_cflag |= CS8;
1951 break;
1952 case 7:
1953 tty.c_cflag |= CS7;
1954 break;
1955 case 6:
1956 tty.c_cflag |= CS6;
1957 break;
1958 case 5:
1959 tty.c_cflag |= CS5;
1960 break;
1962 switch(parity) {
1963 default:
1964 case 'N':
1965 break;
1966 case 'E':
1967 tty.c_cflag |= PARENB;
1968 break;
1969 case 'O':
1970 tty.c_cflag |= PARENB | PARODD;
1971 break;
1973 if (stop_bits == 2)
1974 tty.c_cflag |= CSTOPB;
1976 tcsetattr (fd, TCSANOW, &tty);
1979 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1981 FDCharDriver *s = chr->opaque;
1983 switch(cmd) {
1984 case CHR_IOCTL_SERIAL_SET_PARAMS:
1986 QEMUSerialSetParams *ssp = arg;
1987 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1988 ssp->data_bits, ssp->stop_bits);
1990 break;
1991 case CHR_IOCTL_SERIAL_SET_BREAK:
1993 int enable = *(int *)arg;
1994 if (enable)
1995 tcsendbreak(s->fd_in, 1);
1997 break;
1998 case CHR_IOCTL_SERIAL_GET_TIOCM:
2000 ioctl(s->fd_in, TIOCMGET, arg);
2002 break;
2003 case CHR_IOCTL_SERIAL_SET_TIOCM:
2005 ioctl(s->fd_in, TIOCMSET, arg);
2007 break;
2008 default:
2009 return -ENOTSUP;
2011 return 0;
2014 static CharDriverState *qemu_chr_open_tty(const char *filename)
2016 CharDriverState *chr;
2017 int fd;
2019 fd = open(filename, O_RDWR | O_NONBLOCK);
2020 if (fd < 0)
2021 return NULL;
2022 fcntl(fd, F_SETFL, O_NONBLOCK);
2023 tty_serial_init(fd, 115200, 'N', 8, 1);
2024 chr = qemu_chr_open_fd(fd, fd);
2025 if (!chr)
2026 return NULL;
2027 chr->chr_ioctl = tty_serial_ioctl;
2028 qemu_chr_reset(chr);
2029 return chr;
2032 #if defined(__linux__)
2033 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2035 int fd = (int)chr->opaque;
2036 uint8_t b;
2038 switch(cmd) {
2039 case CHR_IOCTL_PP_READ_DATA:
2040 if (ioctl(fd, PPRDATA, &b) < 0)
2041 return -ENOTSUP;
2042 *(uint8_t *)arg = b;
2043 break;
2044 case CHR_IOCTL_PP_WRITE_DATA:
2045 b = *(uint8_t *)arg;
2046 if (ioctl(fd, PPWDATA, &b) < 0)
2047 return -ENOTSUP;
2048 break;
2049 case CHR_IOCTL_PP_READ_CONTROL:
2050 if (ioctl(fd, PPRCONTROL, &b) < 0)
2051 return -ENOTSUP;
2052 *(uint8_t *)arg = b;
2053 break;
2054 case CHR_IOCTL_PP_WRITE_CONTROL:
2055 b = *(uint8_t *)arg;
2056 if (ioctl(fd, PPWCONTROL, &b) < 0)
2057 return -ENOTSUP;
2058 break;
2059 case CHR_IOCTL_PP_READ_STATUS:
2060 if (ioctl(fd, PPRSTATUS, &b) < 0)
2061 return -ENOTSUP;
2062 *(uint8_t *)arg = b;
2063 break;
2064 default:
2065 return -ENOTSUP;
2067 return 0;
2070 static CharDriverState *qemu_chr_open_pp(const char *filename)
2072 CharDriverState *chr;
2073 int fd;
2075 fd = open(filename, O_RDWR);
2076 if (fd < 0)
2077 return NULL;
2079 if (ioctl(fd, PPCLAIM) < 0) {
2080 close(fd);
2081 return NULL;
2084 chr = qemu_mallocz(sizeof(CharDriverState));
2085 if (!chr) {
2086 close(fd);
2087 return NULL;
2089 chr->opaque = (void *)fd;
2090 chr->chr_write = null_chr_write;
2091 chr->chr_ioctl = pp_ioctl;
2093 qemu_chr_reset(chr);
2095 return chr;
2097 #endif /* __linux__ */
2099 #else
2100 static CharDriverState *qemu_chr_open_pty(void)
2102 return NULL;
2104 #endif /* __linux__ || __NetBSD__ || __OpenBSD__ || __sun__ */
2106 #endif /* !defined(_WIN32) */
2108 #ifdef _WIN32
2109 typedef struct {
2110 CharDriverState *chr;
2111 int max_size;
2112 HANDLE hcom, hrecv, hsend;
2113 OVERLAPPED orecv, osend;
2114 BOOL fpipe;
2115 DWORD len;
2116 } WinCharState;
2118 #define NSENDBUF 2048
2119 #define NRECVBUF 2048
2120 #define MAXCONNECT 1
2121 #define NTIMEOUT 5000
2123 static int win_chr_poll(void *opaque);
2124 static int win_chr_pipe_poll(void *opaque);
2126 static void win_chr_close2(WinCharState *s)
2128 if (s->hsend) {
2129 CloseHandle(s->hsend);
2130 s->hsend = NULL;
2132 if (s->hrecv) {
2133 CloseHandle(s->hrecv);
2134 s->hrecv = NULL;
2136 if (s->hcom) {
2137 CloseHandle(s->hcom);
2138 s->hcom = NULL;
2140 if (s->fpipe)
2141 qemu_del_polling_cb(win_chr_pipe_poll, s);
2142 else
2143 qemu_del_polling_cb(win_chr_poll, s);
2146 static void win_chr_close(CharDriverState *chr)
2148 WinCharState *s = chr->opaque;
2149 win_chr_close2(s);
2152 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2154 COMMCONFIG comcfg;
2155 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2156 COMSTAT comstat;
2157 DWORD size;
2158 DWORD err;
2160 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2161 if (!s->hsend) {
2162 fprintf(stderr, "Failed CreateEvent\n");
2163 goto fail;
2165 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2166 if (!s->hrecv) {
2167 fprintf(stderr, "Failed CreateEvent\n");
2168 goto fail;
2171 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2172 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2173 if (s->hcom == INVALID_HANDLE_VALUE) {
2174 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2175 s->hcom = NULL;
2176 goto fail;
2179 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2180 fprintf(stderr, "Failed SetupComm\n");
2181 goto fail;
2184 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2185 size = sizeof(COMMCONFIG);
2186 GetDefaultCommConfig(filename, &comcfg, &size);
2187 comcfg.dcb.DCBlength = sizeof(DCB);
2188 CommConfigDialog(filename, NULL, &comcfg);
2190 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2191 fprintf(stderr, "Failed SetCommState\n");
2192 goto fail;
2195 if (!SetCommMask(s->hcom, EV_ERR)) {
2196 fprintf(stderr, "Failed SetCommMask\n");
2197 goto fail;
2200 cto.ReadIntervalTimeout = MAXDWORD;
2201 if (!SetCommTimeouts(s->hcom, &cto)) {
2202 fprintf(stderr, "Failed SetCommTimeouts\n");
2203 goto fail;
2206 if (!ClearCommError(s->hcom, &err, &comstat)) {
2207 fprintf(stderr, "Failed ClearCommError\n");
2208 goto fail;
2210 s->chr = chr;
2211 qemu_add_polling_cb(win_chr_poll, s);
2212 return 0;
2214 fail:
2215 win_chr_close2(s);
2216 return -1;
2219 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2221 WinCharState *s = chr->opaque;
2222 DWORD len, ret, size, err;
2224 len = len1;
2225 ZeroMemory(&s->osend, sizeof(s->osend));
2226 s->osend.hEvent = s->hsend;
2227 while (len > 0) {
2228 if (s->hsend)
2229 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2230 else
2231 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2232 if (!ret) {
2233 err = GetLastError();
2234 if (err == ERROR_IO_PENDING) {
2235 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2236 if (ret) {
2237 buf += size;
2238 len -= size;
2239 } else {
2240 break;
2242 } else {
2243 break;
2245 } else {
2246 buf += size;
2247 len -= size;
2250 return len1 - len;
2253 static int win_chr_read_poll(WinCharState *s)
2255 s->max_size = qemu_chr_can_read(s->chr);
2256 return s->max_size;
2259 static void win_chr_readfile(WinCharState *s)
2261 int ret, err;
2262 uint8_t buf[1024];
2263 DWORD size;
2265 ZeroMemory(&s->orecv, sizeof(s->orecv));
2266 s->orecv.hEvent = s->hrecv;
2267 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2268 if (!ret) {
2269 err = GetLastError();
2270 if (err == ERROR_IO_PENDING) {
2271 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2275 if (size > 0) {
2276 qemu_chr_read(s->chr, buf, size);
2280 static void win_chr_read(WinCharState *s)
2282 if (s->len > s->max_size)
2283 s->len = s->max_size;
2284 if (s->len == 0)
2285 return;
2287 win_chr_readfile(s);
2290 static int win_chr_poll(void *opaque)
2292 WinCharState *s = opaque;
2293 COMSTAT status;
2294 DWORD comerr;
2296 ClearCommError(s->hcom, &comerr, &status);
2297 if (status.cbInQue > 0) {
2298 s->len = status.cbInQue;
2299 win_chr_read_poll(s);
2300 win_chr_read(s);
2301 return 1;
2303 return 0;
2306 static CharDriverState *qemu_chr_open_win(const char *filename)
2308 CharDriverState *chr;
2309 WinCharState *s;
2311 chr = qemu_mallocz(sizeof(CharDriverState));
2312 if (!chr)
2313 return NULL;
2314 s = qemu_mallocz(sizeof(WinCharState));
2315 if (!s) {
2316 free(chr);
2317 return NULL;
2319 chr->opaque = s;
2320 chr->chr_write = win_chr_write;
2321 chr->chr_close = win_chr_close;
2323 if (win_chr_init(s, chr, filename) < 0) {
2324 free(s);
2325 free(chr);
2326 return NULL;
2328 qemu_chr_reset(chr);
2329 return chr;
2332 static int win_chr_pipe_poll(void *opaque)
2334 WinCharState *s = opaque;
2335 DWORD size;
2337 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2338 if (size > 0) {
2339 s->len = size;
2340 win_chr_read_poll(s);
2341 win_chr_read(s);
2342 return 1;
2344 return 0;
2347 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2349 OVERLAPPED ov;
2350 int ret;
2351 DWORD size;
2352 char openname[256];
2354 s->fpipe = TRUE;
2356 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2357 if (!s->hsend) {
2358 fprintf(stderr, "Failed CreateEvent\n");
2359 goto fail;
2361 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2362 if (!s->hrecv) {
2363 fprintf(stderr, "Failed CreateEvent\n");
2364 goto fail;
2367 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2368 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2369 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2370 PIPE_WAIT,
2371 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2372 if (s->hcom == INVALID_HANDLE_VALUE) {
2373 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2374 s->hcom = NULL;
2375 goto fail;
2378 ZeroMemory(&ov, sizeof(ov));
2379 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2380 ret = ConnectNamedPipe(s->hcom, &ov);
2381 if (ret) {
2382 fprintf(stderr, "Failed ConnectNamedPipe\n");
2383 goto fail;
2386 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2387 if (!ret) {
2388 fprintf(stderr, "Failed GetOverlappedResult\n");
2389 if (ov.hEvent) {
2390 CloseHandle(ov.hEvent);
2391 ov.hEvent = NULL;
2393 goto fail;
2396 if (ov.hEvent) {
2397 CloseHandle(ov.hEvent);
2398 ov.hEvent = NULL;
2400 qemu_add_polling_cb(win_chr_pipe_poll, s);
2401 return 0;
2403 fail:
2404 win_chr_close2(s);
2405 return -1;
2409 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2411 CharDriverState *chr;
2412 WinCharState *s;
2414 chr = qemu_mallocz(sizeof(CharDriverState));
2415 if (!chr)
2416 return NULL;
2417 s = qemu_mallocz(sizeof(WinCharState));
2418 if (!s) {
2419 free(chr);
2420 return NULL;
2422 chr->opaque = s;
2423 chr->chr_write = win_chr_write;
2424 chr->chr_close = win_chr_close;
2426 if (win_chr_pipe_init(s, filename) < 0) {
2427 free(s);
2428 free(chr);
2429 return NULL;
2431 qemu_chr_reset(chr);
2432 return chr;
2435 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2437 CharDriverState *chr;
2438 WinCharState *s;
2440 chr = qemu_mallocz(sizeof(CharDriverState));
2441 if (!chr)
2442 return NULL;
2443 s = qemu_mallocz(sizeof(WinCharState));
2444 if (!s) {
2445 free(chr);
2446 return NULL;
2448 s->hcom = fd_out;
2449 chr->opaque = s;
2450 chr->chr_write = win_chr_write;
2451 qemu_chr_reset(chr);
2452 return chr;
2455 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2457 HANDLE fd_out;
2459 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2460 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2461 if (fd_out == INVALID_HANDLE_VALUE)
2462 return NULL;
2464 return qemu_chr_open_win_file(fd_out);
2466 #endif
2468 /***********************************************************/
2469 /* UDP Net console */
2471 typedef struct {
2472 int fd;
2473 struct sockaddr_in daddr;
2474 char buf[1024];
2475 int bufcnt;
2476 int bufptr;
2477 int max_size;
2478 } NetCharDriver;
2480 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2482 NetCharDriver *s = chr->opaque;
2484 return sendto(s->fd, buf, len, 0,
2485 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2488 static int udp_chr_read_poll(void *opaque)
2490 CharDriverState *chr = opaque;
2491 NetCharDriver *s = chr->opaque;
2493 s->max_size = qemu_chr_can_read(chr);
2495 /* If there were any stray characters in the queue process them
2496 * first
2497 */
2498 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2499 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2500 s->bufptr++;
2501 s->max_size = qemu_chr_can_read(chr);
2503 return s->max_size;
2506 static void udp_chr_read(void *opaque)
2508 CharDriverState *chr = opaque;
2509 NetCharDriver *s = chr->opaque;
2511 if (s->max_size == 0)
2512 return;
2513 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2514 s->bufptr = s->bufcnt;
2515 if (s->bufcnt <= 0)
2516 return;
2518 s->bufptr = 0;
2519 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2520 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2521 s->bufptr++;
2522 s->max_size = qemu_chr_can_read(chr);
2526 static void udp_chr_update_read_handler(CharDriverState *chr)
2528 NetCharDriver *s = chr->opaque;
2530 if (s->fd >= 0) {
2531 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2532 udp_chr_read, NULL, chr);
2536 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2537 #ifndef _WIN32
2538 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2539 #endif
2540 int parse_host_src_port(struct sockaddr_in *haddr,
2541 struct sockaddr_in *saddr,
2542 const char *str);
2544 static CharDriverState *qemu_chr_open_udp(const char *def)
2546 CharDriverState *chr = NULL;
2547 NetCharDriver *s = NULL;
2548 int fd = -1;
2549 struct sockaddr_in saddr;
2551 chr = qemu_mallocz(sizeof(CharDriverState));
2552 if (!chr)
2553 goto return_err;
2554 s = qemu_mallocz(sizeof(NetCharDriver));
2555 if (!s)
2556 goto return_err;
2558 fd = socket(PF_INET, SOCK_DGRAM, 0);
2559 if (fd < 0) {
2560 perror("socket(PF_INET, SOCK_DGRAM)");
2561 goto return_err;
2564 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2565 printf("Could not parse: %s\n", def);
2566 goto return_err;
2569 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2571 perror("bind");
2572 goto return_err;
2575 s->fd = fd;
2576 s->bufcnt = 0;
2577 s->bufptr = 0;
2578 chr->opaque = s;
2579 chr->chr_write = udp_chr_write;
2580 chr->chr_update_read_handler = udp_chr_update_read_handler;
2581 return chr;
2583 return_err:
2584 if (chr)
2585 free(chr);
2586 if (s)
2587 free(s);
2588 if (fd >= 0)
2589 closesocket(fd);
2590 return NULL;
2593 /***********************************************************/
2594 /* TCP Net console */
2596 typedef struct {
2597 int fd, listen_fd;
2598 int connected;
2599 int max_size;
2600 int do_telnetopt;
2601 int do_nodelay;
2602 int is_unix;
2603 } TCPCharDriver;
2605 static void tcp_chr_accept(void *opaque);
2607 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2609 TCPCharDriver *s = chr->opaque;
2610 if (s->connected) {
2611 return send_all(s->fd, buf, len);
2612 } else {
2613 /* XXX: indicate an error ? */
2614 return len;
2618 static int tcp_chr_read_poll(void *opaque)
2620 CharDriverState *chr = opaque;
2621 TCPCharDriver *s = chr->opaque;
2622 if (!s->connected)
2623 return 0;
2624 s->max_size = qemu_chr_can_read(chr);
2625 return s->max_size;
2628 #define IAC 255
2629 #define IAC_BREAK 243
2630 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2631 TCPCharDriver *s,
2632 char *buf, int *size)
2634 /* Handle any telnet client's basic IAC options to satisfy char by
2635 * char mode with no echo. All IAC options will be removed from
2636 * the buf and the do_telnetopt variable will be used to track the
2637 * state of the width of the IAC information.
2639 * IAC commands come in sets of 3 bytes with the exception of the
2640 * "IAC BREAK" command and the double IAC.
2641 */
2643 int i;
2644 int j = 0;
2646 for (i = 0; i < *size; i++) {
2647 if (s->do_telnetopt > 1) {
2648 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2649 /* Double IAC means send an IAC */
2650 if (j != i)
2651 buf[j] = buf[i];
2652 j++;
2653 s->do_telnetopt = 1;
2654 } else {
2655 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2656 /* Handle IAC break commands by sending a serial break */
2657 qemu_chr_event(chr, CHR_EVENT_BREAK);
2658 s->do_telnetopt++;
2660 s->do_telnetopt++;
2662 if (s->do_telnetopt >= 4) {
2663 s->do_telnetopt = 1;
2665 } else {
2666 if ((unsigned char)buf[i] == IAC) {
2667 s->do_telnetopt = 2;
2668 } else {
2669 if (j != i)
2670 buf[j] = buf[i];
2671 j++;
2675 *size = j;
2678 static void tcp_chr_read(void *opaque)
2680 CharDriverState *chr = opaque;
2681 TCPCharDriver *s = chr->opaque;
2682 uint8_t buf[1024];
2683 int len, size;
2685 if (!s->connected || s->max_size <= 0)
2686 return;
2687 len = sizeof(buf);
2688 if (len > s->max_size)
2689 len = s->max_size;
2690 size = recv(s->fd, buf, len, 0);
2691 if (size == 0) {
2692 /* connection closed */
2693 s->connected = 0;
2694 if (s->listen_fd >= 0) {
2695 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2697 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2698 closesocket(s->fd);
2699 s->fd = -1;
2700 } else if (size > 0) {
2701 if (s->do_telnetopt)
2702 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2703 if (size > 0)
2704 qemu_chr_read(chr, buf, size);
2708 static void tcp_chr_connect(void *opaque)
2710 CharDriverState *chr = opaque;
2711 TCPCharDriver *s = chr->opaque;
2713 s->connected = 1;
2714 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2715 tcp_chr_read, NULL, chr);
2716 qemu_chr_reset(chr);
2719 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2720 static void tcp_chr_telnet_init(int fd)
2722 char buf[3];
2723 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2724 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2725 send(fd, (char *)buf, 3, 0);
2726 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2727 send(fd, (char *)buf, 3, 0);
2728 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2729 send(fd, (char *)buf, 3, 0);
2730 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2731 send(fd, (char *)buf, 3, 0);
2734 static void socket_set_nodelay(int fd)
2736 int val = 1;
2737 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2740 static void tcp_chr_accept(void *opaque)
2742 CharDriverState *chr = opaque;
2743 TCPCharDriver *s = chr->opaque;
2744 struct sockaddr_in saddr;
2745 #ifndef _WIN32
2746 struct sockaddr_un uaddr;
2747 #endif
2748 struct sockaddr *addr;
2749 socklen_t len;
2750 int fd;
2752 for(;;) {
2753 #ifndef _WIN32
2754 if (s->is_unix) {
2755 len = sizeof(uaddr);
2756 addr = (struct sockaddr *)&uaddr;
2757 } else
2758 #endif
2760 len = sizeof(saddr);
2761 addr = (struct sockaddr *)&saddr;
2763 fd = accept(s->listen_fd, addr, &len);
2764 if (fd < 0 && errno != EINTR) {
2765 return;
2766 } else if (fd >= 0) {
2767 if (s->do_telnetopt)
2768 tcp_chr_telnet_init(fd);
2769 break;
2772 socket_set_nonblock(fd);
2773 if (s->do_nodelay)
2774 socket_set_nodelay(fd);
2775 s->fd = fd;
2776 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2777 tcp_chr_connect(chr);
2780 static void tcp_chr_close(CharDriverState *chr)
2782 TCPCharDriver *s = chr->opaque;
2783 if (s->fd >= 0)
2784 closesocket(s->fd);
2785 if (s->listen_fd >= 0)
2786 closesocket(s->listen_fd);
2787 qemu_free(s);
2790 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2791 int is_telnet,
2792 int is_unix)
2794 CharDriverState *chr = NULL;
2795 TCPCharDriver *s = NULL;
2796 int fd = -1, ret, err, val;
2797 int is_listen = 0;
2798 int is_waitconnect = 1;
2799 int do_nodelay = 0;
2800 const char *ptr;
2801 struct sockaddr_in saddr;
2802 #ifndef _WIN32
2803 struct sockaddr_un uaddr;
2804 #endif
2805 struct sockaddr *addr;
2806 socklen_t addrlen;
2808 #ifndef _WIN32
2809 if (is_unix) {
2810 addr = (struct sockaddr *)&uaddr;
2811 addrlen = sizeof(uaddr);
2812 if (parse_unix_path(&uaddr, host_str) < 0)
2813 goto fail;
2814 } else
2815 #endif
2817 addr = (struct sockaddr *)&saddr;
2818 addrlen = sizeof(saddr);
2819 if (parse_host_port(&saddr, host_str) < 0)
2820 goto fail;
2823 ptr = host_str;
2824 while((ptr = strchr(ptr,','))) {
2825 ptr++;
2826 if (!strncmp(ptr,"server",6)) {
2827 is_listen = 1;
2828 } else if (!strncmp(ptr,"nowait",6)) {
2829 is_waitconnect = 0;
2830 } else if (!strncmp(ptr,"nodelay",6)) {
2831 do_nodelay = 1;
2832 } else {
2833 printf("Unknown option: %s\n", ptr);
2834 goto fail;
2837 if (!is_listen)
2838 is_waitconnect = 0;
2840 chr = qemu_mallocz(sizeof(CharDriverState));
2841 if (!chr)
2842 goto fail;
2843 s = qemu_mallocz(sizeof(TCPCharDriver));
2844 if (!s)
2845 goto fail;
2847 #ifndef _WIN32
2848 if (is_unix)
2849 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2850 else
2851 #endif
2852 fd = socket(PF_INET, SOCK_STREAM, 0);
2854 if (fd < 0)
2855 goto fail;
2857 if (!is_waitconnect)
2858 socket_set_nonblock(fd);
2860 s->connected = 0;
2861 s->fd = -1;
2862 s->listen_fd = -1;
2863 s->is_unix = is_unix;
2864 s->do_nodelay = do_nodelay && !is_unix;
2866 chr->opaque = s;
2867 chr->chr_write = tcp_chr_write;
2868 chr->chr_close = tcp_chr_close;
2870 if (is_listen) {
2871 /* allow fast reuse */
2872 #ifndef _WIN32
2873 if (is_unix) {
2874 char path[109];
2875 strncpy(path, uaddr.sun_path, 108);
2876 path[108] = 0;
2877 unlink(path);
2878 } else
2879 #endif
2881 val = 1;
2882 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2885 ret = bind(fd, addr, addrlen);
2886 if (ret < 0)
2887 goto fail;
2889 ret = listen(fd, 0);
2890 if (ret < 0)
2891 goto fail;
2893 s->listen_fd = fd;
2894 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2895 if (is_telnet)
2896 s->do_telnetopt = 1;
2897 } else {
2898 for(;;) {
2899 ret = connect(fd, addr, addrlen);
2900 if (ret < 0) {
2901 err = socket_error();
2902 if (err == EINTR || err == EWOULDBLOCK) {
2903 } else if (err == EINPROGRESS) {
2904 break;
2905 } else {
2906 goto fail;
2908 } else {
2909 s->connected = 1;
2910 break;
2913 s->fd = fd;
2914 socket_set_nodelay(fd);
2915 if (s->connected)
2916 tcp_chr_connect(chr);
2917 else
2918 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2921 if (is_listen && is_waitconnect) {
2922 printf("QEMU waiting for connection on: %s\n", host_str);
2923 tcp_chr_accept(chr);
2924 socket_set_nonblock(s->listen_fd);
2927 return chr;
2928 fail:
2929 if (fd >= 0)
2930 closesocket(fd);
2931 qemu_free(s);
2932 qemu_free(chr);
2933 return NULL;
2936 CharDriverState *qemu_chr_open(const char *filename)
2938 const char *p;
2940 if (!strcmp(filename, "vc")) {
2941 return text_console_init(&display_state);
2942 } else if (!strcmp(filename, "null")) {
2943 return qemu_chr_open_null();
2944 } else
2945 if (strstart(filename, "tcp:", &p)) {
2946 return qemu_chr_open_tcp(p, 0, 0);
2947 } else
2948 if (strstart(filename, "telnet:", &p)) {
2949 return qemu_chr_open_tcp(p, 1, 0);
2950 } else
2951 if (strstart(filename, "udp:", &p)) {
2952 return qemu_chr_open_udp(p);
2953 } else
2954 #ifndef _WIN32
2955 if (strstart(filename, "unix:", &p)) {
2956 return qemu_chr_open_tcp(p, 0, 1);
2957 } else if (strstart(filename, "file:", &p)) {
2958 return qemu_chr_open_file_out(p);
2959 } else if (strstart(filename, "pipe:", &p)) {
2960 return qemu_chr_open_pipe(p);
2961 } else if (!strcmp(filename, "pty")) {
2962 return qemu_chr_open_pty();
2963 } else if (!strcmp(filename, "stdio")) {
2964 return qemu_chr_open_stdio();
2965 } else
2966 #endif
2967 #if defined(__linux__)
2968 if (strstart(filename, "/dev/parport", NULL)) {
2969 return qemu_chr_open_pp(filename);
2970 } else
2971 if (strstart(filename, "/dev/", NULL)) {
2972 return qemu_chr_open_tty(filename);
2973 } else
2974 #endif
2975 #ifdef _WIN32
2976 if (strstart(filename, "COM", NULL)) {
2977 return qemu_chr_open_win(filename);
2978 } else
2979 if (strstart(filename, "pipe:", &p)) {
2980 return qemu_chr_open_win_pipe(p);
2981 } else
2982 if (strstart(filename, "file:", &p)) {
2983 return qemu_chr_open_win_file_out(p);
2985 #endif
2987 return NULL;
2991 void qemu_chr_close(CharDriverState *chr)
2993 if (chr->chr_close)
2994 chr->chr_close(chr);
2997 /***********************************************************/
2998 /* network device redirectors */
3000 void hex_dump(FILE *f, const uint8_t *buf, int size)
3002 int len, i, j, c;
3004 for(i=0;i<size;i+=16) {
3005 len = size - i;
3006 if (len > 16)
3007 len = 16;
3008 fprintf(f, "%08x ", i);
3009 for(j=0;j<16;j++) {
3010 if (j < len)
3011 fprintf(f, " %02x", buf[i+j]);
3012 else
3013 fprintf(f, " ");
3015 fprintf(f, " ");
3016 for(j=0;j<len;j++) {
3017 c = buf[i+j];
3018 if (c < ' ' || c > '~')
3019 c = '.';
3020 fprintf(f, "%c", c);
3022 fprintf(f, "\n");
3026 static int parse_macaddr(uint8_t *macaddr, const char *p)
3028 int i;
3029 for(i = 0; i < 6; i++) {
3030 macaddr[i] = strtol(p, (char **)&p, 16);
3031 if (i == 5) {
3032 if (*p != '\0')
3033 return -1;
3034 } else {
3035 if (*p != ':')
3036 return -1;
3037 p++;
3040 return 0;
3043 static int get_str_sep(char *buf, size_t buf_size, const char **pp, int sep)
3045 const char *p, *p1;
3046 int len;
3047 p = *pp;
3048 p1 = strchr(p, sep);
3049 if (!p1)
3050 return -1;
3051 len = p1 - p;
3052 p1++;
3053 if (buf_size > 0) {
3054 if (len > buf_size - 1)
3055 len = buf_size - 1;
3056 memcpy(buf, p, len);
3057 buf[len] = '\0';
3059 *pp = p1;
3060 return 0;
3063 int parse_host_src_port(struct sockaddr_in *haddr,
3064 struct sockaddr_in *saddr,
3065 const char *input_str)
3067 char *str = strdup(input_str);
3068 char *host_str = str;
3069 char *src_str;
3070 char *ptr;
3072 /*
3073 * Chop off any extra arguments at the end of the string which
3074 * would start with a comma, then fill in the src port information
3075 * if it was provided else use the "any address" and "any port".
3076 */
3077 if ((ptr = strchr(str,',')))
3078 *ptr = '\0';
3080 if ((src_str = strchr(input_str,'@'))) {
3081 *src_str = '\0';
3082 src_str++;
3085 if (parse_host_port(haddr, host_str) < 0)
3086 goto fail;
3088 if (!src_str || *src_str == '\0')
3089 src_str = ":0";
3091 if (parse_host_port(saddr, src_str) < 0)
3092 goto fail;
3094 free(str);
3095 return(0);
3097 fail:
3098 free(str);
3099 return -1;
3102 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3104 char buf[512];
3105 struct hostent *he;
3106 const char *p, *r;
3107 int port;
3109 p = str;
3110 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3111 return -1;
3112 saddr->sin_family = AF_INET;
3113 if (buf[0] == '\0') {
3114 saddr->sin_addr.s_addr = 0;
3115 } else {
3116 if (isdigit((uint8_t)buf[0])) {
3117 if (!inet_aton(buf, &saddr->sin_addr))
3118 return -1;
3119 } else {
3120 if ((he = gethostbyname(buf)) == NULL)
3121 return - 1;
3122 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3125 port = strtol(p, (char **)&r, 0);
3126 if (r == p)
3127 return -1;
3128 saddr->sin_port = htons(port);
3129 return 0;
3132 #ifndef _WIN32
3133 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3135 const char *p;
3136 int len;
3138 len = MIN(108, strlen(str));
3139 p = strchr(str, ',');
3140 if (p)
3141 len = MIN(len, p - str);
3143 memset(uaddr, 0, sizeof(*uaddr));
3145 uaddr->sun_family = AF_UNIX;
3146 memcpy(uaddr->sun_path, str, len);
3148 return 0;
3150 #endif
3152 /* find or alloc a new VLAN */
3153 VLANState *qemu_find_vlan(int id)
3155 VLANState **pvlan, *vlan;
3156 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3157 if (vlan->id == id)
3158 return vlan;
3160 vlan = qemu_mallocz(sizeof(VLANState));
3161 if (!vlan)
3162 return NULL;
3163 vlan->id = id;
3164 vlan->next = NULL;
3165 pvlan = &first_vlan;
3166 while (*pvlan != NULL)
3167 pvlan = &(*pvlan)->next;
3168 *pvlan = vlan;
3169 return vlan;
3172 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3173 IOReadHandler *fd_read,
3174 IOCanRWHandler *fd_can_read,
3175 void *opaque)
3177 VLANClientState *vc, **pvc;
3178 vc = qemu_mallocz(sizeof(VLANClientState));
3179 if (!vc)
3180 return NULL;
3181 vc->fd_read = fd_read;
3182 vc->fd_can_read = fd_can_read;
3183 vc->opaque = opaque;
3184 vc->vlan = vlan;
3186 vc->next = NULL;
3187 pvc = &vlan->first_client;
3188 while (*pvc != NULL)
3189 pvc = &(*pvc)->next;
3190 *pvc = vc;
3191 return vc;
3194 int qemu_can_send_packet(VLANClientState *vc1)
3196 VLANState *vlan = vc1->vlan;
3197 VLANClientState *vc;
3199 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3200 if (vc != vc1) {
3201 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3202 return 0;
3205 return 1;
3208 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3210 VLANState *vlan = vc1->vlan;
3211 VLANClientState *vc;
3213 #if 0
3214 printf("vlan %d send:\n", vlan->id);
3215 hex_dump(stdout, buf, size);
3216 #endif
3217 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3218 if (vc != vc1) {
3219 vc->fd_read(vc->opaque, buf, size);
3224 #if defined(CONFIG_SLIRP)
3226 /* slirp network adapter */
3228 static int slirp_inited;
3229 static VLANClientState *slirp_vc;
3231 int slirp_can_output(void)
3233 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3236 void slirp_output(const uint8_t *pkt, int pkt_len)
3238 #if 0
3239 printf("slirp output:\n");
3240 hex_dump(stdout, pkt, pkt_len);
3241 #endif
3242 if (!slirp_vc)
3243 return;
3244 qemu_send_packet(slirp_vc, pkt, pkt_len);
3247 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3249 #if 0
3250 printf("slirp input:\n");
3251 hex_dump(stdout, buf, size);
3252 #endif
3253 slirp_input(buf, size);
3256 static int net_slirp_init(VLANState *vlan)
3258 if (!slirp_inited) {
3259 slirp_inited = 1;
3260 slirp_init();
3262 slirp_vc = qemu_new_vlan_client(vlan,
3263 slirp_receive, NULL, NULL);
3264 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3265 return 0;
3268 static void net_slirp_redir(const char *redir_str)
3270 int is_udp;
3271 char buf[256], *r;
3272 const char *p;
3273 struct in_addr guest_addr;
3274 int host_port, guest_port;
3276 if (!slirp_inited) {
3277 slirp_inited = 1;
3278 slirp_init();
3281 p = redir_str;
3282 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3283 goto fail;
3284 if (!strcmp(buf, "tcp")) {
3285 is_udp = 0;
3286 } else if (!strcmp(buf, "udp")) {
3287 is_udp = 1;
3288 } else {
3289 goto fail;
3292 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3293 goto fail;
3294 host_port = strtol(buf, &r, 0);
3295 if (r == buf)
3296 goto fail;
3298 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3299 goto fail;
3300 if (buf[0] == '\0') {
3301 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3303 if (!inet_aton(buf, &guest_addr))
3304 goto fail;
3306 guest_port = strtol(p, &r, 0);
3307 if (r == p)
3308 goto fail;
3310 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3311 fprintf(stderr, "qemu: could not set up redirection\n");
3312 exit(1);
3314 return;
3315 fail:
3316 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3317 exit(1);
3320 #ifndef _WIN32
3322 char smb_dir[1024];
3324 static void smb_exit(void)
3326 DIR *d;
3327 struct dirent *de;
3328 char filename[1024];
3330 /* erase all the files in the directory */
3331 d = opendir(smb_dir);
3332 for(;;) {
3333 de = readdir(d);
3334 if (!de)
3335 break;
3336 if (strcmp(de->d_name, ".") != 0 &&
3337 strcmp(de->d_name, "..") != 0) {
3338 snprintf(filename, sizeof(filename), "%s/%s",
3339 smb_dir, de->d_name);
3340 unlink(filename);
3343 closedir(d);
3344 rmdir(smb_dir);
3347 /* automatic user mode samba server configuration */
3348 void net_slirp_smb(const char *exported_dir)
3350 char smb_conf[1024];
3351 char smb_cmdline[1024];
3352 FILE *f;
3354 if (!slirp_inited) {
3355 slirp_inited = 1;
3356 slirp_init();
3359 /* XXX: better tmp dir construction */
3360 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3361 if (mkdir(smb_dir, 0700) < 0) {
3362 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3363 exit(1);
3365 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3367 f = fopen(smb_conf, "w");
3368 if (!f) {
3369 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3370 exit(1);
3372 fprintf(f,
3373 "[global]\n"
3374 "private dir=%s\n"
3375 "smb ports=0\n"
3376 "socket address=127.0.0.1\n"
3377 "pid directory=%s\n"
3378 "lock directory=%s\n"
3379 "log file=%s/log.smbd\n"
3380 "smb passwd file=%s/smbpasswd\n"
3381 "security = share\n"
3382 "[qemu]\n"
3383 "path=%s\n"
3384 "read only=no\n"
3385 "guest ok=yes\n",
3386 smb_dir,
3387 smb_dir,
3388 smb_dir,
3389 smb_dir,
3390 smb_dir,
3391 exported_dir
3392 );
3393 fclose(f);
3394 atexit(smb_exit);
3396 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3397 SMBD_COMMAND, smb_conf);
3399 slirp_add_exec(0, smb_cmdline, 4, 139);
3402 #endif /* !defined(_WIN32) */
3404 #endif /* CONFIG_SLIRP */
3406 #if !defined(_WIN32)
3408 typedef struct TAPState {
3409 VLANClientState *vc;
3410 int fd;
3411 } TAPState;
3413 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3415 TAPState *s = opaque;
3416 int ret;
3417 for(;;) {
3418 ret = write(s->fd, buf, size);
3419 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3420 } else {
3421 break;
3426 static void tap_send(void *opaque)
3428 TAPState *s = opaque;
3429 uint8_t buf[4096];
3430 int size;
3432 size = read(s->fd, buf, sizeof(buf));
3433 if (size > 0) {
3434 qemu_send_packet(s->vc, buf, size);
3438 /* fd support */
3440 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3442 TAPState *s;
3444 s = qemu_mallocz(sizeof(TAPState));
3445 if (!s)
3446 return NULL;
3447 s->fd = fd;
3448 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3449 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3450 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3451 return s;
3454 #ifdef _BSD
3455 static int tap_open(char *ifname, int ifname_size)
3457 int fd;
3458 #ifndef TAPGIFNAME
3459 char *dev;
3460 struct stat s;
3461 #endif
3462 struct ifreq ifr;
3464 fd = open("/dev/tap", O_RDWR);
3465 if (fd < 0) {
3466 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation %s\n", strerror(errno));
3467 return -1;
3470 #ifdef TAPGIFNAME
3471 if (ioctl (fd, TAPGIFNAME, (void*)&ifr) < 0) {
3472 fprintf(stderr, "warning: could not open get tap name: %s\n",
3473 strerror(errno));
3474 return -1;
3476 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3477 #else
3478 fstat(fd, &s);
3479 dev = devname(s.st_rdev, S_IFCHR);
3480 pstrcpy(ifname, ifname_size, dev);
3481 #endif
3483 fcntl(fd, F_SETFL, O_NONBLOCK);
3484 return fd;
3486 #elif defined(__sun__)
3487 static int tap_open(char *ifname, int ifname_size)
3489 fprintf(stderr, "warning: tap_open not yet implemented\n");
3490 return -1;
3492 #else
3493 static int tap_open(char *ifname, int ifname_size)
3495 struct ifreq ifr;
3496 int fd, ret, retries = 0;
3498 fd = open("/dev/net/tun", O_RDWR);
3499 if (fd < 0) {
3500 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3501 return -1;
3503 memset(&ifr, 0, sizeof(ifr));
3504 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3505 if (ifname[0] != '\0')
3506 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3507 else
3508 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3509 do {
3510 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3511 } while ((ret != 0) && (retries++ < 3));
3512 if (ret != 0) {
3513 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3514 close(fd);
3515 return -1;
3517 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3518 fcntl(fd, F_SETFL, O_NONBLOCK);
3519 return fd;
3521 #endif
3523 static int net_tap_init(VLANState *vlan, const char *ifname1,
3524 const char *setup_script, const char *bridge)
3526 TAPState *s;
3527 int pid, status, fd;
3528 char *args[4];
3529 char **parg;
3530 char ifname[128];
3532 memset(ifname, 0, sizeof(ifname));
3534 if (ifname1 != NULL)
3535 pstrcpy(ifname, sizeof(ifname), ifname1);
3536 else
3537 ifname[0] = '\0';
3538 fd = tap_open(ifname, sizeof(ifname));
3539 if (fd < 0)
3540 return -1;
3542 if (!setup_script || !strcmp(setup_script, "no"))
3543 setup_script = "";
3544 if (setup_script[0] != '\0') {
3545 /* try to launch network init script */
3546 pid = fork();
3547 if (pid >= 0) {
3548 if (pid == 0) {
3549 int open_max = sysconf(_SC_OPEN_MAX), i;
3550 for (i = 0; i < open_max; i++)
3551 if (i != STDIN_FILENO &&
3552 i != STDOUT_FILENO &&
3553 i != STDERR_FILENO &&
3554 i != fd)
3555 close(i);
3557 parg = args;
3558 *parg++ = (char *)setup_script;
3559 *parg++ = ifname;
3560 *parg++ = (char *)bridge;
3561 *parg++ = NULL;
3562 execv(setup_script, args);
3563 _exit(1);
3565 while (waitpid(pid, &status, 0) != pid);
3566 if (!WIFEXITED(status) ||
3567 WEXITSTATUS(status) != 0) {
3568 fprintf(stderr, "%s: could not launch network script\n",
3569 setup_script);
3570 return -1;
3574 s = net_tap_fd_init(vlan, fd);
3575 if (!s)
3576 return -1;
3577 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3578 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3579 return 0;
3582 #endif /* !_WIN32 */
3584 /* network connection */
3585 typedef struct NetSocketState {
3586 VLANClientState *vc;
3587 int fd;
3588 int state; /* 0 = getting length, 1 = getting data */
3589 int index;
3590 int packet_len;
3591 uint8_t buf[4096];
3592 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3593 } NetSocketState;
3595 typedef struct NetSocketListenState {
3596 VLANState *vlan;
3597 int fd;
3598 } NetSocketListenState;
3600 /* XXX: we consider we can send the whole packet without blocking */
3601 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3603 NetSocketState *s = opaque;
3604 uint32_t len;
3605 len = htonl(size);
3607 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3608 send_all(s->fd, buf, size);
3611 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3613 NetSocketState *s = opaque;
3614 sendto(s->fd, buf, size, 0,
3615 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3618 static void net_socket_send(void *opaque)
3620 NetSocketState *s = opaque;
3621 int l, size, err;
3622 uint8_t buf1[4096];
3623 const uint8_t *buf;
3625 size = recv(s->fd, buf1, sizeof(buf1), 0);
3626 if (size < 0) {
3627 err = socket_error();
3628 if (err != EWOULDBLOCK)
3629 goto eoc;
3630 } else if (size == 0) {
3631 /* end of connection */
3632 eoc:
3633 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3634 closesocket(s->fd);
3635 return;
3637 buf = buf1;
3638 while (size > 0) {
3639 /* reassemble a packet from the network */
3640 switch(s->state) {
3641 case 0:
3642 l = 4 - s->index;
3643 if (l > size)
3644 l = size;
3645 memcpy(s->buf + s->index, buf, l);
3646 buf += l;
3647 size -= l;
3648 s->index += l;
3649 if (s->index == 4) {
3650 /* got length */
3651 s->packet_len = ntohl(*(uint32_t *)s->buf);
3652 s->index = 0;
3653 s->state = 1;
3655 break;
3656 case 1:
3657 l = s->packet_len - s->index;
3658 if (l > size)
3659 l = size;
3660 memcpy(s->buf + s->index, buf, l);
3661 s->index += l;
3662 buf += l;
3663 size -= l;
3664 if (s->index >= s->packet_len) {
3665 qemu_send_packet(s->vc, s->buf, s->packet_len);
3666 s->index = 0;
3667 s->state = 0;
3669 break;
3674 static void net_socket_send_dgram(void *opaque)
3676 NetSocketState *s = opaque;
3677 int size;
3679 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3680 if (size < 0)
3681 return;
3682 if (size == 0) {
3683 /* end of connection */
3684 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3685 return;
3687 qemu_send_packet(s->vc, s->buf, size);
3690 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3692 struct ip_mreq imr;
3693 int fd;
3694 int val, ret;
3695 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3696 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3697 inet_ntoa(mcastaddr->sin_addr),
3698 (int)ntohl(mcastaddr->sin_addr.s_addr));
3699 return -1;
3702 fd = socket(PF_INET, SOCK_DGRAM, 0);
3703 if (fd < 0) {
3704 perror("socket(PF_INET, SOCK_DGRAM)");
3705 return -1;
3708 val = 1;
3709 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3710 (const char *)&val, sizeof(char));
3711 if (ret < 0) {
3712 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3713 goto fail;
3716 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3717 if (ret < 0) {
3718 perror("bind");
3719 goto fail;
3722 /* Add host to multicast group */
3723 imr.imr_multiaddr = mcastaddr->sin_addr;
3724 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3726 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3727 (const char *)&imr, sizeof(struct ip_mreq));
3728 if (ret < 0) {
3729 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3730 goto fail;
3733 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3734 val = 1;
3735 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3736 (const char *)&val, sizeof(val));
3737 if (ret < 0) {
3738 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3739 goto fail;
3742 socket_set_nonblock(fd);
3743 return fd;
3744 fail:
3745 if (fd >= 0)
3746 closesocket(fd);
3747 return -1;
3750 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3751 int is_connected)
3753 struct sockaddr_in saddr;
3754 int newfd;
3755 socklen_t saddr_len;
3756 NetSocketState *s;
3758 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3759 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3760 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3761 */
3763 if (is_connected) {
3764 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3765 /* must be bound */
3766 if (saddr.sin_addr.s_addr==0) {
3767 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3768 fd);
3769 return NULL;
3771 /* clone dgram socket */
3772 newfd = net_socket_mcast_create(&saddr);
3773 if (newfd < 0) {
3774 /* error already reported by net_socket_mcast_create() */
3775 close(fd);
3776 return NULL;
3778 /* clone newfd to fd, close newfd */
3779 dup2(newfd, fd);
3780 close(newfd);
3782 } else {
3783 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3784 fd, strerror(errno));
3785 return NULL;
3789 s = qemu_mallocz(sizeof(NetSocketState));
3790 if (!s)
3791 return NULL;
3792 s->fd = fd;
3794 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3795 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3797 /* mcast: save bound address as dst */
3798 if (is_connected) s->dgram_dst=saddr;
3800 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3801 "socket: fd=%d (%s mcast=%s:%d)",
3802 fd, is_connected? "cloned" : "",
3803 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3804 return s;
3807 static void net_socket_connect(void *opaque)
3809 NetSocketState *s = opaque;
3810 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3813 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3814 int is_connected)
3816 NetSocketState *s;
3817 s = qemu_mallocz(sizeof(NetSocketState));
3818 if (!s)
3819 return NULL;
3820 s->fd = fd;
3821 s->vc = qemu_new_vlan_client(vlan,
3822 net_socket_receive, NULL, s);
3823 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3824 "socket: fd=%d", fd);
3825 if (is_connected) {
3826 net_socket_connect(s);
3827 } else {
3828 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3830 return s;
3833 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3834 int is_connected)
3836 int so_type=-1, optlen=sizeof(so_type);
3838 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3839 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3840 return NULL;
3842 switch(so_type) {
3843 case SOCK_DGRAM:
3844 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3845 case SOCK_STREAM:
3846 return net_socket_fd_init_stream(vlan, fd, is_connected);
3847 default:
3848 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3849 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3850 return net_socket_fd_init_stream(vlan, fd, is_connected);
3852 return NULL;
3855 static void net_socket_accept(void *opaque)
3857 NetSocketListenState *s = opaque;
3858 NetSocketState *s1;
3859 struct sockaddr_in saddr;
3860 socklen_t len;
3861 int fd;
3863 for(;;) {
3864 len = sizeof(saddr);
3865 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3866 if (fd < 0 && errno != EINTR) {
3867 return;
3868 } else if (fd >= 0) {
3869 break;
3872 s1 = net_socket_fd_init(s->vlan, fd, 1);
3873 if (!s1) {
3874 closesocket(fd);
3875 } else {
3876 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3877 "socket: connection from %s:%d",
3878 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3882 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3884 NetSocketListenState *s;
3885 int fd, val, ret;
3886 struct sockaddr_in saddr;
3888 if (parse_host_port(&saddr, host_str) < 0)
3889 return -1;
3891 s = qemu_mallocz(sizeof(NetSocketListenState));
3892 if (!s)
3893 return -1;
3895 fd = socket(PF_INET, SOCK_STREAM, 0);
3896 if (fd < 0) {
3897 perror("socket");
3898 return -1;
3900 socket_set_nonblock(fd);
3902 /* allow fast reuse */
3903 val = 1;
3904 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3906 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3907 if (ret < 0) {
3908 perror("bind");
3909 return -1;
3911 ret = listen(fd, 0);
3912 if (ret < 0) {
3913 perror("listen");
3914 return -1;
3916 s->vlan = vlan;
3917 s->fd = fd;
3918 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3919 return 0;
3922 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3924 NetSocketState *s;
3925 int fd, connected, ret, err;
3926 struct sockaddr_in saddr;
3928 if (parse_host_port(&saddr, host_str) < 0)
3929 return -1;
3931 fd = socket(PF_INET, SOCK_STREAM, 0);
3932 if (fd < 0) {
3933 perror("socket");
3934 return -1;
3936 socket_set_nonblock(fd);
3938 connected = 0;
3939 for(;;) {
3940 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3941 if (ret < 0) {
3942 err = socket_error();
3943 if (err == EINTR || err == EWOULDBLOCK) {
3944 } else if (err == EINPROGRESS) {
3945 break;
3946 } else {
3947 perror("connect");
3948 closesocket(fd);
3949 return -1;
3951 } else {
3952 connected = 1;
3953 break;
3956 s = net_socket_fd_init(vlan, fd, connected);
3957 if (!s)
3958 return -1;
3959 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3960 "socket: connect to %s:%d",
3961 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3962 return 0;
3965 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3967 NetSocketState *s;
3968 int fd;
3969 struct sockaddr_in saddr;
3971 if (parse_host_port(&saddr, host_str) < 0)
3972 return -1;
3975 fd = net_socket_mcast_create(&saddr);
3976 if (fd < 0)
3977 return -1;
3979 s = net_socket_fd_init(vlan, fd, 0);
3980 if (!s)
3981 return -1;
3983 s->dgram_dst = saddr;
3985 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3986 "socket: mcast=%s:%d",
3987 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3988 return 0;
3992 static int get_param_value(char *buf, size_t buf_size,
3993 const char *tag, const char *str)
3995 const char *p;
3996 char *q;
3997 char option[128];
3999 p = str;
4000 for(;;) {
4001 q = option;
4002 while (*p != '\0' && *p != '=') {
4003 if ((q - option) < sizeof(option) - 1)
4004 *q++ = *p;
4005 p++;
4007 *q = '\0';
4008 if (*p != '=')
4009 break;
4010 p++;
4011 if (!strcmp(tag, option)) {
4012 q = buf;
4013 while (*p != '\0' && *p != ',') {
4014 if ((q - buf) < buf_size - 1)
4015 *q++ = *p;
4016 p++;
4018 *q = '\0';
4019 return q - buf;
4020 } else {
4021 while (*p != '\0' && *p != ',') {
4022 p++;
4025 if (*p != ',')
4026 break;
4027 p++;
4029 return 0;
4032 static int net_client_init(const char *str)
4034 const char *p;
4035 char *q;
4036 char device[64];
4037 char buf[1024];
4038 int vlan_id, ret;
4039 VLANState *vlan;
4041 p = str;
4042 q = device;
4043 while (*p != '\0' && *p != ',') {
4044 if ((q - device) < sizeof(device) - 1)
4045 *q++ = *p;
4046 p++;
4048 *q = '\0';
4049 if (*p == ',')
4050 p++;
4051 vlan_id = 0;
4052 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4053 vlan_id = strtol(buf, NULL, 0);
4055 vlan = qemu_find_vlan(vlan_id);
4056 if (!vlan) {
4057 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4058 return -1;
4060 if (!strcmp(device, "nic")) {
4061 NICInfo *nd;
4062 uint8_t *macaddr;
4064 if (nb_nics < MAX_NICS) {
4065 nd = &nd_table[nb_nics];
4066 macaddr = nd->macaddr;
4067 macaddr[0] = 0x52;
4068 macaddr[1] = 0x54;
4069 macaddr[2] = 0x00;
4070 macaddr[3] = 0x12;
4071 macaddr[4] = 0x34;
4072 macaddr[5] = 0x56 + nb_nics;
4074 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4075 if (parse_macaddr(macaddr, buf) < 0) {
4076 fprintf(stderr, "invalid syntax for ethernet address\n");
4077 return -1;
4080 if (get_param_value(buf, sizeof(buf), "model", p)) {
4081 nd->model = strdup(buf);
4083 nd->vlan = vlan;
4084 nb_nics++;
4085 } else {
4086 fprintf(stderr, "Too Many NICs\n");
4088 ret = 0;
4089 } else
4090 if (!strcmp(device, "none")) {
4091 /* does nothing. It is needed to signal that no network cards
4092 are wanted */
4093 ret = 0;
4094 } else
4095 #ifdef CONFIG_SLIRP
4096 if (!strcmp(device, "user")) {
4097 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4098 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4100 ret = net_slirp_init(vlan);
4101 } else
4102 #endif
4103 #ifdef _WIN32
4104 if (!strcmp(device, "tap")) {
4105 char ifname[64];
4106 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4107 fprintf(stderr, "tap: no interface name\n");
4108 return -1;
4110 ret = tap_win32_init(vlan, ifname);
4111 } else
4112 #else
4113 if (!strcmp(device, "tap")) {
4114 char ifname[64];
4115 char setup_script[1024];
4116 char bridge[16];
4117 int fd;
4119 memset(ifname, 0, sizeof(ifname));
4120 memset(setup_script, 0, sizeof(setup_script));
4122 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4123 fd = strtol(buf, NULL, 0);
4124 ret = -1;
4125 if (net_tap_fd_init(vlan, fd))
4126 ret = 0;
4127 } else {
4128 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4129 ifname[0] = '\0';
4131 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4132 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4134 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4135 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4137 ret = net_tap_init(vlan, ifname, setup_script, bridge);
4139 } else
4140 #endif
4141 if (!strcmp(device, "socket")) {
4142 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4143 int fd;
4144 fd = strtol(buf, NULL, 0);
4145 ret = -1;
4146 if (net_socket_fd_init(vlan, fd, 1))
4147 ret = 0;
4148 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4149 ret = net_socket_listen_init(vlan, buf);
4150 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4151 ret = net_socket_connect_init(vlan, buf);
4152 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4153 ret = net_socket_mcast_init(vlan, buf);
4154 } else {
4155 fprintf(stderr, "Unknown socket options: %s\n", p);
4156 return -1;
4158 } else
4160 fprintf(stderr, "Unknown network device: %s\n", device);
4161 return -1;
4163 if (ret < 0) {
4164 fprintf(stderr, "Could not initialize device '%s'\n", device);
4167 return ret;
4170 void do_info_network(void)
4172 VLANState *vlan;
4173 VLANClientState *vc;
4175 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4176 term_printf("VLAN %d devices:\n", vlan->id);
4177 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4178 term_printf(" %s\n", vc->info_str);
4182 /***********************************************************/
4183 /* USB devices */
4185 static USBPort *used_usb_ports;
4186 static USBPort *free_usb_ports;
4188 /* ??? Maybe change this to register a hub to keep track of the topology. */
4189 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4190 usb_attachfn attach)
4192 port->opaque = opaque;
4193 port->index = index;
4194 port->attach = attach;
4195 port->next = free_usb_ports;
4196 free_usb_ports = port;
4199 static int usb_device_add(const char *devname)
4201 const char *p;
4202 USBDevice *dev;
4203 USBPort *port;
4204 char usb_name[256] = "USB ";
4206 if (!free_usb_ports)
4207 return -1;
4209 if (strstart(devname, "host:", &p)) {
4210 dev = usb_host_device_open(p);
4211 } else if (!strcmp(devname, "mouse")) {
4212 dev = usb_mouse_init();
4213 } else if (!strcmp(devname, "tablet")) {
4214 dev = usb_tablet_init();
4215 } else if (strstart(devname, "disk:", &p)) {
4216 dev = usb_msd_init(p);
4217 } else {
4218 return -1;
4220 if (!dev)
4221 return -1;
4223 /* Find a USB port to add the device to. */
4224 port = free_usb_ports;
4225 if (!port->next) {
4226 USBDevice *hub;
4228 /* Create a new hub and chain it on. */
4229 free_usb_ports = NULL;
4230 port->next = used_usb_ports;
4231 used_usb_ports = port;
4233 hub = usb_hub_init(VM_USB_HUB_SIZE);
4234 usb_attach(port, hub);
4235 port = free_usb_ports;
4238 free_usb_ports = port->next;
4239 port->next = used_usb_ports;
4240 used_usb_ports = port;
4242 pstrcpy(usb_name + strlen(usb_name),
4243 sizeof(usb_name) - strlen(usb_name),
4244 devname);
4245 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4247 usb_attach(port, dev);
4248 return 0;
4251 static int usb_device_del(const char *devname)
4253 USBPort *port;
4254 USBPort **lastp;
4255 USBDevice *dev;
4256 int bus_num, addr;
4257 const char *p;
4259 if (!used_usb_ports)
4260 return -1;
4262 p = strchr(devname, '.');
4263 if (!p)
4264 return -1;
4265 bus_num = strtoul(devname, NULL, 0);
4266 addr = strtoul(p + 1, NULL, 0);
4267 if (bus_num != 0)
4268 return -1;
4270 lastp = &used_usb_ports;
4271 port = used_usb_ports;
4272 while (port && port->dev->addr != addr) {
4273 lastp = &port->next;
4274 port = port->next;
4277 if (!port)
4278 return -1;
4280 dev = port->dev;
4281 *lastp = port->next;
4282 usb_attach(port, NULL);
4283 dev->handle_destroy(dev);
4284 port->next = free_usb_ports;
4285 free_usb_ports = port;
4286 return 0;
4289 void do_usb_add(const char *devname)
4291 int ret;
4292 ret = usb_device_add(devname);
4293 if (ret < 0)
4294 term_printf("Could not add USB device '%s'\n", devname);
4297 void do_usb_del(const char *devname)
4299 int ret;
4300 ret = usb_device_del(devname);
4301 if (ret < 0)
4302 term_printf("Could not remove USB device '%s'\n", devname);
4305 void usb_info(void)
4307 USBDevice *dev;
4308 USBPort *port;
4309 const char *speed_str;
4311 if (!usb_enabled) {
4312 term_printf("USB support not enabled\n");
4313 return;
4316 for (port = used_usb_ports; port; port = port->next) {
4317 dev = port->dev;
4318 if (!dev)
4319 continue;
4320 switch(dev->speed) {
4321 case USB_SPEED_LOW:
4322 speed_str = "1.5";
4323 break;
4324 case USB_SPEED_FULL:
4325 speed_str = "12";
4326 break;
4327 case USB_SPEED_HIGH:
4328 speed_str = "480";
4329 break;
4330 default:
4331 speed_str = "?";
4332 break;
4334 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4335 0, dev->addr, speed_str, dev->devname);
4339 /***********************************************************/
4340 /* pid file */
4342 static char *pid_filename;
4344 /* Remove PID file. Called on normal exit */
4346 static void remove_pidfile(void)
4348 unlink (pid_filename);
4351 static void create_pidfile(const char *filename)
4353 struct stat pidstat;
4354 FILE *f;
4356 /* Try to write our PID to the named file */
4357 if (stat(filename, &pidstat) < 0) {
4358 if (errno == ENOENT) {
4359 if ((f = fopen (filename, "w")) == NULL) {
4360 perror("Opening pidfile");
4361 exit(1);
4363 fprintf(f, "%ld\n", (long)getpid());
4364 fclose(f);
4365 pid_filename = qemu_strdup(filename);
4366 if (!pid_filename) {
4367 fprintf(stderr, "Could not save PID filename");
4368 exit(1);
4370 atexit(remove_pidfile);
4372 } else {
4373 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4374 filename);
4375 exit(1);
4379 /***********************************************************/
4380 /* dumb display */
4382 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4386 static void dumb_resize(DisplayState *ds, int w, int h)
4390 static void dumb_refresh(DisplayState *ds)
4392 vga_hw_update();
4395 void dumb_display_init(DisplayState *ds)
4397 ds->data = NULL;
4398 ds->linesize = 0;
4399 ds->depth = 0;
4400 ds->dpy_update = dumb_update;
4401 ds->dpy_resize = dumb_resize;
4402 ds->dpy_refresh = dumb_refresh;
4405 /***********************************************************/
4406 /* I/O handling */
4408 #define MAX_IO_HANDLERS 64
4410 typedef struct IOHandlerRecord {
4411 int fd;
4412 IOCanRWHandler *fd_read_poll;
4413 IOHandler *fd_read;
4414 IOHandler *fd_write;
4415 int deleted;
4416 void *opaque;
4417 /* temporary data */
4418 struct pollfd *ufd;
4419 struct IOHandlerRecord *next;
4420 } IOHandlerRecord;
4422 static IOHandlerRecord *first_io_handler;
4424 /* XXX: fd_read_poll should be suppressed, but an API change is
4425 necessary in the character devices to suppress fd_can_read(). */
4426 int qemu_set_fd_handler2(int fd,
4427 IOCanRWHandler *fd_read_poll,
4428 IOHandler *fd_read,
4429 IOHandler *fd_write,
4430 void *opaque)
4432 IOHandlerRecord **pioh, *ioh;
4434 if (!fd_read && !fd_write) {
4435 pioh = &first_io_handler;
4436 for(;;) {
4437 ioh = *pioh;
4438 if (ioh == NULL)
4439 break;
4440 if (ioh->fd == fd) {
4441 ioh->deleted = 1;
4442 break;
4444 pioh = &ioh->next;
4446 } else {
4447 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4448 if (ioh->fd == fd)
4449 goto found;
4451 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4452 if (!ioh)
4453 return -1;
4454 ioh->next = first_io_handler;
4455 first_io_handler = ioh;
4456 found:
4457 ioh->fd = fd;
4458 ioh->fd_read_poll = fd_read_poll;
4459 ioh->fd_read = fd_read;
4460 ioh->fd_write = fd_write;
4461 ioh->opaque = opaque;
4462 ioh->deleted = 0;
4464 return 0;
4467 int qemu_set_fd_handler(int fd,
4468 IOHandler *fd_read,
4469 IOHandler *fd_write,
4470 void *opaque)
4472 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4475 /***********************************************************/
4476 /* Polling handling */
4478 typedef struct PollingEntry {
4479 PollingFunc *func;
4480 void *opaque;
4481 struct PollingEntry *next;
4482 } PollingEntry;
4484 static PollingEntry *first_polling_entry;
4486 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4488 PollingEntry **ppe, *pe;
4489 pe = qemu_mallocz(sizeof(PollingEntry));
4490 if (!pe)
4491 return -1;
4492 pe->func = func;
4493 pe->opaque = opaque;
4494 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4495 *ppe = pe;
4496 return 0;
4499 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4501 PollingEntry **ppe, *pe;
4502 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4503 pe = *ppe;
4504 if (pe->func == func && pe->opaque == opaque) {
4505 *ppe = pe->next;
4506 qemu_free(pe);
4507 break;
4512 #ifdef _WIN32
4513 /***********************************************************/
4514 /* Wait objects support */
4515 typedef struct WaitObjects {
4516 int num;
4517 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4518 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4519 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4520 } WaitObjects;
4522 static WaitObjects wait_objects = {0};
4524 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4526 WaitObjects *w = &wait_objects;
4528 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4529 return -1;
4530 w->events[w->num] = handle;
4531 w->func[w->num] = func;
4532 w->opaque[w->num] = opaque;
4533 w->num++;
4534 return 0;
4537 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4539 int i, found;
4540 WaitObjects *w = &wait_objects;
4542 found = 0;
4543 for (i = 0; i < w->num; i++) {
4544 if (w->events[i] == handle)
4545 found = 1;
4546 if (found) {
4547 w->events[i] = w->events[i + 1];
4548 w->func[i] = w->func[i + 1];
4549 w->opaque[i] = w->opaque[i + 1];
4552 if (found)
4553 w->num--;
4555 #endif
4557 /***********************************************************/
4558 /* savevm/loadvm support */
4560 #define IO_BUF_SIZE 32768
4562 struct QEMUFile {
4563 FILE *outfile;
4564 BlockDriverState *bs;
4565 int is_file;
4566 int is_writable;
4567 int64_t base_offset;
4568 int64_t buf_offset; /* start of buffer when writing, end of buffer
4569 when reading */
4570 int buf_index;
4571 int buf_size; /* 0 when writing */
4572 uint8_t buf[IO_BUF_SIZE];
4573 };
4575 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4577 QEMUFile *f;
4579 f = qemu_mallocz(sizeof(QEMUFile));
4580 if (!f)
4581 return NULL;
4582 if (!strcmp(mode, "wb")) {
4583 f->is_writable = 1;
4584 } else if (!strcmp(mode, "rb")) {
4585 f->is_writable = 0;
4586 } else {
4587 goto fail;
4589 f->outfile = fopen(filename, mode);
4590 if (!f->outfile)
4591 goto fail;
4592 f->is_file = 1;
4593 return f;
4594 fail:
4595 if (f->outfile)
4596 fclose(f->outfile);
4597 qemu_free(f);
4598 return NULL;
4601 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4603 QEMUFile *f;
4605 f = qemu_mallocz(sizeof(QEMUFile));
4606 if (!f)
4607 return NULL;
4608 f->is_file = 0;
4609 f->bs = bs;
4610 f->is_writable = is_writable;
4611 f->base_offset = offset;
4612 return f;
4615 void qemu_fflush(QEMUFile *f)
4617 if (!f->is_writable)
4618 return;
4619 if (f->buf_index > 0) {
4620 if (f->is_file) {
4621 fseek(f->outfile, f->buf_offset, SEEK_SET);
4622 fwrite(f->buf, 1, f->buf_index, f->outfile);
4623 } else {
4624 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4625 f->buf, f->buf_index);
4627 f->buf_offset += f->buf_index;
4628 f->buf_index = 0;
4632 static void qemu_fill_buffer(QEMUFile *f)
4634 int len;
4636 if (f->is_writable)
4637 return;
4638 if (f->is_file) {
4639 fseek(f->outfile, f->buf_offset, SEEK_SET);
4640 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4641 if (len < 0)
4642 len = 0;
4643 } else {
4644 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4645 f->buf, IO_BUF_SIZE);
4646 if (len < 0)
4647 len = 0;
4649 f->buf_index = 0;
4650 f->buf_size = len;
4651 f->buf_offset += len;
4654 void qemu_fclose(QEMUFile *f)
4656 if (f->is_writable)
4657 qemu_fflush(f);
4658 if (f->is_file) {
4659 fclose(f->outfile);
4661 qemu_free(f);
4664 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4666 int l;
4667 while (size > 0) {
4668 l = IO_BUF_SIZE - f->buf_index;
4669 if (l > size)
4670 l = size;
4671 memcpy(f->buf + f->buf_index, buf, l);
4672 f->buf_index += l;
4673 buf += l;
4674 size -= l;
4675 if (f->buf_index >= IO_BUF_SIZE)
4676 qemu_fflush(f);
4680 void qemu_put_byte(QEMUFile *f, int v)
4682 f->buf[f->buf_index++] = v;
4683 if (f->buf_index >= IO_BUF_SIZE)
4684 qemu_fflush(f);
4687 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4689 int size, l;
4691 size = size1;
4692 while (size > 0) {
4693 l = f->buf_size - f->buf_index;
4694 if (l == 0) {
4695 qemu_fill_buffer(f);
4696 l = f->buf_size - f->buf_index;
4697 if (l == 0)
4698 break;
4700 if (l > size)
4701 l = size;
4702 memcpy(buf, f->buf + f->buf_index, l);
4703 f->buf_index += l;
4704 buf += l;
4705 size -= l;
4707 return size1 - size;
4710 int qemu_get_byte(QEMUFile *f)
4712 if (f->buf_index >= f->buf_size) {
4713 qemu_fill_buffer(f);
4714 if (f->buf_index >= f->buf_size)
4715 return 0;
4717 return f->buf[f->buf_index++];
4720 int64_t qemu_ftell(QEMUFile *f)
4722 return f->buf_offset - f->buf_size + f->buf_index;
4725 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4727 if (whence == SEEK_SET) {
4728 /* nothing to do */
4729 } else if (whence == SEEK_CUR) {
4730 pos += qemu_ftell(f);
4731 } else {
4732 /* SEEK_END not supported */
4733 return -1;
4735 if (f->is_writable) {
4736 qemu_fflush(f);
4737 f->buf_offset = pos;
4738 } else {
4739 f->buf_offset = pos;
4740 f->buf_index = 0;
4741 f->buf_size = 0;
4743 return pos;
4746 void qemu_put_be16(QEMUFile *f, unsigned int v)
4748 qemu_put_byte(f, v >> 8);
4749 qemu_put_byte(f, v);
4752 void qemu_put_be32(QEMUFile *f, unsigned int v)
4754 qemu_put_byte(f, v >> 24);
4755 qemu_put_byte(f, v >> 16);
4756 qemu_put_byte(f, v >> 8);
4757 qemu_put_byte(f, v);
4760 void qemu_put_be64(QEMUFile *f, uint64_t v)
4762 qemu_put_be32(f, v >> 32);
4763 qemu_put_be32(f, v);
4766 unsigned int qemu_get_be16(QEMUFile *f)
4768 unsigned int v;
4769 v = qemu_get_byte(f) << 8;
4770 v |= qemu_get_byte(f);
4771 return v;
4774 unsigned int qemu_get_be32(QEMUFile *f)
4776 unsigned int v;
4777 v = qemu_get_byte(f) << 24;
4778 v |= qemu_get_byte(f) << 16;
4779 v |= qemu_get_byte(f) << 8;
4780 v |= qemu_get_byte(f);
4781 return v;
4784 uint64_t qemu_get_be64(QEMUFile *f)
4786 uint64_t v;
4787 v = (uint64_t)qemu_get_be32(f) << 32;
4788 v |= qemu_get_be32(f);
4789 return v;
4792 typedef struct SaveStateEntry {
4793 char idstr[256];
4794 int instance_id;
4795 int version_id;
4796 SaveStateHandler *save_state;
4797 LoadStateHandler *load_state;
4798 void *opaque;
4799 struct SaveStateEntry *next;
4800 } SaveStateEntry;
4802 static SaveStateEntry *first_se;
4804 int register_savevm(const char *idstr,
4805 int instance_id,
4806 int version_id,
4807 SaveStateHandler *save_state,
4808 LoadStateHandler *load_state,
4809 void *opaque)
4811 SaveStateEntry *se, **pse;
4813 se = qemu_malloc(sizeof(SaveStateEntry));
4814 if (!se)
4815 return -1;
4816 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4817 se->instance_id = instance_id;
4818 se->version_id = version_id;
4819 se->save_state = save_state;
4820 se->load_state = load_state;
4821 se->opaque = opaque;
4822 se->next = NULL;
4824 /* add at the end of list */
4825 pse = &first_se;
4826 while (*pse != NULL)
4827 pse = &(*pse)->next;
4828 *pse = se;
4829 return 0;
4832 #define QEMU_VM_FILE_MAGIC 0x5145564d
4833 #define QEMU_VM_FILE_VERSION 0x00000002
4835 int qemu_savevm_state(QEMUFile *f)
4837 SaveStateEntry *se;
4838 int len, ret;
4839 int64_t cur_pos, len_pos, total_len_pos;
4841 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4842 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4843 total_len_pos = qemu_ftell(f);
4844 qemu_put_be64(f, 0); /* total size */
4846 for(se = first_se; se != NULL; se = se->next) {
4847 /* ID string */
4848 len = strlen(se->idstr);
4849 qemu_put_byte(f, len);
4850 qemu_put_buffer(f, se->idstr, len);
4852 qemu_put_be32(f, se->instance_id);
4853 qemu_put_be32(f, se->version_id);
4855 /* record size: filled later */
4856 len_pos = qemu_ftell(f);
4857 qemu_put_be32(f, 0);
4859 se->save_state(f, se->opaque);
4861 /* fill record size */
4862 cur_pos = qemu_ftell(f);
4863 len = cur_pos - len_pos - 4;
4864 qemu_fseek(f, len_pos, SEEK_SET);
4865 qemu_put_be32(f, len);
4866 qemu_fseek(f, cur_pos, SEEK_SET);
4868 cur_pos = qemu_ftell(f);
4869 qemu_fseek(f, total_len_pos, SEEK_SET);
4870 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4871 qemu_fseek(f, cur_pos, SEEK_SET);
4873 ret = 0;
4874 return ret;
4877 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4879 SaveStateEntry *se;
4881 for(se = first_se; se != NULL; se = se->next) {
4882 if (!strcmp(se->idstr, idstr) &&
4883 instance_id == se->instance_id)
4884 return se;
4886 return NULL;
4889 int qemu_loadvm_state(QEMUFile *f)
4891 SaveStateEntry *se;
4892 int len, ret, instance_id, record_len, version_id;
4893 int64_t total_len, end_pos, cur_pos;
4894 unsigned int v;
4895 char idstr[256];
4897 v = qemu_get_be32(f);
4898 if (v != QEMU_VM_FILE_MAGIC)
4899 goto fail;
4900 v = qemu_get_be32(f);
4901 if (v != QEMU_VM_FILE_VERSION) {
4902 fail:
4903 ret = -1;
4904 goto the_end;
4906 total_len = qemu_get_be64(f);
4907 end_pos = total_len + qemu_ftell(f);
4908 for(;;) {
4909 if (qemu_ftell(f) >= end_pos)
4910 break;
4911 len = qemu_get_byte(f);
4912 qemu_get_buffer(f, idstr, len);
4913 idstr[len] = '\0';
4914 instance_id = qemu_get_be32(f);
4915 version_id = qemu_get_be32(f);
4916 record_len = qemu_get_be32(f);
4917 #if 0
4918 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4919 idstr, instance_id, version_id, record_len);
4920 #endif
4921 cur_pos = qemu_ftell(f);
4922 se = find_se(idstr, instance_id);
4923 if (!se) {
4924 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4925 instance_id, idstr);
4926 } else {
4927 ret = se->load_state(f, se->opaque, version_id);
4928 if (ret < 0) {
4929 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4930 instance_id, idstr);
4933 /* always seek to exact end of record */
4934 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4936 ret = 0;
4937 the_end:
4938 return ret;
4941 /* device can contain snapshots */
4942 static int bdrv_can_snapshot(BlockDriverState *bs)
4944 return (bs &&
4945 !bdrv_is_removable(bs) &&
4946 !bdrv_is_read_only(bs));
4949 /* device must be snapshots in order to have a reliable snapshot */
4950 static int bdrv_has_snapshot(BlockDriverState *bs)
4952 return (bs &&
4953 !bdrv_is_removable(bs) &&
4954 !bdrv_is_read_only(bs));
4957 static BlockDriverState *get_bs_snapshots(void)
4959 BlockDriverState *bs;
4960 int i;
4962 if (bs_snapshots)
4963 return bs_snapshots;
4964 for(i = 0; i <= MAX_DISKS; i++) {
4965 bs = bs_table[i];
4966 if (bdrv_can_snapshot(bs))
4967 goto ok;
4969 return NULL;
4970 ok:
4971 bs_snapshots = bs;
4972 return bs;
4975 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4976 const char *name)
4978 QEMUSnapshotInfo *sn_tab, *sn;
4979 int nb_sns, i, ret;
4981 ret = -ENOENT;
4982 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4983 if (nb_sns < 0)
4984 return ret;
4985 for(i = 0; i < nb_sns; i++) {
4986 sn = &sn_tab[i];
4987 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4988 *sn_info = *sn;
4989 ret = 0;
4990 break;
4993 qemu_free(sn_tab);
4994 return ret;
4997 #ifdef CONFIG_DM
4998 /* We use simpler state save/load functions for Xen */
4999 void do_savevm(const char *name)
5001 QEMUFile *f;
5002 int saved_vm_running, ret;
5004 f = qemu_fopen(name, "wb");
5006 /* ??? Should this occur after vm_stop? */
5007 qemu_aio_flush();
5009 saved_vm_running = vm_running;
5010 vm_stop(0);
5012 if (!f) {
5013 fprintf(logfile, "Failed to open savevm file '%s'\n", name);
5014 goto the_end;
5017 ret = qemu_savevm_state(f);
5018 qemu_fclose(f);
5020 if (ret < 0)
5021 fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
5022 ret, name);
5024 the_end:
5025 if (saved_vm_running)
5026 vm_start();
5028 return;
5030 void do_loadvm(const char *name)
5032 QEMUFile *f;
5033 int saved_vm_running, ret;
5035 /* Flush all IO requests so they don't interfere with the new state. */
5036 qemu_aio_flush();
5038 saved_vm_running = vm_running;
5039 vm_stop(0);
5041 /* restore the VM state */
5042 f = qemu_fopen(name, "rb");
5043 if (!f) {
5044 fprintf(logfile, "Could not open VM state file\n");
5045 goto the_end;
5048 ret = qemu_loadvm_state(f);
5049 qemu_fclose(f);
5050 if (ret < 0) {
5051 fprintf(logfile, "Error %d while loading savevm file '%s'\n",
5052 ret, name);
5053 goto the_end;
5056 #if 0
5057 /* del tmp file */
5058 if (unlink(name) == -1)
5059 fprintf(stderr, "delete tmp qemu state file failed.\n");
5060 #endif
5063 the_end:
5064 if (saved_vm_running)
5065 vm_start();
5067 #else
5068 void do_savevm(const char *name)
5070 BlockDriverState *bs, *bs1;
5071 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5072 int must_delete, ret, i;
5073 BlockDriverInfo bdi1, *bdi = &bdi1;
5074 QEMUFile *f;
5075 int saved_vm_running;
5076 #ifdef _WIN32
5077 struct _timeb tb;
5078 #else
5079 struct timeval tv;
5080 #endif
5082 bs = get_bs_snapshots();
5083 if (!bs) {
5084 term_printf("No block device can accept snapshots\n");
5085 return;
5088 /* ??? Should this occur after vm_stop? */
5089 qemu_aio_flush();
5091 saved_vm_running = vm_running;
5092 vm_stop(0);
5094 must_delete = 0;
5095 if (name) {
5096 ret = bdrv_snapshot_find(bs, old_sn, name);
5097 if (ret >= 0) {
5098 must_delete = 1;
5101 memset(sn, 0, sizeof(*sn));
5102 if (must_delete) {
5103 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5104 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5105 } else {
5106 if (name)
5107 pstrcpy(sn->name, sizeof(sn->name), name);
5110 /* fill auxiliary fields */
5111 #ifdef _WIN32
5112 _ftime(&tb);
5113 sn->date_sec = tb.time;
5114 sn->date_nsec = tb.millitm * 1000000;
5115 #else
5116 gettimeofday(&tv, NULL);
5117 sn->date_sec = tv.tv_sec;
5118 sn->date_nsec = tv.tv_usec * 1000;
5119 #endif
5120 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5122 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5123 term_printf("Device %s does not support VM state snapshots\n",
5124 bdrv_get_device_name(bs));
5125 goto the_end;
5128 /* save the VM state */
5129 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5130 if (!f) {
5131 term_printf("Could not open VM state file\n");
5132 goto the_end;
5134 ret = qemu_savevm_state(f);
5135 sn->vm_state_size = qemu_ftell(f);
5136 qemu_fclose(f);
5137 if (ret < 0) {
5138 term_printf("Error %d while writing VM\n", ret);
5139 goto the_end;
5142 /* create the snapshots */
5144 for(i = 0; i < MAX_DISKS; i++) {
5145 bs1 = bs_table[i];
5146 if (bdrv_has_snapshot(bs1)) {
5147 if (must_delete) {
5148 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5149 if (ret < 0) {
5150 term_printf("Error while deleting snapshot on '%s'\n",
5151 bdrv_get_device_name(bs1));
5154 ret = bdrv_snapshot_create(bs1, sn);
5155 if (ret < 0) {
5156 term_printf("Error while creating snapshot on '%s'\n",
5157 bdrv_get_device_name(bs1));
5162 the_end:
5163 if (saved_vm_running)
5164 vm_start();
5167 void do_loadvm(const char *name)
5169 BlockDriverState *bs, *bs1;
5170 BlockDriverInfo bdi1, *bdi = &bdi1;
5171 QEMUFile *f;
5172 int i, ret;
5173 int saved_vm_running;
5175 bs = get_bs_snapshots();
5176 if (!bs) {
5177 term_printf("No block device supports snapshots\n");
5178 return;
5181 /* Flush all IO requests so they don't interfere with the new state. */
5182 qemu_aio_flush();
5184 saved_vm_running = vm_running;
5185 vm_stop(0);
5187 for(i = 0; i <= MAX_DISKS; i++) {
5188 bs1 = bs_table[i];
5189 if (bdrv_has_snapshot(bs1)) {
5190 ret = bdrv_snapshot_goto(bs1, name);
5191 if (ret < 0) {
5192 if (bs != bs1)
5193 term_printf("Warning: ");
5194 switch(ret) {
5195 case -ENOTSUP:
5196 term_printf("Snapshots not supported on device '%s'\n",
5197 bdrv_get_device_name(bs1));
5198 break;
5199 case -ENOENT:
5200 term_printf("Could not find snapshot '%s' on device '%s'\n",
5201 name, bdrv_get_device_name(bs1));
5202 break;
5203 default:
5204 term_printf("Error %d while activating snapshot on '%s'\n",
5205 ret, bdrv_get_device_name(bs1));
5206 break;
5208 /* fatal on snapshot block device */
5209 if (bs == bs1)
5210 goto the_end;
5215 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5216 term_printf("Device %s does not support VM state snapshots\n",
5217 bdrv_get_device_name(bs));
5218 return;
5221 /* restore the VM state */
5222 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5223 if (!f) {
5224 term_printf("Could not open VM state file\n");
5225 goto the_end;
5227 ret = qemu_loadvm_state(f);
5228 qemu_fclose(f);
5229 if (ret < 0) {
5230 term_printf("Error %d while loading VM state\n", ret);
5233 /* del tmp file */
5234 if (unlink(name) == -1)
5235 fprintf(stderr, "delete tmp qemu state file failed.\n");
5237 the_end:
5238 if (saved_vm_running)
5239 vm_start();
5241 #endif
5243 void do_delvm(const char *name)
5245 BlockDriverState *bs, *bs1;
5246 int i, ret;
5248 bs = get_bs_snapshots();
5249 if (!bs) {
5250 term_printf("No block device supports snapshots\n");
5251 return;
5254 for(i = 0; i <= MAX_DISKS; i++) {
5255 bs1 = bs_table[i];
5256 if (bdrv_has_snapshot(bs1)) {
5257 ret = bdrv_snapshot_delete(bs1, name);
5258 if (ret < 0) {
5259 if (ret == -ENOTSUP)
5260 term_printf("Snapshots not supported on device '%s'\n",
5261 bdrv_get_device_name(bs1));
5262 else
5263 term_printf("Error %d while deleting snapshot on '%s'\n",
5264 ret, bdrv_get_device_name(bs1));
5270 void do_info_snapshots(void)
5272 BlockDriverState *bs, *bs1;
5273 QEMUSnapshotInfo *sn_tab, *sn;
5274 int nb_sns, i;
5275 char buf[256];
5277 bs = get_bs_snapshots();
5278 if (!bs) {
5279 term_printf("No available block device supports snapshots\n");
5280 return;
5282 term_printf("Snapshot devices:");
5283 for(i = 0; i <= MAX_DISKS; i++) {
5284 bs1 = bs_table[i];
5285 if (bdrv_has_snapshot(bs1)) {
5286 if (bs == bs1)
5287 term_printf(" %s", bdrv_get_device_name(bs1));
5290 term_printf("\n");
5292 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5293 if (nb_sns < 0) {
5294 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5295 return;
5297 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5298 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5299 for(i = 0; i < nb_sns; i++) {
5300 sn = &sn_tab[i];
5301 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5303 qemu_free(sn_tab);
5306 #ifndef CONFIG_DM
5307 /***********************************************************/
5308 /* cpu save/restore */
5310 #if defined(TARGET_I386)
5312 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5314 qemu_put_be32(f, dt->selector);
5315 qemu_put_betl(f, dt->base);
5316 qemu_put_be32(f, dt->limit);
5317 qemu_put_be32(f, dt->flags);
5320 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5322 dt->selector = qemu_get_be32(f);
5323 dt->base = qemu_get_betl(f);
5324 dt->limit = qemu_get_be32(f);
5325 dt->flags = qemu_get_be32(f);
5328 void cpu_save(QEMUFile *f, void *opaque)
5330 CPUState *env = opaque;
5331 uint16_t fptag, fpus, fpuc, fpregs_format;
5332 uint32_t hflags;
5333 int i;
5335 for(i = 0; i < CPU_NB_REGS; i++)
5336 qemu_put_betls(f, &env->regs[i]);
5337 qemu_put_betls(f, &env->eip);
5338 qemu_put_betls(f, &env->eflags);
5339 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5340 qemu_put_be32s(f, &hflags);
5342 /* FPU */
5343 fpuc = env->fpuc;
5344 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5345 fptag = 0;
5346 for(i = 0; i < 8; i++) {
5347 fptag |= ((!env->fptags[i]) << i);
5350 qemu_put_be16s(f, &fpuc);
5351 qemu_put_be16s(f, &fpus);
5352 qemu_put_be16s(f, &fptag);
5354 #ifdef USE_X86LDOUBLE
5355 fpregs_format = 0;
5356 #else
5357 fpregs_format = 1;
5358 #endif
5359 qemu_put_be16s(f, &fpregs_format);
5361 for(i = 0; i < 8; i++) {
5362 #ifdef USE_X86LDOUBLE
5364 uint64_t mant;
5365 uint16_t exp;
5366 /* we save the real CPU data (in case of MMX usage only 'mant'
5367 contains the MMX register */
5368 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5369 qemu_put_be64(f, mant);
5370 qemu_put_be16(f, exp);
5372 #else
5373 /* if we use doubles for float emulation, we save the doubles to
5374 avoid losing information in case of MMX usage. It can give
5375 problems if the image is restored on a CPU where long
5376 doubles are used instead. */
5377 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5378 #endif
5381 for(i = 0; i < 6; i++)
5382 cpu_put_seg(f, &env->segs[i]);
5383 cpu_put_seg(f, &env->ldt);
5384 cpu_put_seg(f, &env->tr);
5385 cpu_put_seg(f, &env->gdt);
5386 cpu_put_seg(f, &env->idt);
5388 qemu_put_be32s(f, &env->sysenter_cs);
5389 qemu_put_be32s(f, &env->sysenter_esp);
5390 qemu_put_be32s(f, &env->sysenter_eip);
5392 qemu_put_betls(f, &env->cr[0]);
5393 qemu_put_betls(f, &env->cr[2]);
5394 qemu_put_betls(f, &env->cr[3]);
5395 qemu_put_betls(f, &env->cr[4]);
5397 for(i = 0; i < 8; i++)
5398 qemu_put_betls(f, &env->dr[i]);
5400 /* MMU */
5401 qemu_put_be32s(f, &env->a20_mask);
5403 /* XMM */
5404 qemu_put_be32s(f, &env->mxcsr);
5405 for(i = 0; i < CPU_NB_REGS; i++) {
5406 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5407 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5410 #ifdef TARGET_X86_64
5411 qemu_put_be64s(f, &env->efer);
5412 qemu_put_be64s(f, &env->star);
5413 qemu_put_be64s(f, &env->lstar);
5414 qemu_put_be64s(f, &env->cstar);
5415 qemu_put_be64s(f, &env->fmask);
5416 qemu_put_be64s(f, &env->kernelgsbase);
5417 #endif
5418 qemu_put_be32s(f, &env->smbase);
5421 #ifdef USE_X86LDOUBLE
5422 /* XXX: add that in a FPU generic layer */
5423 union x86_longdouble {
5424 uint64_t mant;
5425 uint16_t exp;
5426 };
5428 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5429 #define EXPBIAS1 1023
5430 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5431 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5433 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5435 int e;
5436 /* mantissa */
5437 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5438 /* exponent + sign */
5439 e = EXPD1(temp) - EXPBIAS1 + 16383;
5440 e |= SIGND1(temp) >> 16;
5441 p->exp = e;
5443 #endif
5445 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5447 CPUState *env = opaque;
5448 int i, guess_mmx;
5449 uint32_t hflags;
5450 uint16_t fpus, fpuc, fptag, fpregs_format;
5452 if (version_id != 3 && version_id != 4)
5453 return -EINVAL;
5454 for(i = 0; i < CPU_NB_REGS; i++)
5455 qemu_get_betls(f, &env->regs[i]);
5456 qemu_get_betls(f, &env->eip);
5457 qemu_get_betls(f, &env->eflags);
5458 qemu_get_be32s(f, &hflags);
5460 qemu_get_be16s(f, &fpuc);
5461 qemu_get_be16s(f, &fpus);
5462 qemu_get_be16s(f, &fptag);
5463 qemu_get_be16s(f, &fpregs_format);
5465 /* NOTE: we cannot always restore the FPU state if the image come
5466 from a host with a different 'USE_X86LDOUBLE' define. We guess
5467 if we are in an MMX state to restore correctly in that case. */
5468 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5469 for(i = 0; i < 8; i++) {
5470 uint64_t mant;
5471 uint16_t exp;
5473 switch(fpregs_format) {
5474 case 0:
5475 mant = qemu_get_be64(f);
5476 exp = qemu_get_be16(f);
5477 #ifdef USE_X86LDOUBLE
5478 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5479 #else
5480 /* difficult case */
5481 if (guess_mmx)
5482 env->fpregs[i].mmx.MMX_Q(0) = mant;
5483 else
5484 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5485 #endif
5486 break;
5487 case 1:
5488 mant = qemu_get_be64(f);
5489 #ifdef USE_X86LDOUBLE
5491 union x86_longdouble *p;
5492 /* difficult case */
5493 p = (void *)&env->fpregs[i];
5494 if (guess_mmx) {
5495 p->mant = mant;
5496 p->exp = 0xffff;
5497 } else {
5498 fp64_to_fp80(p, mant);
5501 #else
5502 env->fpregs[i].mmx.MMX_Q(0) = mant;
5503 #endif
5504 break;
5505 default:
5506 return -EINVAL;
5510 env->fpuc = fpuc;
5511 /* XXX: restore FPU round state */
5512 env->fpstt = (fpus >> 11) & 7;
5513 env->fpus = fpus & ~0x3800;
5514 fptag ^= 0xff;
5515 for(i = 0; i < 8; i++) {
5516 env->fptags[i] = (fptag >> i) & 1;
5519 for(i = 0; i < 6; i++)
5520 cpu_get_seg(f, &env->segs[i]);
5521 cpu_get_seg(f, &env->ldt);
5522 cpu_get_seg(f, &env->tr);
5523 cpu_get_seg(f, &env->gdt);
5524 cpu_get_seg(f, &env->idt);
5526 qemu_get_be32s(f, &env->sysenter_cs);
5527 qemu_get_be32s(f, &env->sysenter_esp);
5528 qemu_get_be32s(f, &env->sysenter_eip);
5530 qemu_get_betls(f, &env->cr[0]);
5531 qemu_get_betls(f, &env->cr[2]);
5532 qemu_get_betls(f, &env->cr[3]);
5533 qemu_get_betls(f, &env->cr[4]);
5535 for(i = 0; i < 8; i++)
5536 qemu_get_betls(f, &env->dr[i]);
5538 /* MMU */
5539 qemu_get_be32s(f, &env->a20_mask);
5541 qemu_get_be32s(f, &env->mxcsr);
5542 for(i = 0; i < CPU_NB_REGS; i++) {
5543 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5544 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5547 #ifdef TARGET_X86_64
5548 qemu_get_be64s(f, &env->efer);
5549 qemu_get_be64s(f, &env->star);
5550 qemu_get_be64s(f, &env->lstar);
5551 qemu_get_be64s(f, &env->cstar);
5552 qemu_get_be64s(f, &env->fmask);
5553 qemu_get_be64s(f, &env->kernelgsbase);
5554 #endif
5555 if (version_id >= 4)
5556 qemu_get_be32s(f, &env->smbase);
5558 /* XXX: compute hflags from scratch, except for CPL and IIF */
5559 env->hflags = hflags;
5560 tlb_flush(env, 1);
5561 return 0;
5564 #elif defined(TARGET_PPC)
5565 void cpu_save(QEMUFile *f, void *opaque)
5569 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5571 return 0;
5574 #elif defined(TARGET_MIPS)
5575 void cpu_save(QEMUFile *f, void *opaque)
5579 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5581 return 0;
5584 #elif defined(TARGET_SPARC)
5585 void cpu_save(QEMUFile *f, void *opaque)
5587 CPUState *env = opaque;
5588 int i;
5589 uint32_t tmp;
5591 for(i = 0; i < 8; i++)
5592 qemu_put_betls(f, &env->gregs[i]);
5593 for(i = 0; i < NWINDOWS * 16; i++)
5594 qemu_put_betls(f, &env->regbase[i]);
5596 /* FPU */
5597 for(i = 0; i < TARGET_FPREGS; i++) {
5598 union {
5599 float32 f;
5600 uint32_t i;
5601 } u;
5602 u.f = env->fpr[i];
5603 qemu_put_be32(f, u.i);
5606 qemu_put_betls(f, &env->pc);
5607 qemu_put_betls(f, &env->npc);
5608 qemu_put_betls(f, &env->y);
5609 tmp = GET_PSR(env);
5610 qemu_put_be32(f, tmp);
5611 qemu_put_betls(f, &env->fsr);
5612 qemu_put_betls(f, &env->tbr);
5613 #ifndef TARGET_SPARC64
5614 qemu_put_be32s(f, &env->wim);
5615 /* MMU */
5616 for(i = 0; i < 16; i++)
5617 qemu_put_be32s(f, &env->mmuregs[i]);
5618 #endif
5621 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5623 CPUState *env = opaque;
5624 int i;
5625 uint32_t tmp;
5627 for(i = 0; i < 8; i++)
5628 qemu_get_betls(f, &env->gregs[i]);
5629 for(i = 0; i < NWINDOWS * 16; i++)
5630 qemu_get_betls(f, &env->regbase[i]);
5632 /* FPU */
5633 for(i = 0; i < TARGET_FPREGS; i++) {
5634 union {
5635 float32 f;
5636 uint32_t i;
5637 } u;
5638 u.i = qemu_get_be32(f);
5639 env->fpr[i] = u.f;
5642 qemu_get_betls(f, &env->pc);
5643 qemu_get_betls(f, &env->npc);
5644 qemu_get_betls(f, &env->y);
5645 tmp = qemu_get_be32(f);
5646 env->cwp = 0; /* needed to ensure that the wrapping registers are
5647 correctly updated */
5648 PUT_PSR(env, tmp);
5649 qemu_get_betls(f, &env->fsr);
5650 qemu_get_betls(f, &env->tbr);
5651 #ifndef TARGET_SPARC64
5652 qemu_get_be32s(f, &env->wim);
5653 /* MMU */
5654 for(i = 0; i < 16; i++)
5655 qemu_get_be32s(f, &env->mmuregs[i]);
5656 #endif
5657 tlb_flush(env, 1);
5658 return 0;
5661 #elif defined(TARGET_ARM)
5663 /* ??? Need to implement these. */
5664 void cpu_save(QEMUFile *f, void *opaque)
5668 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5670 return 0;
5673 #else
5675 #warning No CPU save/restore functions
5677 #endif
5679 /***********************************************************/
5680 /* ram save/restore */
5682 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5684 int v;
5686 v = qemu_get_byte(f);
5687 switch(v) {
5688 case 0:
5689 if (qemu_get_buffer(f, buf, len) != len)
5690 return -EIO;
5691 break;
5692 case 1:
5693 v = qemu_get_byte(f);
5694 memset(buf, v, len);
5695 break;
5696 default:
5697 return -EINVAL;
5699 return 0;
5702 static int ram_load_v1(QEMUFile *f, void *opaque)
5704 int i, ret;
5706 if (qemu_get_be32(f) != phys_ram_size)
5707 return -EINVAL;
5708 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5709 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5710 if (ret)
5711 return ret;
5713 return 0;
5716 #define BDRV_HASH_BLOCK_SIZE 1024
5717 #define IOBUF_SIZE 4096
5718 #define RAM_CBLOCK_MAGIC 0xfabe
5720 typedef struct RamCompressState {
5721 z_stream zstream;
5722 QEMUFile *f;
5723 uint8_t buf[IOBUF_SIZE];
5724 } RamCompressState;
5726 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5728 int ret;
5729 memset(s, 0, sizeof(*s));
5730 s->f = f;
5731 ret = deflateInit2(&s->zstream, 1,
5732 Z_DEFLATED, 15,
5733 9, Z_DEFAULT_STRATEGY);
5734 if (ret != Z_OK)
5735 return -1;
5736 s->zstream.avail_out = IOBUF_SIZE;
5737 s->zstream.next_out = s->buf;
5738 return 0;
5741 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5743 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5744 qemu_put_be16(s->f, len);
5745 qemu_put_buffer(s->f, buf, len);
5748 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5750 int ret;
5752 s->zstream.avail_in = len;
5753 s->zstream.next_in = (uint8_t *)buf;
5754 while (s->zstream.avail_in > 0) {
5755 ret = deflate(&s->zstream, Z_NO_FLUSH);
5756 if (ret != Z_OK)
5757 return -1;
5758 if (s->zstream.avail_out == 0) {
5759 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5760 s->zstream.avail_out = IOBUF_SIZE;
5761 s->zstream.next_out = s->buf;
5764 return 0;
5767 static void ram_compress_close(RamCompressState *s)
5769 int len, ret;
5771 /* compress last bytes */
5772 for(;;) {
5773 ret = deflate(&s->zstream, Z_FINISH);
5774 if (ret == Z_OK || ret == Z_STREAM_END) {
5775 len = IOBUF_SIZE - s->zstream.avail_out;
5776 if (len > 0) {
5777 ram_put_cblock(s, s->buf, len);
5779 s->zstream.avail_out = IOBUF_SIZE;
5780 s->zstream.next_out = s->buf;
5781 if (ret == Z_STREAM_END)
5782 break;
5783 } else {
5784 goto fail;
5787 fail:
5788 deflateEnd(&s->zstream);
5791 typedef struct RamDecompressState {
5792 z_stream zstream;
5793 QEMUFile *f;
5794 uint8_t buf[IOBUF_SIZE];
5795 } RamDecompressState;
5797 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5799 int ret;
5800 memset(s, 0, sizeof(*s));
5801 s->f = f;
5802 ret = inflateInit(&s->zstream);
5803 if (ret != Z_OK)
5804 return -1;
5805 return 0;
5808 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5810 int ret, clen;
5812 s->zstream.avail_out = len;
5813 s->zstream.next_out = buf;
5814 while (s->zstream.avail_out > 0) {
5815 if (s->zstream.avail_in == 0) {
5816 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5817 return -1;
5818 clen = qemu_get_be16(s->f);
5819 if (clen > IOBUF_SIZE)
5820 return -1;
5821 qemu_get_buffer(s->f, s->buf, clen);
5822 s->zstream.avail_in = clen;
5823 s->zstream.next_in = s->buf;
5825 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5826 if (ret != Z_OK && ret != Z_STREAM_END) {
5827 return -1;
5830 return 0;
5833 static void ram_decompress_close(RamDecompressState *s)
5835 inflateEnd(&s->zstream);
5838 static void ram_save(QEMUFile *f, void *opaque)
5840 int i;
5841 RamCompressState s1, *s = &s1;
5842 uint8_t buf[10];
5844 qemu_put_be32(f, phys_ram_size);
5845 if (ram_compress_open(s, f) < 0)
5846 return;
5847 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5848 #if 0
5849 if (tight_savevm_enabled) {
5850 int64_t sector_num;
5851 int j;
5853 /* find if the memory block is available on a virtual
5854 block device */
5855 sector_num = -1;
5856 for(j = 0; j < MAX_DISKS; j++) {
5857 if (bs_table[j]) {
5858 sector_num = bdrv_hash_find(bs_table[j],
5859 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5860 if (sector_num >= 0)
5861 break;
5864 if (j == MAX_DISKS)
5865 goto normal_compress;
5866 buf[0] = 1;
5867 buf[1] = j;
5868 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5869 ram_compress_buf(s, buf, 10);
5870 } else
5871 #endif
5873 // normal_compress:
5874 buf[0] = 0;
5875 ram_compress_buf(s, buf, 1);
5876 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5879 ram_compress_close(s);
5882 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5884 RamDecompressState s1, *s = &s1;
5885 uint8_t buf[10];
5886 int i;
5888 if (version_id == 1)
5889 return ram_load_v1(f, opaque);
5890 if (version_id != 2)
5891 return -EINVAL;
5892 if (qemu_get_be32(f) != phys_ram_size)
5893 return -EINVAL;
5894 if (ram_decompress_open(s, f) < 0)
5895 return -EINVAL;
5896 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5897 if (ram_decompress_buf(s, buf, 1) < 0) {
5898 fprintf(stderr, "Error while reading ram block header\n");
5899 goto error;
5901 if (buf[0] == 0) {
5902 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5903 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5904 goto error;
5906 } else
5907 #if 0
5908 if (buf[0] == 1) {
5909 int bs_index;
5910 int64_t sector_num;
5912 ram_decompress_buf(s, buf + 1, 9);
5913 bs_index = buf[1];
5914 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5915 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5916 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5917 goto error;
5919 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5920 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5921 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5922 bs_index, sector_num);
5923 goto error;
5925 } else
5926 #endif
5928 error:
5929 printf("Error block header\n");
5930 return -EINVAL;
5933 ram_decompress_close(s);
5934 return 0;
5936 #else /* CONFIG_DM */
5937 void cpu_save(QEMUFile *f, void *opaque)
5941 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5943 return 0;
5946 static void ram_save(QEMUFile *f, void *opaque)
5950 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5952 return 0;
5954 #endif /* CONFIG_DM */
5956 /***********************************************************/
5957 /* bottom halves (can be seen as timers which expire ASAP) */
5959 struct QEMUBH {
5960 QEMUBHFunc *cb;
5961 void *opaque;
5962 int scheduled;
5963 QEMUBH *next;
5964 };
5966 static QEMUBH *first_bh = NULL;
5968 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5970 QEMUBH *bh;
5971 bh = qemu_mallocz(sizeof(QEMUBH));
5972 if (!bh)
5973 return NULL;
5974 bh->cb = cb;
5975 bh->opaque = opaque;
5976 return bh;
5979 int qemu_bh_poll(void)
5981 QEMUBH *bh, **pbh;
5982 int ret;
5984 ret = 0;
5985 for(;;) {
5986 pbh = &first_bh;
5987 bh = *pbh;
5988 if (!bh)
5989 break;
5990 ret = 1;
5991 *pbh = bh->next;
5992 bh->scheduled = 0;
5993 bh->cb(bh->opaque);
5995 return ret;
5998 void qemu_bh_schedule(QEMUBH *bh)
6000 CPUState *env = cpu_single_env;
6001 if (bh->scheduled)
6002 return;
6003 bh->scheduled = 1;
6004 bh->next = first_bh;
6005 first_bh = bh;
6007 /* stop the currently executing CPU to execute the BH ASAP */
6008 if (env) {
6009 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6013 void qemu_bh_cancel(QEMUBH *bh)
6015 QEMUBH **pbh;
6016 if (bh->scheduled) {
6017 pbh = &first_bh;
6018 while (*pbh != bh)
6019 pbh = &(*pbh)->next;
6020 *pbh = bh->next;
6021 bh->scheduled = 0;
6025 void qemu_bh_delete(QEMUBH *bh)
6027 qemu_bh_cancel(bh);
6028 qemu_free(bh);
6031 /***********************************************************/
6032 /* machine registration */
6034 QEMUMachine *first_machine = NULL;
6036 int qemu_register_machine(QEMUMachine *m)
6038 QEMUMachine **pm;
6039 pm = &first_machine;
6040 while (*pm != NULL)
6041 pm = &(*pm)->next;
6042 m->next = NULL;
6043 *pm = m;
6044 return 0;
6047 QEMUMachine *find_machine(const char *name)
6049 QEMUMachine *m;
6051 for(m = first_machine; m != NULL; m = m->next) {
6052 if (!strcmp(m->name, name))
6053 return m;
6055 return NULL;
6058 /***********************************************************/
6059 /* main execution loop */
6061 void gui_update(void *opaque)
6063 display_state.dpy_refresh(&display_state);
6064 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6067 struct vm_change_state_entry {
6068 VMChangeStateHandler *cb;
6069 void *opaque;
6070 LIST_ENTRY (vm_change_state_entry) entries;
6071 };
6073 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6075 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6076 void *opaque)
6078 VMChangeStateEntry *e;
6080 e = qemu_mallocz(sizeof (*e));
6081 if (!e)
6082 return NULL;
6084 e->cb = cb;
6085 e->opaque = opaque;
6086 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6087 return e;
6090 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6092 LIST_REMOVE (e, entries);
6093 qemu_free (e);
6096 static void vm_state_notify(int running)
6098 VMChangeStateEntry *e;
6100 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6101 e->cb(e->opaque, running);
6105 /* XXX: support several handlers */
6106 static VMStopHandler *vm_stop_cb;
6107 static void *vm_stop_opaque;
6109 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6111 vm_stop_cb = cb;
6112 vm_stop_opaque = opaque;
6113 return 0;
6116 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6118 vm_stop_cb = NULL;
6121 void vm_start(void)
6123 if (!vm_running) {
6124 cpu_enable_ticks();
6125 vm_running = 1;
6126 vm_state_notify(1);
6130 void vm_stop(int reason)
6132 if (vm_running) {
6133 cpu_disable_ticks();
6134 vm_running = 0;
6135 if (reason != 0) {
6136 if (vm_stop_cb) {
6137 vm_stop_cb(vm_stop_opaque, reason);
6140 vm_state_notify(0);
6144 /* reset/shutdown handler */
6146 typedef struct QEMUResetEntry {
6147 QEMUResetHandler *func;
6148 void *opaque;
6149 struct QEMUResetEntry *next;
6150 } QEMUResetEntry;
6152 static QEMUResetEntry *first_reset_entry;
6153 int reset_requested;
6154 int shutdown_requested;
6155 int suspend_requested;
6156 static int powerdown_requested;
6158 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6160 QEMUResetEntry **pre, *re;
6162 pre = &first_reset_entry;
6163 while (*pre != NULL)
6164 pre = &(*pre)->next;
6165 re = qemu_mallocz(sizeof(QEMUResetEntry));
6166 re->func = func;
6167 re->opaque = opaque;
6168 re->next = NULL;
6169 *pre = re;
6172 void qemu_system_reset(void)
6174 QEMUResetEntry *re;
6176 /* reset all devices */
6177 for(re = first_reset_entry; re != NULL; re = re->next) {
6178 re->func(re->opaque);
6182 void qemu_system_reset_request(void)
6184 if (no_reboot) {
6185 shutdown_requested = 1;
6186 } else {
6187 reset_requested = 1;
6189 if (cpu_single_env)
6190 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6193 void qemu_system_shutdown_request(void)
6195 shutdown_requested = 1;
6196 if (cpu_single_env)
6197 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6200 void qemu_system_powerdown_request(void)
6202 powerdown_requested = 1;
6203 if (cpu_single_env)
6204 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6207 void main_loop_wait(int timeout)
6209 IOHandlerRecord *ioh;
6210 fd_set rfds, wfds, xfds;
6211 int ret, nfds;
6212 struct timeval tv;
6213 PollingEntry *pe;
6216 /* XXX: need to suppress polling by better using win32 events */
6217 ret = 0;
6218 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6219 ret |= pe->func(pe->opaque);
6221 #ifdef _WIN32
6222 if (ret == 0 && timeout > 0) {
6223 int err;
6224 WaitObjects *w = &wait_objects;
6226 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6227 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6228 if (w->func[ret - WAIT_OBJECT_0])
6229 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6230 } else if (ret == WAIT_TIMEOUT) {
6231 } else {
6232 err = GetLastError();
6233 fprintf(stderr, "Wait error %d %d\n", ret, err);
6236 #endif
6237 /* poll any events */
6238 /* XXX: separate device handlers from system ones */
6239 nfds = -1;
6240 FD_ZERO(&rfds);
6241 FD_ZERO(&wfds);
6242 FD_ZERO(&xfds);
6243 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6244 if (ioh->deleted)
6245 continue;
6246 if (ioh->fd_read &&
6247 (!ioh->fd_read_poll ||
6248 ioh->fd_read_poll(ioh->opaque) != 0)) {
6249 FD_SET(ioh->fd, &rfds);
6250 if (ioh->fd > nfds)
6251 nfds = ioh->fd;
6253 if (ioh->fd_write) {
6254 FD_SET(ioh->fd, &wfds);
6255 if (ioh->fd > nfds)
6256 nfds = ioh->fd;
6260 tv.tv_sec = 0;
6261 #ifdef _WIN32
6262 tv.tv_usec = 0;
6263 #else
6264 tv.tv_usec = timeout * 1000;
6265 #endif
6266 #if defined(CONFIG_SLIRP)
6267 if (slirp_inited) {
6268 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6270 #endif
6271 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6272 if (ret > 0) {
6273 IOHandlerRecord **pioh;
6275 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6276 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6277 ioh->fd_read(ioh->opaque);
6279 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6280 ioh->fd_write(ioh->opaque);
6284 /* remove deleted IO handlers */
6285 pioh = &first_io_handler;
6286 while (*pioh) {
6287 ioh = *pioh;
6288 if (ioh->deleted) {
6289 *pioh = ioh->next;
6290 qemu_free(ioh);
6291 } else
6292 pioh = &ioh->next;
6295 #if defined(CONFIG_SLIRP)
6296 if (slirp_inited) {
6297 if (ret < 0) {
6298 FD_ZERO(&rfds);
6299 FD_ZERO(&wfds);
6300 FD_ZERO(&xfds);
6302 slirp_select_poll(&rfds, &wfds, &xfds);
6304 #endif
6305 qemu_aio_poll();
6306 qemu_bh_poll();
6308 if (vm_running) {
6309 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6310 qemu_get_clock(vm_clock));
6311 /* run dma transfers, if any */
6312 DMA_run();
6315 /* real time timers */
6316 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6317 qemu_get_clock(rt_clock));
6320 #ifndef CONFIG_DM
6321 static CPUState *cur_cpu;
6323 int main_loop(void)
6325 int ret, timeout;
6326 #ifdef CONFIG_PROFILER
6327 int64_t ti;
6328 #endif
6329 CPUState *env;
6331 cur_cpu = first_cpu;
6332 for(;;) {
6333 if (vm_running) {
6335 env = cur_cpu;
6336 for(;;) {
6337 /* get next cpu */
6338 env = env->next_cpu;
6339 if (!env)
6340 env = first_cpu;
6341 #ifdef CONFIG_PROFILER
6342 ti = profile_getclock();
6343 #endif
6344 ret = cpu_exec(env);
6345 #ifdef CONFIG_PROFILER
6346 qemu_time += profile_getclock() - ti;
6347 #endif
6348 if (ret != EXCP_HALTED)
6349 break;
6350 /* all CPUs are halted ? */
6351 if (env == cur_cpu) {
6352 ret = EXCP_HLT;
6353 break;
6356 cur_cpu = env;
6358 if (shutdown_requested) {
6359 ret = EXCP_INTERRUPT;
6360 break;
6362 if (reset_requested) {
6363 reset_requested = 0;
6364 qemu_system_reset();
6365 ret = EXCP_INTERRUPT;
6367 if (powerdown_requested) {
6368 powerdown_requested = 0;
6369 qemu_system_powerdown();
6370 ret = EXCP_INTERRUPT;
6372 if (ret == EXCP_DEBUG) {
6373 vm_stop(EXCP_DEBUG);
6375 /* if hlt instruction, we wait until the next IRQ */
6376 /* XXX: use timeout computed from timers */
6377 if (ret == EXCP_HLT)
6378 timeout = 10;
6379 else
6380 timeout = 0;
6381 } else {
6382 timeout = 10;
6384 #ifdef CONFIG_PROFILER
6385 ti = profile_getclock();
6386 #endif
6387 main_loop_wait(timeout);
6388 #ifdef CONFIG_PROFILER
6389 dev_time += profile_getclock() - ti;
6390 #endif
6392 cpu_disable_ticks();
6393 return ret;
6395 #endif /* !CONFIG_DM */
6397 void help(void)
6399 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6400 "usage: %s [options] [disk_image]\n"
6401 "\n"
6402 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6403 "\n"
6404 "Standard options:\n"
6405 "-M machine select emulated machine (-M ? for list)\n"
6406 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6407 #ifndef CONFIG_DM
6408 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6409 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6410 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6411 #endif /* !CONFIG_DM */
6412 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6413 "-snapshot write to temporary files instead of disk image files\n"
6414 #ifdef CONFIG_SDL
6415 "-no-quit disable SDL window close capability\n"
6416 #endif
6417 #ifdef TARGET_I386
6418 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6419 #endif
6420 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6421 "-smp n set the number of CPUs to 'n' [default=1]\n"
6422 "-nographic disable graphical output and redirect serial I/Os to console\n"
6423 "-vcpus set CPU number of guest platform\n"
6424 #ifndef _WIN32
6425 "-k language use keyboard layout (for example \"fr\" for French)\n"
6426 #endif
6427 #ifdef HAS_AUDIO
6428 "-audio-help print list of audio drivers and their options\n"
6429 "-soundhw c1,... enable audio support\n"
6430 " and only specified sound cards (comma separated list)\n"
6431 " use -soundhw ? to get the list of supported cards\n"
6432 " use -soundhw all to enable all of them\n"
6433 #endif
6434 "-localtime set the real time clock to local time [default=utc]\n"
6435 "-full-screen start in full screen\n"
6436 #ifdef TARGET_I386
6437 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6438 #endif
6439 "-usb enable the USB driver (will be the default soon)\n"
6440 "-usbdevice name add the host or guest USB device 'name'\n"
6441 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6442 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6443 #endif
6444 "\n"
6445 "Network options:\n"
6446 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6447 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6448 #ifdef CONFIG_SLIRP
6449 "-net user[,vlan=n][,hostname=host]\n"
6450 " connect the user mode network stack to VLAN 'n' and send\n"
6451 " hostname 'host' to DHCP clients\n"
6452 #endif
6453 #ifdef _WIN32
6454 "-net tap[,vlan=n],ifname=name\n"
6455 " connect the host TAP network interface to VLAN 'n'\n"
6456 #else
6457 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6458 " connect the host TAP network interface to VLAN 'n' and use\n"
6459 " the network script 'file' (default=%s);\n"
6460 " use 'script=no' to disable script execution;\n"
6461 " use 'fd=h' to connect to an already opened TAP interface\n"
6462 #endif
6463 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6464 " connect the vlan 'n' to another VLAN using a socket connection\n"
6465 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6466 " connect the vlan 'n' to multicast maddr and port\n"
6467 "-net none use it alone to have zero network devices; if no -net option\n"
6468 " is provided, the default is '-net nic -net user'\n"
6469 "\n"
6470 #ifdef CONFIG_SLIRP
6471 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6472 #ifndef _WIN32
6473 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6474 #endif
6475 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6476 " redirect TCP or UDP connections from host to guest [-net user]\n"
6477 #endif
6478 "\n"
6479 "Linux boot specific:\n"
6480 "-kernel bzImage use 'bzImage' as kernel image\n"
6481 "-append cmdline use 'cmdline' as kernel command line\n"
6482 "-initrd file use 'file' as initial ram disk\n"
6483 "\n"
6484 "Debug/Expert options:\n"
6485 "-monitor dev redirect the monitor to char device 'dev'\n"
6486 "-serial dev redirect the serial port to char device 'dev'\n"
6487 "-parallel dev redirect the parallel port to char device 'dev'\n"
6488 "-pidfile file Write PID to 'file'\n"
6489 "-S freeze CPU at startup (use 'c' to start execution)\n"
6490 "-s wait gdb connection to port %d\n"
6491 "-p port change gdb connection port\n"
6492 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
6493 "-d domain domain that we're serving\n"
6494 "-domain-name domain name that we're serving\n"
6495 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6496 " translation (t=none or lba) (usually qemu can guess them)\n"
6497 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6498 #ifdef USE_KQEMU
6499 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6500 "-no-kqemu disable KQEMU kernel module usage\n"
6501 #endif
6502 #ifdef USE_CODE_COPY
6503 "-no-code-copy disable code copy acceleration\n"
6504 #endif
6505 #ifdef TARGET_I386
6506 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6507 " (default is CL-GD5446 PCI VGA)\n"
6508 "-no-acpi disable ACPI\n"
6509 #endif
6510 "-no-reboot exit instead of rebooting\n"
6511 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6512 "-vnc display start a VNC server on display\n"
6513 "-vncviewer start a vncviewer process for this domain\n"
6514 "-vncunused bind the VNC server to an unused port\n"
6515 #ifndef _WIN32
6516 "-daemonize daemonize QEMU after initializing\n"
6517 #endif
6518 "-option-rom rom load a file, rom, into the option ROM space\n"
6519 "-acpi disable or enable ACPI of HVM domain \n"
6520 "\n"
6521 "During emulation, the following keys are useful:\n"
6522 "ctrl-alt-f toggle full screen\n"
6523 "ctrl-alt-n switch to virtual console 'n'\n"
6524 "ctrl-alt toggle mouse and keyboard grab\n"
6525 "\n"
6526 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6528 "qemu",
6529 DEFAULT_RAM_SIZE,
6530 #ifndef _WIN32
6531 DEFAULT_NETWORK_SCRIPT,
6532 #endif
6533 DEFAULT_GDBSTUB_PORT,
6534 "/tmp/qemu.log");
6535 exit(1);
6538 #define HAS_ARG 0x0001
6540 enum {
6541 QEMU_OPTION_h,
6543 QEMU_OPTION_M,
6544 QEMU_OPTION_fda,
6545 QEMU_OPTION_fdb,
6546 #ifndef CONFIG_DM
6547 QEMU_OPTION_hda,
6548 QEMU_OPTION_hdb,
6549 QEMU_OPTION_hdc,
6550 QEMU_OPTION_hdd,
6551 QEMU_OPTION_cdrom,
6552 #endif /* !CONFIG_DM */
6553 QEMU_OPTION_boot,
6554 QEMU_OPTION_snapshot,
6555 #ifdef TARGET_I386
6556 QEMU_OPTION_no_fd_bootchk,
6557 #endif
6558 QEMU_OPTION_m,
6559 QEMU_OPTION_nographic,
6560 #ifdef HAS_AUDIO
6561 QEMU_OPTION_audio_help,
6562 QEMU_OPTION_soundhw,
6563 #endif
6565 QEMU_OPTION_net,
6566 QEMU_OPTION_tftp,
6567 QEMU_OPTION_smb,
6568 QEMU_OPTION_redir,
6570 QEMU_OPTION_kernel,
6571 QEMU_OPTION_append,
6572 QEMU_OPTION_initrd,
6574 QEMU_OPTION_S,
6575 QEMU_OPTION_s,
6576 QEMU_OPTION_p,
6577 QEMU_OPTION_l,
6578 QEMU_OPTION_hdachs,
6579 QEMU_OPTION_L,
6580 #ifdef USE_CODE_COPY
6581 QEMU_OPTION_no_code_copy,
6582 #endif
6583 QEMU_OPTION_k,
6584 QEMU_OPTION_localtime,
6585 QEMU_OPTION_cirrusvga,
6586 QEMU_OPTION_g,
6587 QEMU_OPTION_std_vga,
6588 QEMU_OPTION_monitor,
6589 QEMU_OPTION_domainname,
6590 QEMU_OPTION_serial,
6591 QEMU_OPTION_parallel,
6592 QEMU_OPTION_loadvm,
6593 QEMU_OPTION_full_screen,
6594 QEMU_OPTION_no_quit,
6595 QEMU_OPTION_pidfile,
6596 QEMU_OPTION_no_kqemu,
6597 QEMU_OPTION_kernel_kqemu,
6598 QEMU_OPTION_win2k_hack,
6599 QEMU_OPTION_usb,
6600 QEMU_OPTION_usbdevice,
6601 QEMU_OPTION_smp,
6602 QEMU_OPTION_vnc,
6603 QEMU_OPTION_no_acpi,
6604 QEMU_OPTION_no_reboot,
6605 QEMU_OPTION_daemonize,
6606 QEMU_OPTION_option_rom,
6607 QEMU_OPTION_semihosting
6609 QEMU_OPTION_d,
6610 QEMU_OPTION_vcpus,
6611 QEMU_OPTION_acpi,
6612 QEMU_OPTION_vncviewer,
6613 QEMU_OPTION_vncunused,
6614 QEMU_OPTION_pci,
6615 };
6617 typedef struct QEMUOption {
6618 const char *name;
6619 int flags;
6620 int index;
6621 } QEMUOption;
6623 const QEMUOption qemu_options[] = {
6624 { "h", 0, QEMU_OPTION_h },
6625 { "help", 0, QEMU_OPTION_h },
6627 { "M", HAS_ARG, QEMU_OPTION_M },
6628 { "fda", HAS_ARG, QEMU_OPTION_fda },
6629 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6630 #ifndef CONFIG_DM
6631 { "hda", HAS_ARG, QEMU_OPTION_hda },
6632 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6633 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6634 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6635 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6636 #endif /* !CONFIG_DM */
6637 { "boot", HAS_ARG, QEMU_OPTION_boot },
6638 { "snapshot", 0, QEMU_OPTION_snapshot },
6639 #ifdef TARGET_I386
6640 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6641 #endif
6642 { "m", HAS_ARG, QEMU_OPTION_m },
6643 { "nographic", 0, QEMU_OPTION_nographic },
6644 { "k", HAS_ARG, QEMU_OPTION_k },
6645 #ifdef HAS_AUDIO
6646 { "audio-help", 0, QEMU_OPTION_audio_help },
6647 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6648 #endif
6650 { "net", HAS_ARG, QEMU_OPTION_net},
6651 #ifdef CONFIG_SLIRP
6652 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6653 #ifndef _WIN32
6654 { "smb", HAS_ARG, QEMU_OPTION_smb },
6655 #endif
6656 { "redir", HAS_ARG, QEMU_OPTION_redir },
6657 #endif
6659 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6660 { "append", HAS_ARG, QEMU_OPTION_append },
6661 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6663 { "S", 0, QEMU_OPTION_S },
6664 { "s", 0, QEMU_OPTION_s },
6665 { "p", HAS_ARG, QEMU_OPTION_p },
6666 { "l", HAS_ARG, QEMU_OPTION_l },
6667 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6668 { "L", HAS_ARG, QEMU_OPTION_L },
6669 #ifdef USE_CODE_COPY
6670 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6671 #endif
6672 #ifdef USE_KQEMU
6673 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6674 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6675 #endif
6676 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6677 { "g", 1, QEMU_OPTION_g },
6678 #endif
6679 { "localtime", 0, QEMU_OPTION_localtime },
6680 { "std-vga", 0, QEMU_OPTION_std_vga },
6681 { "monitor", 1, QEMU_OPTION_monitor },
6682 { "domain-name", 1, QEMU_OPTION_domainname },
6683 { "serial", 1, QEMU_OPTION_serial },
6684 { "parallel", 1, QEMU_OPTION_parallel },
6685 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6686 { "full-screen", 0, QEMU_OPTION_full_screen },
6687 #ifdef CONFIG_SDL
6688 { "no-quit", 0, QEMU_OPTION_no_quit },
6689 #endif
6690 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6691 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6692 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6693 { "smp", HAS_ARG, QEMU_OPTION_smp },
6694 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6695 { "vncviewer", 0, QEMU_OPTION_vncviewer },
6696 { "vncunused", 0, QEMU_OPTION_vncunused },
6698 /* temporary options */
6699 { "usb", 0, QEMU_OPTION_usb },
6700 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6701 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6702 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6703 { "daemonize", 0, QEMU_OPTION_daemonize },
6704 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6705 #if defined(TARGET_ARM)
6706 { "semihosting", 0, QEMU_OPTION_semihosting },
6707 #endif
6709 { "d", HAS_ARG, QEMU_OPTION_d },
6710 { "vcpus", 1, QEMU_OPTION_vcpus },
6711 { "acpi", 0, QEMU_OPTION_acpi },
6712 { "pci", HAS_ARG, QEMU_OPTION_pci},
6713 { NULL },
6714 };
6716 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6718 /* this stack is only used during signal handling */
6719 #define SIGNAL_STACK_SIZE 32768
6721 static uint8_t *signal_stack;
6723 #endif
6725 /* password input */
6727 static BlockDriverState *get_bdrv(int index)
6729 BlockDriverState *bs;
6731 if (index < 4) {
6732 bs = bs_table[index];
6733 } else if (index < 6) {
6734 bs = fd_table[index - 4];
6735 } else {
6736 bs = NULL;
6738 return bs;
6741 static void read_passwords(void)
6743 BlockDriverState *bs;
6744 int i, j;
6745 char password[256];
6747 for(i = 0; i < 6; i++) {
6748 bs = get_bdrv(i);
6749 if (bs && bdrv_is_encrypted(bs)) {
6750 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6751 for(j = 0; j < 3; j++) {
6752 monitor_readline("Password: ",
6753 1, password, sizeof(password));
6754 if (bdrv_set_key(bs, password) == 0)
6755 break;
6756 term_printf("invalid password\n");
6762 /* XXX: currently we cannot use simultaneously different CPUs */
6763 void register_machines(void)
6765 #if defined(TARGET_I386)
6766 #ifndef CONFIG_DM
6767 qemu_register_machine(&pc_machine);
6768 qemu_register_machine(&isapc_machine);
6769 #else
6770 qemu_register_machine(&xenfv_machine);
6771 qemu_register_machine(&xenpv_machine);
6772 #endif
6773 #elif defined(TARGET_PPC)
6774 qemu_register_machine(&heathrow_machine);
6775 qemu_register_machine(&core99_machine);
6776 qemu_register_machine(&prep_machine);
6777 #elif defined(TARGET_MIPS)
6778 qemu_register_machine(&mips_machine);
6779 qemu_register_machine(&mips_malta_machine);
6780 #elif defined(TARGET_SPARC)
6781 #ifdef TARGET_SPARC64
6782 qemu_register_machine(&sun4u_machine);
6783 #else
6784 qemu_register_machine(&sun4m_machine);
6785 #endif
6786 #elif defined(TARGET_ARM)
6787 qemu_register_machine(&integratorcp926_machine);
6788 qemu_register_machine(&integratorcp1026_machine);
6789 qemu_register_machine(&versatilepb_machine);
6790 qemu_register_machine(&versatileab_machine);
6791 qemu_register_machine(&realview_machine);
6792 #elif defined(TARGET_SH4)
6793 qemu_register_machine(&shix_machine);
6794 #else
6795 #error unsupported CPU
6796 #endif
6799 #ifdef HAS_AUDIO
6800 struct soundhw soundhw[] = {
6801 #ifndef CONFIG_DM
6802 #ifdef TARGET_I386
6804 "pcspk",
6805 "PC speaker",
6806 0,
6807 1,
6808 { .init_isa = pcspk_audio_init }
6809 },
6810 #endif
6811 #endif /* !CONFIG_DM */
6813 "sb16",
6814 "Creative Sound Blaster 16",
6815 0,
6816 1,
6817 { .init_isa = SB16_init }
6818 },
6820 #ifdef CONFIG_ADLIB
6822 "adlib",
6823 #ifdef HAS_YMF262
6824 "Yamaha YMF262 (OPL3)",
6825 #else
6826 "Yamaha YM3812 (OPL2)",
6827 #endif
6828 0,
6829 1,
6830 { .init_isa = Adlib_init }
6831 },
6832 #endif
6834 #ifdef CONFIG_GUS
6836 "gus",
6837 "Gravis Ultrasound GF1",
6838 0,
6839 1,
6840 { .init_isa = GUS_init }
6841 },
6842 #endif
6845 "es1370",
6846 "ENSONIQ AudioPCI ES1370",
6847 0,
6848 0,
6849 { .init_pci = es1370_init }
6850 },
6852 { NULL, NULL, 0, 0, { NULL } }
6853 };
6855 static void select_soundhw (const char *optarg)
6857 struct soundhw *c;
6859 if (*optarg == '?') {
6860 show_valid_cards:
6862 printf ("Valid sound card names (comma separated):\n");
6863 for (c = soundhw; c->name; ++c) {
6864 printf ("%-11s %s\n", c->name, c->descr);
6866 printf ("\n-soundhw all will enable all of the above\n");
6867 exit (*optarg != '?');
6869 else {
6870 size_t l;
6871 const char *p;
6872 char *e;
6873 int bad_card = 0;
6875 if (!strcmp (optarg, "all")) {
6876 for (c = soundhw; c->name; ++c) {
6877 c->enabled = 1;
6879 return;
6882 p = optarg;
6883 while (*p) {
6884 e = strchr (p, ',');
6885 l = !e ? strlen (p) : (size_t) (e - p);
6887 for (c = soundhw; c->name; ++c) {
6888 if (!strncmp (c->name, p, l)) {
6889 c->enabled = 1;
6890 break;
6894 if (!c->name) {
6895 if (l > 80) {
6896 fprintf (stderr,
6897 "Unknown sound card name (too big to show)\n");
6899 else {
6900 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6901 (int) l, p);
6903 bad_card = 1;
6905 p += l + (e != NULL);
6908 if (bad_card)
6909 goto show_valid_cards;
6912 #endif
6914 #ifdef _WIN32
6915 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6917 exit(STATUS_CONTROL_C_EXIT);
6918 return TRUE;
6920 #endif
6922 #define MAX_NET_CLIENTS 32
6924 #include <xg_private.h>
6926 /* FIXME Flush the shadow page */
6927 int unset_mm_mapping(int xc_handle, uint32_t domid,
6928 unsigned long nr_pages, unsigned int address_bits,
6929 xen_pfn_t *extent_start)
6931 int err = 0;
6932 xc_dominfo_t info;
6934 xc_domain_getinfo(xc_handle, domid, 1, &info);
6935 if ((info.nr_pages - nr_pages) <= 0) {
6936 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
6937 err = -1;
6940 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
6941 nr_pages, 0, extent_start);
6942 if (err)
6943 fprintf(stderr, "Failed to decrease physmap\n");
6946 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
6947 PAGE_SIZE/1024) != 0) {
6948 fprintf(logfile, "set maxmem returned error %d\n", errno);
6949 err = -1;
6952 return err;
6955 int set_mm_mapping(int xc_handle, uint32_t domid,
6956 unsigned long nr_pages, unsigned int address_bits,
6957 xen_pfn_t *extent_start)
6959 xc_dominfo_t info;
6960 int err = 0;
6962 xc_domain_getinfo(xc_handle, domid, 1, &info);
6964 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
6965 nr_pages * PAGE_SIZE/1024) != 0) {
6966 fprintf(logfile, "set maxmem returned error %d\n", errno);
6967 return -1;
6970 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
6971 address_bits, extent_start);
6972 if (err) {
6973 fprintf(stderr, "Failed to populate physmap\n");
6974 return -1;
6977 return 0;
6981 int main(int argc, char **argv)
6983 #ifdef CONFIG_GDBSTUB
6984 int use_gdbstub, gdbstub_port;
6985 #endif
6986 int i;
6987 #ifndef CONFIG_DM
6988 int cdrom_index;
6989 #endif /* !CONFIG_DM */
6990 int snapshot, linux_boot;
6991 const char *initrd_filename;
6992 #ifndef CONFIG_DM
6993 const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
6994 #endif /* !CONFIG_DM */
6995 const char *fd_filename[MAX_FD];
6996 const char *kernel_filename, *kernel_cmdline;
6997 DisplayState *ds = &display_state;
6998 int cyls, heads, secs, translation;
6999 char net_clients[MAX_NET_CLIENTS][256];
7000 int nb_net_clients;
7001 int optind;
7002 const char *r, *optarg;
7003 CharDriverState *monitor_hd;
7004 char monitor_device[128];
7005 char serial_devices[MAX_SERIAL_PORTS][128];
7006 int serial_device_index;
7007 char parallel_devices[MAX_PARALLEL_PORTS][128];
7008 int parallel_device_index;
7009 const char *loadvm = NULL;
7010 QEMUMachine *machine;
7011 char usb_devices[MAX_USB_CMDLINE][128];
7012 int usb_devices_index;
7013 int fds[2];
7014 struct rlimit rl;
7015 sigset_t set;
7016 char qemu_dm_logfilename[128];
7017 const char *direct_pci = NULL;
7019 #ifndef __sun__
7020 /* Maximise rlimits. Needed where default constraints are tight (*BSD). */
7021 if (getrlimit(RLIMIT_STACK, &rl) != 0) {
7022 perror("getrlimit(RLIMIT_STACK)");
7023 exit(1);
7025 rl.rlim_cur = rl.rlim_max;
7026 if (setrlimit(RLIMIT_STACK, &rl) != 0)
7027 perror("setrlimit(RLIMIT_STACK)");
7028 if (getrlimit(RLIMIT_DATA, &rl) != 0) {
7029 perror("getrlimit(RLIMIT_DATA)");
7030 exit(1);
7032 rl.rlim_cur = rl.rlim_max;
7033 if (setrlimit(RLIMIT_DATA, &rl) != 0)
7034 perror("setrlimit(RLIMIT_DATA)");
7035 rl.rlim_cur = RLIM_INFINITY;
7036 rl.rlim_max = RLIM_INFINITY;
7037 if (setrlimit(RLIMIT_RSS, &rl) != 0)
7038 perror("setrlimit(RLIMIT_RSS)");
7039 rl.rlim_cur = RLIM_INFINITY;
7040 rl.rlim_max = RLIM_INFINITY;
7041 if (setrlimit(RLIMIT_MEMLOCK, &rl) != 0)
7042 perror("setrlimit(RLIMIT_MEMLOCK)");
7043 #endif
7045 /* Ensure that SIGUSR2 is blocked by default when a new thread is created,
7046 then only the threads that use the signal unblock it -- this fixes a
7047 race condition in Qcow support where the AIO signal is misdelivered. */
7049 extern const int aio_sig_num;
7050 sigset_t set;
7052 sigemptyset(&set);
7053 sigaddset(&set, aio_sig_num);
7054 sigprocmask(SIG_BLOCK, &set, NULL);
7057 LIST_INIT (&vm_change_state_head);
7058 #ifndef _WIN32
7060 struct sigaction act;
7061 sigfillset(&act.sa_mask);
7062 act.sa_flags = 0;
7063 act.sa_handler = SIG_IGN;
7064 sigaction(SIGPIPE, &act, NULL);
7066 #else
7067 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7068 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7069 QEMU to run on a single CPU */
7071 HANDLE h;
7072 DWORD mask, smask;
7073 int i;
7074 h = GetCurrentProcess();
7075 if (GetProcessAffinityMask(h, &mask, &smask)) {
7076 for(i = 0; i < 32; i++) {
7077 if (mask & (1 << i))
7078 break;
7080 if (i != 32) {
7081 mask = 1 << i;
7082 SetProcessAffinityMask(h, mask);
7086 #endif
7088 register_machines();
7089 machine = first_machine;
7090 initrd_filename = NULL;
7091 for(i = 0; i < MAX_FD; i++)
7092 fd_filename[i] = NULL;
7093 #ifndef CONFIG_DM
7094 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7095 hd_filename[i] = NULL;
7096 #endif /* !CONFIG_DM */
7097 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7098 vga_ram_size = VGA_RAM_SIZE;
7099 bios_size = BIOS_SIZE;
7100 #ifdef CONFIG_GDBSTUB
7101 use_gdbstub = 0;
7102 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7103 #endif
7104 snapshot = 0;
7105 nographic = 0;
7106 vncviewer = 0;
7107 vncunused = 0;
7108 kernel_filename = NULL;
7109 kernel_cmdline = "";
7110 #ifndef CONFIG_DM
7111 #ifdef TARGET_PPC
7112 cdrom_index = 1;
7113 #else
7114 cdrom_index = 2;
7115 #endif
7116 #endif /* !CONFIG_DM */
7117 cyls = heads = secs = 0;
7118 translation = BIOS_ATA_TRANSLATION_AUTO;
7119 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7121 for(i = 0; i < MAX_SERIAL_PORTS; i++)
7122 serial_devices[i][0] = '\0';
7123 serial_device_index = 0;
7125 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7126 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7127 parallel_devices[i][0] = '\0';
7128 parallel_device_index = 0;
7130 usb_devices_index = 0;
7132 nb_net_clients = 0;
7134 nb_nics = 0;
7135 /* default mac address of the first network interface */
7137 /* Init logs to stderr to start with */
7138 cpu_set_log(0);
7140 optind = 1;
7141 for(;;) {
7142 if (optind >= argc)
7143 break;
7144 r = argv[optind];
7145 if (r[0] != '-') {
7146 #ifndef CONFIG_DM
7147 hd_filename[0] = argv[optind++];
7148 #else
7149 help();
7150 #endif /* !CONFIG_DM */
7151 } else {
7152 const QEMUOption *popt;
7154 optind++;
7155 /* Treat --foo the same as -foo. */
7156 if (r[1] == '-')
7157 r++;
7158 popt = qemu_options;
7159 for(;;) {
7160 if (!popt->name) {
7161 fprintf(stderr, "%s: invalid option -- '%s'\n",
7162 argv[0], r);
7163 exit(1);
7165 if (!strcmp(popt->name, r + 1))
7166 break;
7167 popt++;
7169 if (popt->flags & HAS_ARG) {
7170 if (optind >= argc) {
7171 fprintf(stderr, "%s: option '%s' requires an argument\n",
7172 argv[0], r);
7173 exit(1);
7175 optarg = argv[optind++];
7176 } else {
7177 optarg = NULL;
7180 switch(popt->index) {
7181 case QEMU_OPTION_M:
7182 machine = find_machine(optarg);
7183 if (!machine) {
7184 QEMUMachine *m;
7185 printf("Supported machines are:\n");
7186 for(m = first_machine; m != NULL; m = m->next) {
7187 printf("%-10s %s%s\n",
7188 m->name, m->desc,
7189 m == first_machine ? " (default)" : "");
7191 exit(1);
7193 break;
7194 case QEMU_OPTION_initrd:
7195 initrd_filename = optarg;
7196 break;
7197 #ifndef CONFIG_DM
7198 case QEMU_OPTION_hda:
7199 case QEMU_OPTION_hdb:
7200 case QEMU_OPTION_hdc:
7201 case QEMU_OPTION_hdd:
7203 int hd_index;
7204 hd_index = popt->index - QEMU_OPTION_hda;
7205 hd_filename[hd_index] = optarg;
7206 if (hd_index == cdrom_index)
7207 cdrom_index = -1;
7209 break;
7210 #endif /* !CONFIG_DM */
7211 case QEMU_OPTION_snapshot:
7212 snapshot = 1;
7213 break;
7214 case QEMU_OPTION_hdachs:
7216 const char *p;
7217 p = optarg;
7218 cyls = strtol(p, (char **)&p, 0);
7219 if (cyls < 1 || cyls > 16383)
7220 goto chs_fail;
7221 if (*p != ',')
7222 goto chs_fail;
7223 p++;
7224 heads = strtol(p, (char **)&p, 0);
7225 if (heads < 1 || heads > 16)
7226 goto chs_fail;
7227 if (*p != ',')
7228 goto chs_fail;
7229 p++;
7230 secs = strtol(p, (char **)&p, 0);
7231 if (secs < 1 || secs > 63)
7232 goto chs_fail;
7233 if (*p == ',') {
7234 p++;
7235 if (!strcmp(p, "none"))
7236 translation = BIOS_ATA_TRANSLATION_NONE;
7237 else if (!strcmp(p, "lba"))
7238 translation = BIOS_ATA_TRANSLATION_LBA;
7239 else if (!strcmp(p, "auto"))
7240 translation = BIOS_ATA_TRANSLATION_AUTO;
7241 else
7242 goto chs_fail;
7243 } else if (*p != '\0') {
7244 chs_fail:
7245 fprintf(stderr, "qemu: invalid physical CHS format\n");
7246 exit(1);
7249 break;
7250 case QEMU_OPTION_nographic:
7251 if(!strcmp(monitor_device, "vc"))
7252 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7253 if(!strcmp(serial_devices[0], "vc"))
7254 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7255 "null");
7256 nographic = 1;
7257 break;
7258 case QEMU_OPTION_kernel:
7259 kernel_filename = optarg;
7260 break;
7261 case QEMU_OPTION_append:
7262 kernel_cmdline = optarg;
7263 break;
7264 #ifndef CONFIG_DM
7265 case QEMU_OPTION_cdrom:
7266 if (cdrom_index >= 0) {
7267 hd_filename[cdrom_index] = optarg;
7269 break;
7270 #endif /* !CONFIG_DM */
7271 case QEMU_OPTION_boot:
7272 boot_device = strdup(optarg);
7273 if (strspn(boot_device, "a"
7274 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7275 // Network boot
7276 "n"
7277 #endif
7278 "cd") != strlen(boot_device)) {
7279 fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7280 exit(1);
7282 break;
7283 case QEMU_OPTION_fda:
7284 fd_filename[0] = optarg;
7285 break;
7286 case QEMU_OPTION_fdb:
7287 fd_filename[1] = optarg;
7288 break;
7289 #ifdef TARGET_I386
7290 case QEMU_OPTION_no_fd_bootchk:
7291 fd_bootchk = 0;
7292 break;
7293 #endif
7294 #ifdef USE_CODE_COPY
7295 case QEMU_OPTION_no_code_copy:
7296 code_copy_enabled = 0;
7297 break;
7298 #endif
7299 case QEMU_OPTION_net:
7300 if (nb_net_clients >= MAX_NET_CLIENTS) {
7301 fprintf(stderr, "qemu: too many network clients\n");
7302 exit(1);
7304 pstrcpy(net_clients[nb_net_clients],
7305 sizeof(net_clients[0]),
7306 optarg);
7307 nb_net_clients++;
7308 break;
7309 #ifdef CONFIG_SLIRP
7310 case QEMU_OPTION_tftp:
7311 tftp_prefix = optarg;
7312 break;
7313 #ifndef _WIN32
7314 case QEMU_OPTION_smb:
7315 net_slirp_smb(optarg);
7316 break;
7317 #endif
7318 case QEMU_OPTION_redir:
7319 net_slirp_redir(optarg);
7320 break;
7321 #endif
7322 #ifdef HAS_AUDIO
7323 case QEMU_OPTION_audio_help:
7324 AUD_help ();
7325 exit (0);
7326 break;
7327 case QEMU_OPTION_soundhw:
7328 select_soundhw (optarg);
7329 break;
7330 #endif
7331 case QEMU_OPTION_h:
7332 help();
7333 break;
7334 case QEMU_OPTION_m:
7335 ram_size = atol(optarg) * 1024 * 1024;
7336 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7337 if (ram_size <= 0)
7338 help();
7339 #ifndef CONFIG_DM
7340 if (ram_size > PHYS_RAM_MAX_SIZE) {
7341 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7342 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7343 exit(1);
7345 #endif /* !CONFIG_DM */
7346 break;
7347 case QEMU_OPTION_l:
7349 int mask;
7350 CPULogItem *item;
7352 mask = cpu_str_to_log_mask(optarg);
7353 if (!mask) {
7354 printf("Log items (comma separated):\n");
7355 for(item = cpu_log_items; item->mask != 0; item++) {
7356 printf("%-10s %s\n", item->name, item->help);
7358 exit(1);
7360 cpu_set_log(mask);
7362 break;
7363 #ifdef CONFIG_GDBSTUB
7364 case QEMU_OPTION_s:
7365 use_gdbstub = 1;
7366 break;
7367 case QEMU_OPTION_p:
7368 gdbstub_port = atoi(optarg);
7369 break;
7370 #endif
7371 case QEMU_OPTION_L:
7372 bios_dir = optarg;
7373 break;
7374 case QEMU_OPTION_S:
7375 autostart = 0;
7376 break;
7377 case QEMU_OPTION_k:
7378 keyboard_layout = optarg;
7379 break;
7380 case QEMU_OPTION_localtime:
7381 rtc_utc = 0;
7382 break;
7383 case QEMU_OPTION_cirrusvga:
7384 cirrus_vga_enabled = 1;
7385 break;
7386 case QEMU_OPTION_std_vga:
7387 cirrus_vga_enabled = 0;
7388 break;
7389 case QEMU_OPTION_g:
7391 const char *p;
7392 int w, h, depth;
7393 p = optarg;
7394 w = strtol(p, (char **)&p, 10);
7395 if (w <= 0) {
7396 graphic_error:
7397 fprintf(stderr, "qemu: invalid resolution or depth\n");
7398 exit(1);
7400 if (*p != 'x')
7401 goto graphic_error;
7402 p++;
7403 h = strtol(p, (char **)&p, 10);
7404 if (h <= 0)
7405 goto graphic_error;
7406 if (*p == 'x') {
7407 p++;
7408 depth = strtol(p, (char **)&p, 10);
7409 if (depth != 8 && depth != 15 && depth != 16 &&
7410 depth != 24 && depth != 32)
7411 goto graphic_error;
7412 } else if (*p == '\0') {
7413 depth = graphic_depth;
7414 } else {
7415 goto graphic_error;
7418 graphic_width = w;
7419 graphic_height = h;
7420 graphic_depth = depth;
7422 break;
7423 case QEMU_OPTION_monitor:
7424 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7425 break;
7426 case QEMU_OPTION_serial:
7427 if (serial_device_index >= MAX_SERIAL_PORTS) {
7428 fprintf(stderr, "qemu: too many serial ports\n");
7429 exit(1);
7431 pstrcpy(serial_devices[serial_device_index],
7432 sizeof(serial_devices[0]), optarg);
7433 serial_device_index++;
7434 break;
7435 case QEMU_OPTION_parallel:
7436 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7437 fprintf(stderr, "qemu: too many parallel ports\n");
7438 exit(1);
7440 pstrcpy(parallel_devices[parallel_device_index],
7441 sizeof(parallel_devices[0]), optarg);
7442 parallel_device_index++;
7443 break;
7444 case QEMU_OPTION_loadvm:
7445 loadvm = optarg;
7446 break;
7447 case QEMU_OPTION_full_screen:
7448 full_screen = 1;
7449 break;
7450 #ifdef CONFIG_SDL
7451 case QEMU_OPTION_no_quit:
7452 no_quit = 1;
7453 break;
7454 #endif
7455 case QEMU_OPTION_pidfile:
7456 create_pidfile(optarg);
7457 break;
7458 #ifdef TARGET_I386
7459 case QEMU_OPTION_win2k_hack:
7460 win2k_install_hack = 1;
7461 break;
7462 #endif
7463 #ifdef USE_KQEMU
7464 case QEMU_OPTION_no_kqemu:
7465 kqemu_allowed = 0;
7466 break;
7467 case QEMU_OPTION_kernel_kqemu:
7468 kqemu_allowed = 2;
7469 break;
7470 #endif
7471 case QEMU_OPTION_usb:
7472 usb_enabled = 1;
7473 break;
7474 case QEMU_OPTION_usbdevice:
7475 usb_enabled = 1;
7476 if (usb_devices_index >= MAX_USB_CMDLINE) {
7477 fprintf(stderr, "Too many USB devices\n");
7478 exit(1);
7480 pstrcpy(usb_devices[usb_devices_index],
7481 sizeof(usb_devices[usb_devices_index]),
7482 optarg);
7483 usb_devices_index++;
7484 break;
7485 case QEMU_OPTION_smp:
7486 smp_cpus = atoi(optarg);
7487 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7488 fprintf(stderr, "Invalid number of CPUs\n");
7489 exit(1);
7491 break;
7492 case QEMU_OPTION_vnc:
7493 vnc_display = optarg;
7494 break;
7495 case QEMU_OPTION_no_acpi:
7496 acpi_enabled = 0;
7497 break;
7498 case QEMU_OPTION_no_reboot:
7499 no_reboot = 1;
7500 break;
7501 case QEMU_OPTION_daemonize:
7502 daemonize = 1;
7503 break;
7504 case QEMU_OPTION_option_rom:
7505 if (nb_option_roms >= MAX_OPTION_ROMS) {
7506 fprintf(stderr, "Too many option ROMs\n");
7507 exit(1);
7509 option_rom[nb_option_roms] = optarg;
7510 nb_option_roms++;
7511 break;
7512 case QEMU_OPTION_semihosting:
7513 semihosting_enabled = 1;
7514 break;
7515 case QEMU_OPTION_domainname:
7516 snprintf(domain_name, sizeof(domain_name),
7517 "Xen-%s", optarg);
7518 break;
7519 case QEMU_OPTION_d:
7520 domid = atoi(optarg);
7521 fprintf(logfile, "domid: %d\n", domid);
7522 break;
7523 case QEMU_OPTION_vcpus:
7524 vcpus = atoi(optarg);
7525 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7526 break;
7527 case QEMU_OPTION_acpi:
7528 acpi_enabled = 1;
7529 break;
7530 case QEMU_OPTION_vncviewer:
7531 vncviewer++;
7532 break;
7533 case QEMU_OPTION_vncunused:
7534 vncunused++;
7535 break;
7536 case QEMU_OPTION_pci:
7537 direct_pci = optarg;
7538 break;
7543 /* Now send logs to our named config */
7544 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm-%d.log", domid);
7545 cpu_set_log_filename(qemu_dm_logfilename);
7547 #ifndef _WIN32
7548 if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7549 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7550 daemonize = 0;
7553 if (daemonize) {
7554 pid_t pid;
7556 if (pipe(fds) == -1)
7557 exit(1);
7559 pid = fork();
7560 if (pid > 0) {
7561 uint8_t status;
7562 ssize_t len;
7564 close(fds[1]);
7566 again:
7567 len = read(fds[0], &status, 1);
7568 if (len == -1 && (errno == EINTR))
7569 goto again;
7571 if (len != 1 || status != 0)
7572 exit(1);
7573 else
7574 exit(0);
7575 } else if (pid < 0)
7576 exit(1);
7578 setsid();
7580 pid = fork();
7581 if (pid > 0)
7582 exit(0);
7583 else if (pid < 0)
7584 exit(1);
7586 umask(027);
7587 chdir("/");
7589 signal(SIGTSTP, SIG_IGN);
7590 signal(SIGTTOU, SIG_IGN);
7591 signal(SIGTTIN, SIG_IGN);
7593 #endif
7595 #ifdef CONFIG_DM
7596 bdrv_init();
7597 xc_handle = xc_interface_open();
7598 xenstore_parse_domain_config(domid);
7599 #endif /* CONFIG_DM */
7601 #ifdef USE_KQEMU
7602 if (smp_cpus > 1)
7603 kqemu_allowed = 0;
7604 #endif
7605 linux_boot = (kernel_filename != NULL);
7607 #ifndef CONFIG_DM
7608 if (!linux_boot &&
7609 hd_filename[0] == '\0' &&
7610 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7611 fd_filename[0] == '\0')
7612 help();
7614 /* boot to floppy or the default cd if no hard disk defined yet */
7615 if (hd_filename[0] == '\0' && boot_device == 'c') {
7616 if (fd_filename[0] != '\0')
7617 boot_device = 'a';
7618 else
7619 boot_device = 'd';
7621 #endif /* !CONFIG_DM */
7623 setvbuf(stdout, NULL, _IOLBF, 0);
7625 init_timers();
7626 init_timer_alarm();
7627 qemu_aio_init();
7629 #ifdef _WIN32
7630 socket_init();
7631 #endif
7633 #ifndef CONFIG_DM
7634 /* init network clients */
7635 if (nb_net_clients == 0) {
7636 /* if no clients, we use a default config */
7637 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7638 "nic");
7639 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7640 "user");
7641 nb_net_clients = 2;
7643 #endif /* !CONFIG_DM */
7645 for(i = 0;i < nb_net_clients; i++) {
7646 if (net_client_init(net_clients[i]) < 0)
7647 exit(1);
7650 #ifndef CONFIG_DM
7651 #ifdef TARGET_I386
7652 if (boot_device == 'n') {
7653 for (i = 0; i < nb_nics; i++) {
7654 const char *model = nd_table[i].model;
7655 char buf[1024];
7656 if (model == NULL)
7657 model = "ne2k_pci";
7658 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7659 if (get_image_size(buf) > 0) {
7660 option_rom[nb_option_roms] = strdup(buf);
7661 nb_option_roms++;
7662 break;
7665 if (i == nb_nics) {
7666 fprintf(stderr, "No valid PXE rom found for network device\n");
7667 exit(1);
7669 boot_device = 'c'; /* to prevent confusion by the BIOS */
7671 #endif
7672 #endif /* !CONFIG_DM */
7674 #if defined (__ia64__)
7675 if (ram_size > MMIO_START)
7676 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
7677 #endif
7679 /* init the memory */
7680 phys_ram_size = ram_size + vga_ram_size + bios_size;
7682 #ifndef CONFIG_DM
7683 for (i = 0; i < nb_option_roms; i++) {
7684 int ret = get_image_size(option_rom[i]);
7685 if (ret == -1) {
7686 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7687 exit(1);
7689 phys_ram_size += ret;
7692 phys_ram_base = qemu_vmalloc(phys_ram_size);
7693 if (!phys_ram_base) {
7694 fprintf(stderr, "Could not allocate physical memory\n");
7695 exit(1);
7698 /* we always create the cdrom drive, even if no disk is there */
7699 bdrv_init();
7700 if (cdrom_index >= 0) {
7701 bs_table[cdrom_index] = bdrv_new("cdrom");
7702 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7705 /* open the virtual block devices */
7706 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
7707 if (hd_filename[i]) {
7708 if (!bs_table[i]) {
7709 char buf[64];
7710 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7711 bs_table[i] = bdrv_new(buf);
7713 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7714 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7715 hd_filename[i]);
7716 exit(1);
7718 if (i == 0 && cyls != 0) {
7719 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7720 bdrv_set_translation_hint(bs_table[i], translation);
7724 #endif /* !CONFIG_DM */
7726 /* we always create at least one floppy disk */
7727 fd_table[0] = bdrv_new("fda");
7728 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7730 for(i = 0; i < MAX_FD; i++) {
7731 if (fd_filename[i]) {
7732 if (!fd_table[i]) {
7733 char buf[64];
7734 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7735 fd_table[i] = bdrv_new(buf);
7736 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7738 if (fd_filename[i] != '\0') {
7739 if (bdrv_open(fd_table[i], fd_filename[i],
7740 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7741 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7742 fd_filename[i]);
7743 exit(1);
7749 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7750 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7752 init_ioports();
7754 /* terminal init */
7755 if (nographic) {
7756 dumb_display_init(ds);
7757 } else if (vnc_display != NULL || vncunused != 0) {
7758 int vnc_display_port;
7759 char password[20];
7760 vnc_display_init(ds);
7761 if (xenstore_read_vncpasswd(domid, password, sizeof(password)) < 0)
7762 exit(0);
7763 vnc_display_password(ds, password);
7764 if ((vnc_display_port = vnc_display_open(ds, vnc_display, vncunused)) < 0)
7765 exit (0);
7766 if (vncviewer)
7767 vnc_start_viewer(vnc_display_port);
7768 xenstore_write_vncport(vnc_display_port);
7769 } else {
7770 #if defined(CONFIG_SDL)
7771 sdl_display_init(ds, full_screen);
7772 #elif defined(CONFIG_COCOA)
7773 cocoa_display_init(ds, full_screen);
7774 #else
7775 dumb_display_init(ds);
7776 #endif
7779 monitor_hd = qemu_chr_open(monitor_device);
7780 if (!monitor_hd) {
7781 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7782 exit(1);
7784 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
7785 monitor_init(monitor_hd, !nographic);
7787 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7788 const char *devname = serial_devices[i];
7789 if (devname[0] != '\0' && strcmp(devname, "none")) {
7790 char buf[16];
7791 serial_hds[i] = qemu_chr_open(devname);
7792 if (!serial_hds[i]) {
7793 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7794 devname);
7795 exit(1);
7797 snprintf(buf, sizeof(buf), "/serial/%d", i);
7798 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
7799 if (i == 0) /* serial 0 is also called the console */
7800 store_dev_info(serial_devices[i], domid,
7801 serial_hds[i], "/console");
7802 if (!strcmp(devname, "vc"))
7803 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7807 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7808 const char *devname = parallel_devices[i];
7809 if (devname[0] != '\0' && strcmp(devname, "none")) {
7810 char buf[16];
7811 parallel_hds[i] = qemu_chr_open(devname);
7812 if (!parallel_hds[i]) {
7813 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7814 devname);
7815 exit(1);
7817 snprintf(buf, sizeof(buf), "/parallel/%d", i);
7818 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
7819 if (!strcmp(devname, "vc"))
7820 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7824 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
7826 machine->init(ram_size, vga_ram_size, boot_device,
7827 ds, fd_filename, snapshot,
7828 kernel_filename, kernel_cmdline, initrd_filename,
7829 direct_pci);
7830 free(boot_device);
7832 /* init USB devices */
7833 if (usb_enabled) {
7834 for(i = 0; i < usb_devices_index; i++) {
7835 if (usb_device_add(usb_devices[i]) < 0) {
7836 fprintf(stderr, "Warning: could not add USB device %s\n",
7837 usb_devices[i]);
7842 if (vnc_display == NULL && vncunused == 0) {
7843 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7844 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7847 #ifdef CONFIG_GDBSTUB
7848 if (use_gdbstub) {
7849 /* XXX: use standard host:port notation and modify options
7850 accordingly. */
7851 if (gdbserver_start_port(gdbstub_port) < 0) {
7852 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7853 gdbstub_port);
7854 exit(1);
7856 } else
7857 #endif
7858 if (loadvm)
7859 do_loadvm(loadvm);
7862 /* XXX: simplify init */
7863 read_passwords();
7864 if (autostart) {
7865 vm_start();
7869 if (daemonize) {
7870 uint8_t status = 0;
7871 ssize_t len;
7872 int fd;
7874 again1:
7875 len = write(fds[1], &status, 1);
7876 if (len == -1 && (errno == EINTR))
7877 goto again1;
7879 if (len != 1)
7880 exit(1);
7882 fd = open("/dev/null", O_RDWR);
7883 if (fd == -1)
7884 exit(1);
7886 dup2(fd, 0);
7887 dup2(fd, 1);
7888 dup2(fd, 2);
7890 close(fd);
7893 /* Unblock SIGTERM, which may have been blocked by the caller */
7894 sigemptyset(&set);
7895 sigaddset(&set, SIGTERM);
7896 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
7897 fprintf(stderr, "Failed to unblock SIGTERM\n");
7899 main_loop();
7900 quit_timers();
7901 return 0;