]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
fix for hosts resuming from software suspend (initial patch by John Coiner)
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
0824d6fc 3 *
d827220b 4 * Copyright (c) 2003-2005 Fabrice Bellard
0824d6fc 5 *
1df912cf
FB
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.
0824d6fc 23 */
67b915a5
FB
24#include "vl.h"
25
0824d6fc 26#include <unistd.h>
0824d6fc
FB
27#include <fcntl.h>
28#include <signal.h>
29#include <time.h>
0824d6fc 30#include <errno.h>
67b915a5
FB
31#include <sys/time.h>
32
33#ifndef _WIN32
34#include <sys/times.h>
f1510b2c 35#include <sys/wait.h>
67b915a5
FB
36#include <termios.h>
37#include <sys/poll.h>
38#include <sys/mman.h>
f1510b2c
FB
39#include <sys/ioctl.h>
40#include <sys/socket.h>
c94c8d64 41#include <netinet/in.h>
9d728e8c 42#include <dirent.h>
7c9d8e07 43#include <netdb.h>
7d3505c5
FB
44#ifdef _BSD
45#include <sys/stat.h>
83fb7adf 46#ifndef __APPLE__
7d3505c5 47#include <libutil.h>
83fb7adf 48#endif
7d3505c5 49#else
ec530c81 50#ifndef __sun__
f1510b2c
FB
51#include <linux/if.h>
52#include <linux/if_tun.h>
7d3505c5
FB
53#include <pty.h>
54#include <malloc.h>
fd872598 55#include <linux/rtc.h>
e57a8c0e 56#include <linux/ppdev.h>
67b915a5 57#endif
7d3505c5 58#endif
ec530c81 59#endif
67b915a5 60
c20709aa
FB
61#if defined(CONFIG_SLIRP)
62#include "libslirp.h"
63#endif
64
67b915a5 65#ifdef _WIN32
7d3505c5 66#include <malloc.h>
67b915a5
FB
67#include <sys/timeb.h>
68#include <windows.h>
69#define getopt_long_only getopt_long
70#define memalign(align, size) malloc(size)
71#endif
72
6ca957f0
FB
73#include "qemu_socket.h"
74
73332e5c 75#ifdef CONFIG_SDL
96bcd4f8 76#ifdef __APPLE__
83fb7adf 77#include <SDL/SDL.h>
96bcd4f8 78#endif
73332e5c 79#endif /* CONFIG_SDL */
0824d6fc 80
5b0753e0
FB
81#ifdef CONFIG_COCOA
82#undef main
83#define main qemu_main
84#endif /* CONFIG_COCOA */
85
0824d6fc 86#include "disas.h"
fc01f7e7 87
8a7ddc38 88#include "exec-all.h"
0824d6fc 89
5a67135a 90#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
f1510b2c 91
0824d6fc 92//#define DEBUG_UNUSED_IOPORT
fd872598 93//#define DEBUG_IOPORT
330d0414 94
bb551faa 95#if !defined(CONFIG_SOFTMMU)
7916e224 96#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
bb551faa
FB
97#else
98#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99#endif
7916e224 100
77d4bc34
FB
101#ifdef TARGET_PPC
102#define DEFAULT_RAM_SIZE 144
103#else
1bfe856e 104#define DEFAULT_RAM_SIZE 128
77d4bc34 105#endif
8a7ddc38
FB
106/* in ms */
107#define GUI_REFRESH_INTERVAL 30
313aa567 108
7dea1da4
FB
109/* XXX: use a two level table to limit memory usage */
110#define MAX_IOPORTS 65536
0824d6fc 111
80cabfad 112const char *bios_dir = CONFIG_QEMU_SHAREDIR;
0824d6fc 113char phys_ram_file[1024];
c4b1fcc0 114void *ioport_opaque[MAX_IOPORTS];
fc01f7e7
FB
115IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
c45886db 117BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
313aa567 118int vga_ram_size;
0ced6589 119int bios_size;
313aa567 120static DisplayState display_state;
a20dd508 121int nographic;
3d11d0eb 122const char* keyboard_layout = NULL;
313aa567 123int64_t ticks_per_sec;
36b486bb 124int boot_device = 'c';
0ced6589 125int ram_size;
80cabfad 126int pit_min_timer_count = 0;
c4b1fcc0 127int nb_nics;
7c9d8e07 128NICInfo nd_table[MAX_NICS];
8a7ddc38
FB
129QEMUTimer *gui_timer;
130int vm_running;
ee22c2f7 131int rtc_utc = 1;
1bfe856e 132int cirrus_vga_enabled = 1;
d827220b
FB
133#ifdef TARGET_SPARC
134int graphic_width = 1024;
135int graphic_height = 768;
136#else
1bfe856e
FB
137int graphic_width = 800;
138int graphic_height = 600;
d827220b 139#endif
e9b137c2 140int graphic_depth = 15;
d63d307f 141int full_screen = 0;
8d11df9e 142CharDriverState *serial_hds[MAX_SERIAL_PORTS];
6508fe59 143CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
a09db21f
FB
144#ifdef TARGET_I386
145int win2k_install_hack = 0;
146#endif
bb36d470 147int usb_enabled = 0;
a594cfbf
FB
148USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
149USBDevice *vm_usb_hub;
7c9d8e07 150static VLANState *first_vlan;
6a00d601 151int smp_cpus = 1;
24236869 152int vnc_display = -1;
d3e9db93 153#if defined(TARGET_SPARC)
ba3c64fb 154#define MAX_CPUS 16
d3e9db93
FB
155#elif defined(TARGET_I386)
156#define MAX_CPUS 255
ba3c64fb 157#else
d3e9db93 158#define MAX_CPUS 1
ba3c64fb 159#endif
0824d6fc
FB
160
161/***********************************************************/
26aa7d72
FB
162/* x86 ISA bus support */
163
164target_phys_addr_t isa_mem_base = 0;
3de388f6 165PicState2 *isa_pic;
0824d6fc 166
c4b1fcc0 167uint32_t default_ioport_readb(void *opaque, uint32_t address)
0824d6fc
FB
168{
169#ifdef DEBUG_UNUSED_IOPORT
170 fprintf(stderr, "inb: port=0x%04x\n", address);
171#endif
fc01f7e7 172 return 0xff;
0824d6fc
FB
173}
174
c4b1fcc0 175void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
0824d6fc
FB
176{
177#ifdef DEBUG_UNUSED_IOPORT
178 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
179#endif
180}
181
182/* default is to make two byte accesses */
c4b1fcc0 183uint32_t default_ioport_readw(void *opaque, uint32_t address)
0824d6fc
FB
184{
185 uint32_t data;
db45c29a
FB
186 data = ioport_read_table[0][address](ioport_opaque[address], address);
187 address = (address + 1) & (MAX_IOPORTS - 1);
188 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
0824d6fc
FB
189 return data;
190}
191
c4b1fcc0 192void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
0824d6fc 193{
db45c29a
FB
194 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
195 address = (address + 1) & (MAX_IOPORTS - 1);
196 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
0824d6fc
FB
197}
198
c4b1fcc0 199uint32_t default_ioport_readl(void *opaque, uint32_t address)
0824d6fc 200{
fc01f7e7
FB
201#ifdef DEBUG_UNUSED_IOPORT
202 fprintf(stderr, "inl: port=0x%04x\n", address);
203#endif
204 return 0xffffffff;
0824d6fc
FB
205}
206
c4b1fcc0 207void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
0824d6fc 208{
fc01f7e7
FB
209#ifdef DEBUG_UNUSED_IOPORT
210 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
211#endif
0824d6fc
FB
212}
213
fc01f7e7 214void init_ioports(void)
0824d6fc
FB
215{
216 int i;
217
fc01f7e7
FB
218 for(i = 0; i < MAX_IOPORTS; i++) {
219 ioport_read_table[0][i] = default_ioport_readb;
220 ioport_write_table[0][i] = default_ioport_writeb;
221 ioport_read_table[1][i] = default_ioport_readw;
222 ioport_write_table[1][i] = default_ioport_writew;
223 ioport_read_table[2][i] = default_ioport_readl;
224 ioport_write_table[2][i] = default_ioport_writel;
225 }
0824d6fc
FB
226}
227
fc01f7e7 228/* size is the word size in byte */
c4b1fcc0
FB
229int register_ioport_read(int start, int length, int size,
230 IOPortReadFunc *func, void *opaque)
f1510b2c 231{
fc01f7e7 232 int i, bsize;
f1510b2c 233
c4b1fcc0 234 if (size == 1) {
fc01f7e7 235 bsize = 0;
c4b1fcc0 236 } else if (size == 2) {
fc01f7e7 237 bsize = 1;
c4b1fcc0 238 } else if (size == 4) {
fc01f7e7 239 bsize = 2;
c4b1fcc0
FB
240 } else {
241 hw_error("register_ioport_read: invalid size");
fc01f7e7 242 return -1;
c4b1fcc0
FB
243 }
244 for(i = start; i < start + length; i += size) {
fc01f7e7 245 ioport_read_table[bsize][i] = func;
c4b1fcc0
FB
246 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
247 hw_error("register_ioport_read: invalid opaque");
248 ioport_opaque[i] = opaque;
249 }
f1510b2c
FB
250 return 0;
251}
252
fc01f7e7 253/* size is the word size in byte */
c4b1fcc0
FB
254int register_ioport_write(int start, int length, int size,
255 IOPortWriteFunc *func, void *opaque)
f1510b2c 256{
fc01f7e7 257 int i, bsize;
f1510b2c 258
c4b1fcc0 259 if (size == 1) {
fc01f7e7 260 bsize = 0;
c4b1fcc0 261 } else if (size == 2) {
fc01f7e7 262 bsize = 1;
c4b1fcc0 263 } else if (size == 4) {
fc01f7e7 264 bsize = 2;
c4b1fcc0
FB
265 } else {
266 hw_error("register_ioport_write: invalid size");
fc01f7e7 267 return -1;
c4b1fcc0
FB
268 }
269 for(i = start; i < start + length; i += size) {
fc01f7e7 270 ioport_write_table[bsize][i] = func;
c4b1fcc0
FB
271 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
272 hw_error("register_ioport_read: invalid opaque");
273 ioport_opaque[i] = opaque;
274 }
f1510b2c
FB
275 return 0;
276}
277
69b91039
FB
278void isa_unassign_ioport(int start, int length)
279{
280 int i;
281
282 for(i = start; i < start + length; i++) {
283 ioport_read_table[0][i] = default_ioport_readb;
284 ioport_read_table[1][i] = default_ioport_readw;
285 ioport_read_table[2][i] = default_ioport_readl;
286
287 ioport_write_table[0][i] = default_ioport_writeb;
288 ioport_write_table[1][i] = default_ioport_writew;
289 ioport_write_table[2][i] = default_ioport_writel;
290 }
291}
292
20f32282
FB
293/***********************************************************/
294
0824d6fc
FB
295void pstrcpy(char *buf, int buf_size, const char *str)
296{
297 int c;
298 char *q = buf;
299
300 if (buf_size <= 0)
301 return;
302
303 for(;;) {
304 c = *str++;
305 if (c == 0 || q >= buf + buf_size - 1)
306 break;
307 *q++ = c;
308 }
309 *q = '\0';
310}
311
312/* strcat and truncate. */
313char *pstrcat(char *buf, int buf_size, const char *s)
314{
315 int len;
316 len = strlen(buf);
317 if (len < buf_size)
318 pstrcpy(buf + len, buf_size - len, s);
319 return buf;
320}
321
82c643ff
FB
322int strstart(const char *str, const char *val, const char **ptr)
323{
324 const char *p, *q;
325 p = str;
326 q = val;
327 while (*q != '\0') {
328 if (*p != *q)
329 return 0;
330 p++;
331 q++;
332 }
333 if (ptr)
334 *ptr = p;
335 return 1;
336}
337
c45886db 338void cpu_outb(CPUState *env, int addr, int val)
0824d6fc 339{
fd872598
FB
340#ifdef DEBUG_IOPORT
341 if (loglevel & CPU_LOG_IOPORT)
342 fprintf(logfile, "outb: %04x %02x\n", addr, val);
343#endif
c4b1fcc0 344 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
345#ifdef USE_KQEMU
346 if (env)
347 env->last_io_time = cpu_get_time_fast();
348#endif
0824d6fc
FB
349}
350
c45886db 351void cpu_outw(CPUState *env, int addr, int val)
0824d6fc 352{
fd872598
FB
353#ifdef DEBUG_IOPORT
354 if (loglevel & CPU_LOG_IOPORT)
355 fprintf(logfile, "outw: %04x %04x\n", addr, val);
356#endif
c4b1fcc0 357 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
358#ifdef USE_KQEMU
359 if (env)
360 env->last_io_time = cpu_get_time_fast();
361#endif
0824d6fc
FB
362}
363
c45886db 364void cpu_outl(CPUState *env, int addr, int val)
0824d6fc 365{
fd872598
FB
366#ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outl: %04x %08x\n", addr, val);
369#endif
c4b1fcc0 370 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
371#ifdef USE_KQEMU
372 if (env)
373 env->last_io_time = cpu_get_time_fast();
374#endif
0824d6fc
FB
375}
376
c45886db 377int cpu_inb(CPUState *env, int addr)
0824d6fc 378{
fd872598 379 int val;
fd872598
FB
380 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
381#ifdef DEBUG_IOPORT
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "inb : %04x %02x\n", addr, val);
89bfc105
FB
384#endif
385#ifdef USE_KQEMU
386 if (env)
387 env->last_io_time = cpu_get_time_fast();
fd872598
FB
388#endif
389 return val;
0824d6fc
FB
390}
391
c45886db 392int cpu_inw(CPUState *env, int addr)
0824d6fc 393{
fd872598 394 int val;
fd872598
FB
395 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
396#ifdef DEBUG_IOPORT
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "inw : %04x %04x\n", addr, val);
89bfc105
FB
399#endif
400#ifdef USE_KQEMU
401 if (env)
402 env->last_io_time = cpu_get_time_fast();
fd872598
FB
403#endif
404 return val;
0824d6fc
FB
405}
406
c45886db 407int cpu_inl(CPUState *env, int addr)
0824d6fc 408{
fd872598 409 int val;
fd872598
FB
410 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
411#ifdef DEBUG_IOPORT
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "inl : %04x %08x\n", addr, val);
89bfc105
FB
414#endif
415#ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
fd872598
FB
418#endif
419 return val;
0824d6fc
FB
420}
421
422/***********************************************************/
0824d6fc
FB
423void hw_error(const char *fmt, ...)
424{
425 va_list ap;
6a00d601 426 CPUState *env;
0824d6fc
FB
427
428 va_start(ap, fmt);
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
6a00d601
FB
432 for(env = first_cpu; env != NULL; env = env->next_cpu) {
433 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
0824d6fc 434#ifdef TARGET_I386
6a00d601 435 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
c45886db 436#else
6a00d601 437 cpu_dump_state(env, stderr, fprintf, 0);
0824d6fc 438#endif
6a00d601 439 }
0824d6fc
FB
440 va_end(ap);
441 abort();
442}
443
63066f4f
FB
444/***********************************************************/
445/* keyboard/mouse */
446
447static QEMUPutKBDEvent *qemu_put_kbd_event;
448static void *qemu_put_kbd_event_opaque;
449static QEMUPutMouseEvent *qemu_put_mouse_event;
450static void *qemu_put_mouse_event_opaque;
09b26c5e 451static int qemu_put_mouse_event_absolute;
63066f4f
FB
452
453void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454{
455 qemu_put_kbd_event_opaque = opaque;
456 qemu_put_kbd_event = func;
457}
458
09b26c5e 459void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
63066f4f
FB
460{
461 qemu_put_mouse_event_opaque = opaque;
462 qemu_put_mouse_event = func;
09b26c5e 463 qemu_put_mouse_event_absolute = absolute;
63066f4f
FB
464}
465
466void kbd_put_keycode(int keycode)
467{
468 if (qemu_put_kbd_event) {
469 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
470 }
471}
472
473void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
474{
475 if (qemu_put_mouse_event) {
476 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
477 dx, dy, dz, buttons_state);
478 }
479}
480
09b26c5e
FB
481int kbd_mouse_is_absolute(void)
482{
483 return qemu_put_mouse_event_absolute;
484}
485
8a7ddc38
FB
486/***********************************************************/
487/* timers */
488
34865134
FB
489#if defined(__powerpc__)
490
491static inline uint32_t get_tbl(void)
0824d6fc 492{
34865134
FB
493 uint32_t tbl;
494 asm volatile("mftb %0" : "=r" (tbl));
495 return tbl;
0824d6fc
FB
496}
497
34865134
FB
498static inline uint32_t get_tbu(void)
499{
500 uint32_t tbl;
501 asm volatile("mftbu %0" : "=r" (tbl));
502 return tbl;
503}
504
505int64_t cpu_get_real_ticks(void)
506{
507 uint32_t l, h, h1;
508 /* NOTE: we test if wrapping has occurred */
509 do {
510 h = get_tbu();
511 l = get_tbl();
512 h1 = get_tbu();
513 } while (h != h1);
514 return ((int64_t)h << 32) | l;
515}
516
517#elif defined(__i386__)
518
519int64_t cpu_get_real_ticks(void)
0824d6fc
FB
520{
521 int64_t val;
e463b581 522 asm volatile ("rdtsc" : "=A" (val));
0824d6fc
FB
523 return val;
524}
525
1115dde7
FB
526#elif defined(__x86_64__)
527
528int64_t cpu_get_real_ticks(void)
529{
530 uint32_t low,high;
531 int64_t val;
532 asm volatile("rdtsc" : "=a" (low), "=d" (high));
533 val = high;
534 val <<= 32;
535 val |= low;
536 return val;
537}
538
b8076a74
FB
539#elif defined(__ia64)
540
541int64_t cpu_get_real_ticks(void)
542{
543 int64_t val;
544 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
545 return val;
546}
547
90cb9493
FB
548#elif defined(__s390__)
549
550int64_t cpu_get_real_ticks(void)
551{
552 int64_t val;
553 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
554 return val;
555}
556
34865134
FB
557#else
558#error unsupported CPU
559#endif
560
eade0f19 561static int64_t cpu_ticks_prev;
34865134 562static int64_t cpu_ticks_offset;
8a7ddc38 563static int cpu_ticks_enabled;
34865134 564
8a7ddc38 565static inline int64_t cpu_get_ticks(void)
34865134 566{
8a7ddc38
FB
567 if (!cpu_ticks_enabled) {
568 return cpu_ticks_offset;
569 } else {
eade0f19
FB
570 int64_t ticks;
571 ticks = cpu_get_real_ticks();
572 if (cpu_ticks_prev > ticks) {
573 /* Note: non increasing ticks may happen if the host uses
574 software suspend */
575 cpu_ticks_offset += cpu_ticks_prev - ticks;
576 }
577 cpu_ticks_prev = ticks;
578 return ticks + cpu_ticks_offset;
8a7ddc38 579 }
34865134
FB
580}
581
582/* enable cpu_get_ticks() */
583void cpu_enable_ticks(void)
584{
8a7ddc38
FB
585 if (!cpu_ticks_enabled) {
586 cpu_ticks_offset -= cpu_get_real_ticks();
587 cpu_ticks_enabled = 1;
588 }
34865134
FB
589}
590
591/* disable cpu_get_ticks() : the clock is stopped. You must not call
592 cpu_get_ticks() after that. */
593void cpu_disable_ticks(void)
594{
8a7ddc38
FB
595 if (cpu_ticks_enabled) {
596 cpu_ticks_offset = cpu_get_ticks();
597 cpu_ticks_enabled = 0;
598 }
34865134
FB
599}
600
67b915a5 601static int64_t get_clock(void)
34865134 602{
67b915a5
FB
603#ifdef _WIN32
604 struct _timeb tb;
605 _ftime(&tb);
606 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
607#else
34865134
FB
608 struct timeval tv;
609 gettimeofday(&tv, NULL);
610 return tv.tv_sec * 1000000LL + tv.tv_usec;
67b915a5 611#endif
34865134
FB
612}
613
0824d6fc
FB
614void cpu_calibrate_ticks(void)
615{
616 int64_t usec, ticks;
617
618 usec = get_clock();
8a7ddc38 619 ticks = cpu_get_real_ticks();
67b915a5
FB
620#ifdef _WIN32
621 Sleep(50);
622#else
0824d6fc 623 usleep(50 * 1000);
67b915a5 624#endif
0824d6fc 625 usec = get_clock() - usec;
8a7ddc38 626 ticks = cpu_get_real_ticks() - ticks;
0824d6fc
FB
627 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
628}
629
87858c89 630/* compute with 96 bit intermediate result: (a*b)/c */
80cabfad 631uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
87858c89
FB
632{
633 union {
634 uint64_t ll;
635 struct {
636#ifdef WORDS_BIGENDIAN
637 uint32_t high, low;
638#else
639 uint32_t low, high;
640#endif
641 } l;
642 } u, res;
643 uint64_t rl, rh;
644
645 u.ll = a;
646 rl = (uint64_t)u.l.low * (uint64_t)b;
647 rh = (uint64_t)u.l.high * (uint64_t)b;
648 rh += (rl >> 32);
649 res.l.high = rh / c;
650 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
651 return res.ll;
652}
653
8a7ddc38
FB
654#define QEMU_TIMER_REALTIME 0
655#define QEMU_TIMER_VIRTUAL 1
656
657struct QEMUClock {
658 int type;
659 /* XXX: add frequency */
660};
661
662struct QEMUTimer {
663 QEMUClock *clock;
664 int64_t expire_time;
665 QEMUTimerCB *cb;
666 void *opaque;
667 struct QEMUTimer *next;
668};
669
670QEMUClock *rt_clock;
671QEMUClock *vm_clock;
672
673static QEMUTimer *active_timers[2];
40c3bac3
FB
674#ifdef _WIN32
675static MMRESULT timerID;
676#else
8a7ddc38
FB
677/* frequency of the times() clock tick */
678static int timer_freq;
67b915a5 679#endif
8a7ddc38
FB
680
681QEMUClock *qemu_new_clock(int type)
682{
683 QEMUClock *clock;
684 clock = qemu_mallocz(sizeof(QEMUClock));
685 if (!clock)
686 return NULL;
687 clock->type = type;
688 return clock;
689}
690
691QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
692{
693 QEMUTimer *ts;
694
695 ts = qemu_mallocz(sizeof(QEMUTimer));
696 ts->clock = clock;
697 ts->cb = cb;
698 ts->opaque = opaque;
699 return ts;
700}
701
702void qemu_free_timer(QEMUTimer *ts)
703{
704 qemu_free(ts);
705}
706
707/* stop a timer, but do not dealloc it */
708void qemu_del_timer(QEMUTimer *ts)
709{
710 QEMUTimer **pt, *t;
711
712 /* NOTE: this code must be signal safe because
713 qemu_timer_expired() can be called from a signal. */
714 pt = &active_timers[ts->clock->type];
715 for(;;) {
716 t = *pt;
717 if (!t)
718 break;
719 if (t == ts) {
720 *pt = t->next;
721 break;
722 }
723 pt = &t->next;
724 }
725}
726
727/* modify the current timer so that it will be fired when current_time
728 >= expire_time. The corresponding callback will be called. */
729void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
730{
731 QEMUTimer **pt, *t;
732
733 qemu_del_timer(ts);
734
735 /* add the timer in the sorted list */
736 /* NOTE: this code must be signal safe because
737 qemu_timer_expired() can be called from a signal. */
738 pt = &active_timers[ts->clock->type];
739 for(;;) {
740 t = *pt;
741 if (!t)
742 break;
743 if (t->expire_time > expire_time)
744 break;
745 pt = &t->next;
746 }
747 ts->expire_time = expire_time;
748 ts->next = *pt;
749 *pt = ts;
750}
751
752int qemu_timer_pending(QEMUTimer *ts)
753{
754 QEMUTimer *t;
755 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
756 if (t == ts)
757 return 1;
758 }
759 return 0;
760}
761
762static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
763{
764 if (!timer_head)
765 return 0;
766 return (timer_head->expire_time <= current_time);
767}
768
769static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
770{
771 QEMUTimer *ts;
772
773 for(;;) {
774 ts = *ptimer_head;
e95c8d51 775 if (!ts || ts->expire_time > current_time)
8a7ddc38
FB
776 break;
777 /* remove timer from the list before calling the callback */
778 *ptimer_head = ts->next;
779 ts->next = NULL;
780
781 /* run the callback (the timer list can be modified) */
782 ts->cb(ts->opaque);
783 }
784}
785
786int64_t qemu_get_clock(QEMUClock *clock)
787{
788 switch(clock->type) {
789 case QEMU_TIMER_REALTIME:
67b915a5
FB
790#ifdef _WIN32
791 return GetTickCount();
792#else
7d3505c5
FB
793 {
794 struct tms tp;
795
796 /* Note that using gettimeofday() is not a good solution
797 for timers because its value change when the date is
798 modified. */
799 if (timer_freq == 100) {
800 return times(&tp) * 10;
801 } else {
802 return ((int64_t)times(&tp) * 1000) / timer_freq;
803 }
8a7ddc38 804 }
67b915a5 805#endif
8a7ddc38
FB
806 default:
807 case QEMU_TIMER_VIRTUAL:
808 return cpu_get_ticks();
809 }
810}
811
812/* save a timer */
813void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
814{
815 uint64_t expire_time;
816
817 if (qemu_timer_pending(ts)) {
818 expire_time = ts->expire_time;
819 } else {
820 expire_time = -1;
821 }
822 qemu_put_be64(f, expire_time);
823}
824
825void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
826{
827 uint64_t expire_time;
828
829 expire_time = qemu_get_be64(f);
830 if (expire_time != -1) {
831 qemu_mod_timer(ts, expire_time);
832 } else {
833 qemu_del_timer(ts);
834 }
835}
836
837static void timer_save(QEMUFile *f, void *opaque)
838{
839 if (cpu_ticks_enabled) {
840 hw_error("cannot save state if virtual timers are running");
841 }
842 qemu_put_be64s(f, &cpu_ticks_offset);
843 qemu_put_be64s(f, &ticks_per_sec);
844}
845
846static int timer_load(QEMUFile *f, void *opaque, int version_id)
847{
848 if (version_id != 1)
849 return -EINVAL;
850 if (cpu_ticks_enabled) {
851 return -EINVAL;
852 }
853 qemu_get_be64s(f, &cpu_ticks_offset);
854 qemu_get_be64s(f, &ticks_per_sec);
855 return 0;
856}
857
67b915a5
FB
858#ifdef _WIN32
859void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
860 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
861#else
8a7ddc38 862static void host_alarm_handler(int host_signum)
67b915a5 863#endif
8a7ddc38 864{
02ba45c5
FB
865#if 0
866#define DISP_FREQ 1000
867 {
868 static int64_t delta_min = INT64_MAX;
869 static int64_t delta_max, delta_cum, last_clock, delta, ti;
870 static int count;
871 ti = qemu_get_clock(vm_clock);
872 if (last_clock != 0) {
873 delta = ti - last_clock;
874 if (delta < delta_min)
875 delta_min = delta;
876 if (delta > delta_max)
877 delta_max = delta;
878 delta_cum += delta;
879 if (++count == DISP_FREQ) {
880 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
881 muldiv64(delta_min, 1000000, ticks_per_sec),
882 muldiv64(delta_max, 1000000, ticks_per_sec),
883 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
884 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
885 count = 0;
886 delta_min = INT64_MAX;
887 delta_max = 0;
888 delta_cum = 0;
889 }
890 }
891 last_clock = ti;
892 }
893#endif
8a7ddc38
FB
894 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
895 qemu_get_clock(vm_clock)) ||
896 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
897 qemu_get_clock(rt_clock))) {
6a00d601
FB
898 CPUState *env = cpu_single_env;
899 if (env) {
900 /* stop the currently executing cpu because a timer occured */
901 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
a332e112 902#ifdef USE_KQEMU
6a00d601
FB
903 if (env->kqemu_enabled) {
904 kqemu_cpu_interrupt(env);
905 }
a332e112 906#endif
6a00d601 907 }
8a7ddc38
FB
908 }
909}
910
fd872598
FB
911#ifndef _WIN32
912
829309c7
FB
913#if defined(__linux__)
914
fd872598
FB
915#define RTC_FREQ 1024
916
917static int rtc_fd;
829309c7 918
fd872598
FB
919static int start_rtc_timer(void)
920{
921 rtc_fd = open("/dev/rtc", O_RDONLY);
922 if (rtc_fd < 0)
923 return -1;
924 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
925 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
926 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
927 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
928 goto fail;
929 }
930 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
931 fail:
932 close(rtc_fd);
933 return -1;
934 }
935 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
936 return 0;
937}
938
829309c7
FB
939#else
940
941static int start_rtc_timer(void)
942{
943 return -1;
944}
945
946#endif /* !defined(__linux__) */
947
948#endif /* !defined(_WIN32) */
fd872598 949
8a7ddc38
FB
950static void init_timers(void)
951{
8a7ddc38
FB
952 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
953 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
954
67b915a5
FB
955#ifdef _WIN32
956 {
957 int count=0;
1d14ffa9 958 timerID = timeSetEvent(1, // interval (ms)
40c3bac3
FB
959 0, // resolution
960 host_alarm_handler, // function
961 (DWORD)&count, // user parameter
962 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
67b915a5
FB
963 if( !timerID ) {
964 perror("failed timer alarm");
965 exit(1);
966 }
967 }
968 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
969#else
970 {
971 struct sigaction act;
972 struct itimerval itv;
973
974 /* get times() syscall frequency */
975 timer_freq = sysconf(_SC_CLK_TCK);
976
977 /* timer signal */
978 sigfillset(&act.sa_mask);
a09db21f 979 act.sa_flags = 0;
8a7ddc38 980#if defined (TARGET_I386) && defined(USE_CODE_COPY)
67b915a5
FB
981 act.sa_flags |= SA_ONSTACK;
982#endif
983 act.sa_handler = host_alarm_handler;
984 sigaction(SIGALRM, &act, NULL);
fd872598 985
67b915a5 986 itv.it_interval.tv_sec = 0;
d79284e0 987 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
67b915a5
FB
988 itv.it_value.tv_sec = 0;
989 itv.it_value.tv_usec = 10 * 1000;
990 setitimer(ITIMER_REAL, &itv, NULL);
991 /* we probe the tick duration of the kernel to inform the user if
992 the emulated kernel requested a too high timer frequency */
993 getitimer(ITIMER_REAL, &itv);
fd872598 994
83fb7adf 995#if defined(__linux__)
fd872598
FB
996 if (itv.it_interval.tv_usec > 1000) {
997 /* try to use /dev/rtc to have a faster timer */
998 if (start_rtc_timer() < 0)
999 goto use_itimer;
1000 /* disable itimer */
1001 itv.it_interval.tv_sec = 0;
1002 itv.it_interval.tv_usec = 0;
1003 itv.it_value.tv_sec = 0;
1004 itv.it_value.tv_usec = 0;
1005 setitimer(ITIMER_REAL, &itv, NULL);
1006
1007 /* use the RTC */
a1968d71 1008 sigaction(SIGIO, &act, NULL);
fd872598
FB
1009 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1010 fcntl(rtc_fd, F_SETOWN, getpid());
83fb7adf
FB
1011 } else
1012#endif /* defined(__linux__) */
1013 {
fd872598
FB
1014 use_itimer:
1015 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1016 PIT_FREQ) / 1000000;
1017 }
67b915a5 1018 }
8a7ddc38 1019#endif
8a7ddc38
FB
1020}
1021
40c3bac3
FB
1022void quit_timers(void)
1023{
1024#ifdef _WIN32
1025 timeKillEvent(timerID);
1026#endif
1027}
1028
c4b1fcc0 1029/***********************************************************/
82c643ff 1030/* character device */
313aa567 1031
82c643ff
FB
1032int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1033{
1034 return s->chr_write(s, buf, len);
1035}
67b915a5 1036
e57a8c0e 1037int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
f8d179e3 1038{
e57a8c0e
FB
1039 if (!s->chr_ioctl)
1040 return -ENOTSUP;
1041 return s->chr_ioctl(s, cmd, arg);
f8d179e3
FB
1042}
1043
82c643ff 1044void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
67b915a5 1045{
82c643ff
FB
1046 char buf[4096];
1047 va_list ap;
1048 va_start(ap, fmt);
1049 vsnprintf(buf, sizeof(buf), fmt, ap);
1050 qemu_chr_write(s, buf, strlen(buf));
1051 va_end(ap);
67b915a5
FB
1052}
1053
5905b2e5
FB
1054void qemu_chr_send_event(CharDriverState *s, int event)
1055{
1056 if (s->chr_send_event)
1057 s->chr_send_event(s, event);
1058}
1059
82c643ff
FB
1060void qemu_chr_add_read_handler(CharDriverState *s,
1061 IOCanRWHandler *fd_can_read,
1062 IOReadHandler *fd_read, void *opaque)
1063{
1064 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1065}
1066
1067void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1068{
1069 s->chr_event = chr_event;
1070}
67b915a5 1071
82c643ff 1072static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
313aa567 1073{
82c643ff
FB
1074 return len;
1075}
1076
1077static void null_chr_add_read_handler(CharDriverState *chr,
1078 IOCanRWHandler *fd_can_read,
1079 IOReadHandler *fd_read, void *opaque)
1080{
1081}
1082
1083CharDriverState *qemu_chr_open_null(void)
1084{
1085 CharDriverState *chr;
1086
1087 chr = qemu_mallocz(sizeof(CharDriverState));
1088 if (!chr)
1089 return NULL;
1090 chr->chr_write = null_chr_write;
1091 chr->chr_add_read_handler = null_chr_add_read_handler;
1092 return chr;
1093}
1094
fd1dff4b 1095#ifdef _WIN32
82c643ff 1096
fd1dff4b
FB
1097static void socket_cleanup(void)
1098{
1099 WSACleanup();
1100}
82c643ff 1101
fd1dff4b
FB
1102static int socket_init(void)
1103{
1104 WSADATA Data;
1105 int ret, err;
1106
1107 ret = WSAStartup(MAKEWORD(2,2), &Data);
1108 if (ret != 0) {
1109 err = WSAGetLastError();
1110 fprintf(stderr, "WSAStartup: %d\n", err);
1111 return -1;
1112 }
1113 atexit(socket_cleanup);
1114 return 0;
1115}
1116
1117static int send_all(int fd, const uint8_t *buf, int len1)
1118{
1119 int ret, len;
1120
1121 len = len1;
1122 while (len > 0) {
1123 ret = send(fd, buf, len, 0);
1124 if (ret < 0) {
1125 int errno;
1126 errno = WSAGetLastError();
1127 if (errno != WSAEWOULDBLOCK) {
1128 return -1;
1129 }
1130 } else if (ret == 0) {
1131 break;
1132 } else {
1133 buf += ret;
1134 len -= ret;
1135 }
1136 }
1137 return len1 - len;
1138}
1139
1140void socket_set_nonblock(int fd)
1141{
1142 unsigned long opt = 1;
1143 ioctlsocket(fd, FIONBIO, &opt);
1144}
1145
1146#else
1147
1d96905d
FB
1148static int unix_write(int fd, const uint8_t *buf, int len1)
1149{
1150 int ret, len;
1151
1152 len = len1;
1153 while (len > 0) {
1154 ret = write(fd, buf, len);
1155 if (ret < 0) {
1156 if (errno != EINTR && errno != EAGAIN)
1157 return -1;
1158 } else if (ret == 0) {
1159 break;
1160 } else {
1161 buf += ret;
1162 len -= ret;
1163 }
1164 }
1165 return len1 - len;
1166}
1167
fd1dff4b
FB
1168static inline int send_all(int fd, const uint8_t *buf, int len1)
1169{
1170 return unix_write(fd, buf, len1);
1171}
1172
1173void socket_set_nonblock(int fd)
1174{
1175 fcntl(fd, F_SETFL, O_NONBLOCK);
1176}
1177#endif /* !_WIN32 */
1178
1179#ifndef _WIN32
1180
1181typedef struct {
1182 int fd_in, fd_out;
1183 IOCanRWHandler *fd_can_read;
1184 IOReadHandler *fd_read;
1185 void *fd_opaque;
1186 int max_size;
1187} FDCharDriver;
1188
1189#define STDIO_MAX_CLIENTS 2
1190
1191static int stdio_nb_clients;
1192static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1193
82c643ff
FB
1194static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1195{
1196 FDCharDriver *s = chr->opaque;
1d96905d 1197 return unix_write(s->fd_out, buf, len);
82c643ff
FB
1198}
1199
7c9d8e07
FB
1200static int fd_chr_read_poll(void *opaque)
1201{
1202 CharDriverState *chr = opaque;
1203 FDCharDriver *s = chr->opaque;
1204
1205 s->max_size = s->fd_can_read(s->fd_opaque);
1206 return s->max_size;
1207}
1208
1209static void fd_chr_read(void *opaque)
1210{
1211 CharDriverState *chr = opaque;
1212 FDCharDriver *s = chr->opaque;
1213 int size, len;
1214 uint8_t buf[1024];
1215
1216 len = sizeof(buf);
1217 if (len > s->max_size)
1218 len = s->max_size;
1219 if (len == 0)
1220 return;
1221 size = read(s->fd_in, buf, len);
1222 if (size > 0) {
1223 s->fd_read(s->fd_opaque, buf, size);
1224 }
1225}
1226
82c643ff
FB
1227static void fd_chr_add_read_handler(CharDriverState *chr,
1228 IOCanRWHandler *fd_can_read,
1229 IOReadHandler *fd_read, void *opaque)
1230{
1231 FDCharDriver *s = chr->opaque;
1232
f8d179e3 1233 if (s->fd_in >= 0) {
7c9d8e07
FB
1234 s->fd_can_read = fd_can_read;
1235 s->fd_read = fd_read;
1236 s->fd_opaque = opaque;
f8d179e3 1237 if (nographic && s->fd_in == 0) {
f8d179e3 1238 } else {
7c9d8e07
FB
1239 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1240 fd_chr_read, NULL, chr);
f8d179e3 1241 }
82c643ff
FB
1242 }
1243}
1244
1245/* open a character device to a unix fd */
1246CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1247{
1248 CharDriverState *chr;
1249 FDCharDriver *s;
1250
1251 chr = qemu_mallocz(sizeof(CharDriverState));
1252 if (!chr)
1253 return NULL;
1254 s = qemu_mallocz(sizeof(FDCharDriver));
1255 if (!s) {
1256 free(chr);
1257 return NULL;
1258 }
1259 s->fd_in = fd_in;
1260 s->fd_out = fd_out;
1261 chr->opaque = s;
1262 chr->chr_write = fd_chr_write;
1263 chr->chr_add_read_handler = fd_chr_add_read_handler;
1264 return chr;
1265}
1266
f8d179e3
FB
1267CharDriverState *qemu_chr_open_file_out(const char *file_out)
1268{
1269 int fd_out;
1270
89ba1a73 1271 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
f8d179e3
FB
1272 if (fd_out < 0)
1273 return NULL;
1274 return qemu_chr_open_fd(-1, fd_out);
1275}
1276
1277CharDriverState *qemu_chr_open_pipe(const char *filename)
1278{
1279 int fd;
1280
1281 fd = open(filename, O_RDWR | O_BINARY);
1282 if (fd < 0)
1283 return NULL;
1284 return qemu_chr_open_fd(fd, fd);
1285}
1286
1287
82c643ff
FB
1288/* for STDIO, we handle the case where several clients use it
1289 (nographic mode) */
1290
1291#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1292
aa0bc6b6
FB
1293#define TERM_FIFO_MAX_SIZE 1
1294
82c643ff 1295static int term_got_escape, client_index;
aa0bc6b6
FB
1296static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1297int term_fifo_size;
82c643ff
FB
1298
1299void term_print_help(void)
1300{
1301 printf("\n"
1302 "C-a h print this help\n"
1303 "C-a x exit emulator\n"
1304 "C-a s save disk data back to file (if -snapshot)\n"
1305 "C-a b send break (magic sysrq)\n"
1306 "C-a c switch between console and monitor\n"
1307 "C-a C-a send C-a\n"
1308 );
1309}
1310
1311/* called when a char is received */
1312static void stdio_received_byte(int ch)
1313{
1314 if (term_got_escape) {
1315 term_got_escape = 0;
1316 switch(ch) {
1317 case 'h':
1318 term_print_help();
1319 break;
1320 case 'x':
1321 exit(0);
1322 break;
1323 case 's':
1324 {
1325 int i;
1326 for (i = 0; i < MAX_DISKS; i++) {
1327 if (bs_table[i])
1328 bdrv_commit(bs_table[i]);
1329 }
1330 }
1331 break;
1332 case 'b':
1333 if (client_index < stdio_nb_clients) {
1334 CharDriverState *chr;
1335 FDCharDriver *s;
1336
1337 chr = stdio_clients[client_index];
1338 s = chr->opaque;
1339 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1340 }
1341 break;
1342 case 'c':
1343 client_index++;
1344 if (client_index >= stdio_nb_clients)
1345 client_index = 0;
1346 if (client_index == 0) {
1347 /* send a new line in the monitor to get the prompt */
1348 ch = '\r';
1349 goto send_char;
1350 }
1351 break;
1352 case TERM_ESCAPE:
1353 goto send_char;
1354 }
1355 } else if (ch == TERM_ESCAPE) {
1356 term_got_escape = 1;
1357 } else {
1358 send_char:
1359 if (client_index < stdio_nb_clients) {
1360 uint8_t buf[1];
1361 CharDriverState *chr;
1362 FDCharDriver *s;
1363
1364 chr = stdio_clients[client_index];
1365 s = chr->opaque;
aa0bc6b6
FB
1366 if (s->fd_can_read(s->fd_opaque) > 0) {
1367 buf[0] = ch;
82c643ff 1368 s->fd_read(s->fd_opaque, buf, 1);
aa0bc6b6
FB
1369 } else if (term_fifo_size == 0) {
1370 term_fifo[term_fifo_size++] = ch;
1371 }
c4b1fcc0 1372 }
330d0414 1373 }
330d0414
FB
1374}
1375
7c9d8e07 1376static int stdio_read_poll(void *opaque)
82c643ff 1377{
aa0bc6b6
FB
1378 CharDriverState *chr;
1379 FDCharDriver *s;
1380
1381 if (client_index < stdio_nb_clients) {
1382 chr = stdio_clients[client_index];
1383 s = chr->opaque;
1384 /* try to flush the queue if needed */
1385 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1386 s->fd_read(s->fd_opaque, term_fifo, 1);
1387 term_fifo_size = 0;
1388 }
1389 /* see if we can absorb more chars */
1390 if (term_fifo_size == 0)
1391 return 1;
1392 else
1393 return 0;
1394 } else {
1395 return 1;
1396 }
82c643ff
FB
1397}
1398
7c9d8e07 1399static void stdio_read(void *opaque)
82c643ff 1400{
7c9d8e07
FB
1401 int size;
1402 uint8_t buf[1];
1403
1404 size = read(0, buf, 1);
1405 if (size > 0)
1406 stdio_received_byte(buf[0]);
82c643ff
FB
1407}
1408
8d11df9e
FB
1409/* init terminal so that we can grab keys */
1410static struct termios oldtty;
1411static int old_fd0_flags;
1412
1413static void term_exit(void)
1414{
1415 tcsetattr (0, TCSANOW, &oldtty);
1416 fcntl(0, F_SETFL, old_fd0_flags);
1417}
1418
1419static void term_init(void)
1420{
1421 struct termios tty;
1422
1423 tcgetattr (0, &tty);
1424 oldtty = tty;
1425 old_fd0_flags = fcntl(0, F_GETFL);
1426
1427 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1428 |INLCR|IGNCR|ICRNL|IXON);
1429 tty.c_oflag |= OPOST;
1430 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1431 /* if graphical mode, we allow Ctrl-C handling */
1432 if (nographic)
1433 tty.c_lflag &= ~ISIG;
1434 tty.c_cflag &= ~(CSIZE|PARENB);
1435 tty.c_cflag |= CS8;
1436 tty.c_cc[VMIN] = 1;
1437 tty.c_cc[VTIME] = 0;
1438
1439 tcsetattr (0, TCSANOW, &tty);
1440
1441 atexit(term_exit);
1442
1443 fcntl(0, F_SETFL, O_NONBLOCK);
1444}
1445
82c643ff
FB
1446CharDriverState *qemu_chr_open_stdio(void)
1447{
1448 CharDriverState *chr;
1449
1450 if (nographic) {
1451 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1452 return NULL;
1453 chr = qemu_chr_open_fd(0, 1);
1454 if (stdio_nb_clients == 0)
7c9d8e07 1455 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
82c643ff
FB
1456 client_index = stdio_nb_clients;
1457 } else {
1458 if (stdio_nb_clients != 0)
1459 return NULL;
1460 chr = qemu_chr_open_fd(0, 1);
1461 }
1462 stdio_clients[stdio_nb_clients++] = chr;
8d11df9e
FB
1463 if (stdio_nb_clients == 1) {
1464 /* set the terminal in raw mode */
1465 term_init();
1466 }
82c643ff
FB
1467 return chr;
1468}
1469
1470#if defined(__linux__)
1471CharDriverState *qemu_chr_open_pty(void)
1472{
91fc2119 1473 struct termios tty;
82c643ff
FB
1474 char slave_name[1024];
1475 int master_fd, slave_fd;
1476
1477 /* Not satisfying */
1478 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1479 return NULL;
1480 }
91fc2119
FB
1481
1482 /* Disabling local echo and line-buffered output */
1483 tcgetattr (master_fd, &tty);
1484 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1485 tty.c_cc[VMIN] = 1;
1486 tty.c_cc[VTIME] = 0;
1487 tcsetattr (master_fd, TCSAFLUSH, &tty);
1488
82c643ff
FB
1489 fprintf(stderr, "char device redirected to %s\n", slave_name);
1490 return qemu_chr_open_fd(master_fd, master_fd);
1491}
f8d179e3
FB
1492
1493static void tty_serial_init(int fd, int speed,
1494 int parity, int data_bits, int stop_bits)
1495{
1496 struct termios tty;
1497 speed_t spd;
1498
e57a8c0e
FB
1499#if 0
1500 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1501 speed, parity, data_bits, stop_bits);
1502#endif
1503 tcgetattr (fd, &tty);
f8d179e3
FB
1504
1505 switch(speed) {
1506 case 50:
1507 spd = B50;
1508 break;
1509 case 75:
1510 spd = B75;
1511 break;
1512 case 300:
1513 spd = B300;
1514 break;
1515 case 600:
1516 spd = B600;
1517 break;
1518 case 1200:
1519 spd = B1200;
1520 break;
1521 case 2400:
1522 spd = B2400;
1523 break;
1524 case 4800:
1525 spd = B4800;
1526 break;
1527 case 9600:
1528 spd = B9600;
1529 break;
1530 case 19200:
1531 spd = B19200;
1532 break;
1533 case 38400:
1534 spd = B38400;
1535 break;
1536 case 57600:
1537 spd = B57600;
1538 break;
1539 default:
1540 case 115200:
1541 spd = B115200;
1542 break;
1543 }
1544
1545 cfsetispeed(&tty, spd);
1546 cfsetospeed(&tty, spd);
1547
1548 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1549 |INLCR|IGNCR|ICRNL|IXON);
1550 tty.c_oflag |= OPOST;
1551 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1552 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1553 switch(data_bits) {
1554 default:
1555 case 8:
1556 tty.c_cflag |= CS8;
1557 break;
1558 case 7:
1559 tty.c_cflag |= CS7;
1560 break;
1561 case 6:
1562 tty.c_cflag |= CS6;
1563 break;
1564 case 5:
1565 tty.c_cflag |= CS5;
1566 break;
1567 }
1568 switch(parity) {
1569 default:
1570 case 'N':
1571 break;
1572 case 'E':
1573 tty.c_cflag |= PARENB;
1574 break;
1575 case 'O':
1576 tty.c_cflag |= PARENB | PARODD;
1577 break;
1578 }
1579
1580 tcsetattr (fd, TCSANOW, &tty);
1581}
1582
e57a8c0e 1583static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
f8d179e3
FB
1584{
1585 FDCharDriver *s = chr->opaque;
e57a8c0e
FB
1586
1587 switch(cmd) {
1588 case CHR_IOCTL_SERIAL_SET_PARAMS:
1589 {
1590 QEMUSerialSetParams *ssp = arg;
1591 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1592 ssp->data_bits, ssp->stop_bits);
1593 }
1594 break;
1595 case CHR_IOCTL_SERIAL_SET_BREAK:
1596 {
1597 int enable = *(int *)arg;
1598 if (enable)
1599 tcsendbreak(s->fd_in, 1);
1600 }
1601 break;
1602 default:
1603 return -ENOTSUP;
1604 }
1605 return 0;
f8d179e3
FB
1606}
1607
1608CharDriverState *qemu_chr_open_tty(const char *filename)
1609{
1610 CharDriverState *chr;
1611 int fd;
1612
e57a8c0e 1613 fd = open(filename, O_RDWR | O_NONBLOCK);
f8d179e3
FB
1614 if (fd < 0)
1615 return NULL;
1616 fcntl(fd, F_SETFL, O_NONBLOCK);
1617 tty_serial_init(fd, 115200, 'N', 8, 1);
1618 chr = qemu_chr_open_fd(fd, fd);
1619 if (!chr)
1620 return NULL;
e57a8c0e
FB
1621 chr->chr_ioctl = tty_serial_ioctl;
1622 return chr;
1623}
1624
1625static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1626{
1627 int fd = (int)chr->opaque;
1628 uint8_t b;
1629
1630 switch(cmd) {
1631 case CHR_IOCTL_PP_READ_DATA:
1632 if (ioctl(fd, PPRDATA, &b) < 0)
1633 return -ENOTSUP;
1634 *(uint8_t *)arg = b;
1635 break;
1636 case CHR_IOCTL_PP_WRITE_DATA:
1637 b = *(uint8_t *)arg;
1638 if (ioctl(fd, PPWDATA, &b) < 0)
1639 return -ENOTSUP;
1640 break;
1641 case CHR_IOCTL_PP_READ_CONTROL:
1642 if (ioctl(fd, PPRCONTROL, &b) < 0)
1643 return -ENOTSUP;
1644 *(uint8_t *)arg = b;
1645 break;
1646 case CHR_IOCTL_PP_WRITE_CONTROL:
1647 b = *(uint8_t *)arg;
1648 if (ioctl(fd, PPWCONTROL, &b) < 0)
1649 return -ENOTSUP;
1650 break;
1651 case CHR_IOCTL_PP_READ_STATUS:
1652 if (ioctl(fd, PPRSTATUS, &b) < 0)
1653 return -ENOTSUP;
1654 *(uint8_t *)arg = b;
1655 break;
1656 default:
1657 return -ENOTSUP;
1658 }
1659 return 0;
1660}
1661
1662CharDriverState *qemu_chr_open_pp(const char *filename)
1663{
1664 CharDriverState *chr;
1665 int fd;
1666
1667 fd = open(filename, O_RDWR);
1668 if (fd < 0)
1669 return NULL;
1670
1671 if (ioctl(fd, PPCLAIM) < 0) {
1672 close(fd);
1673 return NULL;
1674 }
1675
1676 chr = qemu_mallocz(sizeof(CharDriverState));
1677 if (!chr) {
1678 close(fd);
1679 return NULL;
1680 }
1681 chr->opaque = (void *)fd;
1682 chr->chr_write = null_chr_write;
1683 chr->chr_add_read_handler = null_chr_add_read_handler;
1684 chr->chr_ioctl = pp_ioctl;
f8d179e3
FB
1685 return chr;
1686}
1687
82c643ff
FB
1688#else
1689CharDriverState *qemu_chr_open_pty(void)
1690{
1691 return NULL;
1692}
67b915a5
FB
1693#endif
1694
82c643ff
FB
1695#endif /* !defined(_WIN32) */
1696
f331110f
FB
1697#ifdef _WIN32
1698typedef struct {
1699 IOCanRWHandler *fd_can_read;
1700 IOReadHandler *fd_read;
1701 void *win_opaque;
1702 int max_size;
1703 HANDLE hcom, hrecv, hsend;
1704 OVERLAPPED orecv, osend;
1705 BOOL fpipe;
1706 DWORD len;
1707} WinCharState;
1708
1709#define NSENDBUF 2048
1710#define NRECVBUF 2048
1711#define MAXCONNECT 1
1712#define NTIMEOUT 5000
1713
1714static int win_chr_poll(void *opaque);
1715static int win_chr_pipe_poll(void *opaque);
1716
1717static void win_chr_close2(WinCharState *s)
1718{
1719 if (s->hsend) {
1720 CloseHandle(s->hsend);
1721 s->hsend = NULL;
1722 }
1723 if (s->hrecv) {
1724 CloseHandle(s->hrecv);
1725 s->hrecv = NULL;
1726 }
1727 if (s->hcom) {
1728 CloseHandle(s->hcom);
1729 s->hcom = NULL;
1730 }
1731 if (s->fpipe)
1732 qemu_del_polling_cb(win_chr_pipe_poll, s);
1733 else
1734 qemu_del_polling_cb(win_chr_poll, s);
1735}
1736
1737static void win_chr_close(CharDriverState *chr)
1738{
1739 WinCharState *s = chr->opaque;
1740 win_chr_close2(s);
1741}
1742
1743static int win_chr_init(WinCharState *s, const char *filename)
1744{
1745 COMMCONFIG comcfg;
1746 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1747 COMSTAT comstat;
1748 DWORD size;
1749 DWORD err;
1750
1751 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1752 if (!s->hsend) {
1753 fprintf(stderr, "Failed CreateEvent\n");
1754 goto fail;
1755 }
1756 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1757 if (!s->hrecv) {
1758 fprintf(stderr, "Failed CreateEvent\n");
1759 goto fail;
1760 }
1761
1762 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1763 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1764 if (s->hcom == INVALID_HANDLE_VALUE) {
1765 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1766 s->hcom = NULL;
1767 goto fail;
1768 }
1769
1770 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1771 fprintf(stderr, "Failed SetupComm\n");
1772 goto fail;
1773 }
1774
1775 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1776 size = sizeof(COMMCONFIG);
1777 GetDefaultCommConfig(filename, &comcfg, &size);
1778 comcfg.dcb.DCBlength = sizeof(DCB);
1779 CommConfigDialog(filename, NULL, &comcfg);
1780
1781 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1782 fprintf(stderr, "Failed SetCommState\n");
1783 goto fail;
1784 }
1785
1786 if (!SetCommMask(s->hcom, EV_ERR)) {
1787 fprintf(stderr, "Failed SetCommMask\n");
1788 goto fail;
1789 }
1790
1791 cto.ReadIntervalTimeout = MAXDWORD;
1792 if (!SetCommTimeouts(s->hcom, &cto)) {
1793 fprintf(stderr, "Failed SetCommTimeouts\n");
1794 goto fail;
1795 }
1796
1797 if (!ClearCommError(s->hcom, &err, &comstat)) {
1798 fprintf(stderr, "Failed ClearCommError\n");
1799 goto fail;
1800 }
1801 qemu_add_polling_cb(win_chr_poll, s);
1802 return 0;
1803
1804 fail:
1805 win_chr_close2(s);
1806 return -1;
1807}
1808
1809static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1810{
1811 WinCharState *s = chr->opaque;
1812 DWORD len, ret, size, err;
1813
1814 len = len1;
1815 ZeroMemory(&s->osend, sizeof(s->osend));
1816 s->osend.hEvent = s->hsend;
1817 while (len > 0) {
1818 if (s->hsend)
1819 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1820 else
1821 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1822 if (!ret) {
1823 err = GetLastError();
1824 if (err == ERROR_IO_PENDING) {
1825 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1826 if (ret) {
1827 buf += size;
1828 len -= size;
1829 } else {
1830 break;
1831 }
1832 } else {
1833 break;
1834 }
1835 } else {
1836 buf += size;
1837 len -= size;
1838 }
1839 }
1840 return len1 - len;
1841}
1842
1843static int win_chr_read_poll(WinCharState *s)
1844{
1845 s->max_size = s->fd_can_read(s->win_opaque);
1846 return s->max_size;
1847}
1848
1849static void win_chr_readfile(WinCharState *s)
1850{
1851 int ret, err;
1852 uint8_t buf[1024];
1853 DWORD size;
1854
1855 ZeroMemory(&s->orecv, sizeof(s->orecv));
1856 s->orecv.hEvent = s->hrecv;
1857 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1858 if (!ret) {
1859 err = GetLastError();
1860 if (err == ERROR_IO_PENDING) {
1861 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1862 }
1863 }
1864
1865 if (size > 0) {
1866 s->fd_read(s->win_opaque, buf, size);
1867 }
1868}
1869
1870static void win_chr_read(WinCharState *s)
1871{
1872 if (s->len > s->max_size)
1873 s->len = s->max_size;
1874 if (s->len == 0)
1875 return;
1876
1877 win_chr_readfile(s);
1878}
1879
1880static int win_chr_poll(void *opaque)
1881{
1882 WinCharState *s = opaque;
1883 COMSTAT status;
1884 DWORD comerr;
1885
1886 ClearCommError(s->hcom, &comerr, &status);
1887 if (status.cbInQue > 0) {
1888 s->len = status.cbInQue;
1889 win_chr_read_poll(s);
1890 win_chr_read(s);
1891 return 1;
1892 }
1893 return 0;
1894}
1895
1896static void win_chr_add_read_handler(CharDriverState *chr,
1897 IOCanRWHandler *fd_can_read,
1898 IOReadHandler *fd_read, void *opaque)
1899{
1900 WinCharState *s = chr->opaque;
1901
1902 s->fd_can_read = fd_can_read;
1903 s->fd_read = fd_read;
1904 s->win_opaque = opaque;
1905}
1906
1907CharDriverState *qemu_chr_open_win(const char *filename)
1908{
1909 CharDriverState *chr;
1910 WinCharState *s;
1911
1912 chr = qemu_mallocz(sizeof(CharDriverState));
1913 if (!chr)
1914 return NULL;
1915 s = qemu_mallocz(sizeof(WinCharState));
1916 if (!s) {
1917 free(chr);
1918 return NULL;
1919 }
1920 chr->opaque = s;
1921 chr->chr_write = win_chr_write;
1922 chr->chr_add_read_handler = win_chr_add_read_handler;
1923 chr->chr_close = win_chr_close;
1924
1925 if (win_chr_init(s, filename) < 0) {
1926 free(s);
1927 free(chr);
1928 return NULL;
1929 }
1930 return chr;
1931}
1932
1933static int win_chr_pipe_poll(void *opaque)
1934{
1935 WinCharState *s = opaque;
1936 DWORD size;
1937
1938 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1939 if (size > 0) {
1940 s->len = size;
1941 win_chr_read_poll(s);
1942 win_chr_read(s);
1943 return 1;
1944 }
1945 return 0;
1946}
1947
1948static int win_chr_pipe_init(WinCharState *s, const char *filename)
1949{
1950 OVERLAPPED ov;
1951 int ret;
1952 DWORD size;
1953 char openname[256];
1954
1955 s->fpipe = TRUE;
1956
1957 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1958 if (!s->hsend) {
1959 fprintf(stderr, "Failed CreateEvent\n");
1960 goto fail;
1961 }
1962 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1963 if (!s->hrecv) {
1964 fprintf(stderr, "Failed CreateEvent\n");
1965 goto fail;
1966 }
1967
1968 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1969 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1970 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1971 PIPE_WAIT,
1972 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1973 if (s->hcom == INVALID_HANDLE_VALUE) {
1974 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1975 s->hcom = NULL;
1976 goto fail;
1977 }
1978
1979 ZeroMemory(&ov, sizeof(ov));
1980 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1981 ret = ConnectNamedPipe(s->hcom, &ov);
1982 if (ret) {
1983 fprintf(stderr, "Failed ConnectNamedPipe\n");
1984 goto fail;
1985 }
1986
1987 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1988 if (!ret) {
1989 fprintf(stderr, "Failed GetOverlappedResult\n");
1990 if (ov.hEvent) {
1991 CloseHandle(ov.hEvent);
1992 ov.hEvent = NULL;
1993 }
1994 goto fail;
1995 }
1996
1997 if (ov.hEvent) {
1998 CloseHandle(ov.hEvent);
1999 ov.hEvent = NULL;
2000 }
2001 qemu_add_polling_cb(win_chr_pipe_poll, s);
2002 return 0;
2003
2004 fail:
2005 win_chr_close2(s);
2006 return -1;
2007}
2008
2009
2010CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2011{
2012 CharDriverState *chr;
2013 WinCharState *s;
2014
2015 chr = qemu_mallocz(sizeof(CharDriverState));
2016 if (!chr)
2017 return NULL;
2018 s = qemu_mallocz(sizeof(WinCharState));
2019 if (!s) {
2020 free(chr);
2021 return NULL;
2022 }
2023 chr->opaque = s;
2024 chr->chr_write = win_chr_write;
2025 chr->chr_add_read_handler = win_chr_add_read_handler;
2026 chr->chr_close = win_chr_close;
2027
2028 if (win_chr_pipe_init(s, filename) < 0) {
2029 free(s);
2030 free(chr);
2031 return NULL;
2032 }
2033 return chr;
2034}
2035
2036CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2037{
2038 CharDriverState *chr;
2039 WinCharState *s;
2040
2041 chr = qemu_mallocz(sizeof(CharDriverState));
2042 if (!chr)
2043 return NULL;
2044 s = qemu_mallocz(sizeof(WinCharState));
2045 if (!s) {
2046 free(chr);
2047 return NULL;
2048 }
2049 s->hcom = fd_out;
2050 chr->opaque = s;
2051 chr->chr_write = win_chr_write;
2052 chr->chr_add_read_handler = win_chr_add_read_handler;
2053 return chr;
2054}
2055
2056CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2057{
2058 HANDLE fd_out;
2059
2060 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2061 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2062 if (fd_out == INVALID_HANDLE_VALUE)
2063 return NULL;
2064
2065 return qemu_chr_open_win_file(fd_out);
2066}
2067#endif
2068
82c643ff
FB
2069CharDriverState *qemu_chr_open(const char *filename)
2070{
f8d179e3 2071 const char *p;
fd1dff4b 2072
82c643ff
FB
2073 if (!strcmp(filename, "vc")) {
2074 return text_console_init(&display_state);
2075 } else if (!strcmp(filename, "null")) {
2076 return qemu_chr_open_null();
7664728b
FB
2077 } else
2078#ifndef _WIN32
2079 if (strstart(filename, "file:", &p)) {
f8d179e3
FB
2080 return qemu_chr_open_file_out(p);
2081 } else if (strstart(filename, "pipe:", &p)) {
2082 return qemu_chr_open_pipe(p);
7664728b 2083 } else if (!strcmp(filename, "pty")) {
82c643ff
FB
2084 return qemu_chr_open_pty();
2085 } else if (!strcmp(filename, "stdio")) {
2086 return qemu_chr_open_stdio();
2087 } else
f8d179e3
FB
2088#endif
2089#if defined(__linux__)
e57a8c0e
FB
2090 if (strstart(filename, "/dev/parport", NULL)) {
2091 return qemu_chr_open_pp(filename);
2092 } else
f8d179e3
FB
2093 if (strstart(filename, "/dev/", NULL)) {
2094 return qemu_chr_open_tty(filename);
2095 } else
f331110f
FB
2096#endif
2097#ifdef _WIN32
2098 if (strstart(filename, "COM", NULL)) {
2099 return qemu_chr_open_win(filename);
2100 } else
2101 if (strstart(filename, "pipe:", &p)) {
2102 return qemu_chr_open_win_pipe(p);
2103 } else
2104 if (strstart(filename, "file:", &p)) {
2105 return qemu_chr_open_win_file_out(p);
2106 }
82c643ff
FB
2107#endif
2108 {
2109 return NULL;
2110 }
2111}
2112
f331110f
FB
2113void qemu_chr_close(CharDriverState *chr)
2114{
2115 if (chr->chr_close)
2116 chr->chr_close(chr);
2117}
2118
80cabfad 2119/***********************************************************/
7c9d8e07 2120/* network device redirectors */
330d0414 2121
c20709aa
FB
2122void hex_dump(FILE *f, const uint8_t *buf, int size)
2123{
2124 int len, i, j, c;
2125
2126 for(i=0;i<size;i+=16) {
2127 len = size - i;
2128 if (len > 16)
2129 len = 16;
2130 fprintf(f, "%08x ", i);
2131 for(j=0;j<16;j++) {
2132 if (j < len)
2133 fprintf(f, " %02x", buf[i+j]);
2134 else
2135 fprintf(f, " ");
2136 }
2137 fprintf(f, " ");
2138 for(j=0;j<len;j++) {
2139 c = buf[i+j];
2140 if (c < ' ' || c > '~')
2141 c = '.';
2142 fprintf(f, "%c", c);
2143 }
2144 fprintf(f, "\n");
2145 }
2146}
2147
7c9d8e07 2148static int parse_macaddr(uint8_t *macaddr, const char *p)
c20709aa 2149{
7c9d8e07
FB
2150 int i;
2151 for(i = 0; i < 6; i++) {
2152 macaddr[i] = strtol(p, (char **)&p, 16);
2153 if (i == 5) {
2154 if (*p != '\0')
2155 return -1;
2156 } else {
2157 if (*p != ':')
2158 return -1;
2159 p++;
2160 }
2161 }
2162 return 0;
c20709aa 2163}
67b915a5 2164
7c9d8e07 2165static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
67b915a5 2166{
7c9d8e07
FB
2167 const char *p, *p1;
2168 int len;
2169 p = *pp;
2170 p1 = strchr(p, sep);
2171 if (!p1)
2172 return -1;
2173 len = p1 - p;
2174 p1++;
2175 if (buf_size > 0) {
2176 if (len > buf_size - 1)
2177 len = buf_size - 1;
2178 memcpy(buf, p, len);
2179 buf[len] = '\0';
2180 }
2181 *pp = p1;
2182 return 0;
c20709aa
FB
2183}
2184
7c9d8e07
FB
2185int parse_host_port(struct sockaddr_in *saddr, const char *str)
2186{
2187 char buf[512];
2188 struct hostent *he;
2189 const char *p, *r;
2190 int port;
2191
2192 p = str;
2193 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2194 return -1;
2195 saddr->sin_family = AF_INET;
2196 if (buf[0] == '\0') {
2197 saddr->sin_addr.s_addr = 0;
2198 } else {
2199 if (isdigit(buf[0])) {
2200 if (!inet_aton(buf, &saddr->sin_addr))
2201 return -1;
2202 } else {
7c9d8e07
FB
2203 if ((he = gethostbyname(buf)) == NULL)
2204 return - 1;
2205 saddr->sin_addr = *(struct in_addr *)he->h_addr;
7c9d8e07
FB
2206 }
2207 }
2208 port = strtol(p, (char **)&r, 0);
2209 if (r == p)
2210 return -1;
2211 saddr->sin_port = htons(port);
2212 return 0;
2213}
c20709aa 2214
7c9d8e07
FB
2215/* find or alloc a new VLAN */
2216VLANState *qemu_find_vlan(int id)
c20709aa 2217{
7c9d8e07
FB
2218 VLANState **pvlan, *vlan;
2219 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2220 if (vlan->id == id)
2221 return vlan;
2222 }
2223 vlan = qemu_mallocz(sizeof(VLANState));
2224 if (!vlan)
2225 return NULL;
2226 vlan->id = id;
2227 vlan->next = NULL;
2228 pvlan = &first_vlan;
2229 while (*pvlan != NULL)
2230 pvlan = &(*pvlan)->next;
2231 *pvlan = vlan;
2232 return vlan;
c20709aa
FB
2233}
2234
7c9d8e07 2235VLANClientState *qemu_new_vlan_client(VLANState *vlan,
d861b05e
PB
2236 IOReadHandler *fd_read,
2237 IOCanRWHandler *fd_can_read,
2238 void *opaque)
c20709aa 2239{
7c9d8e07
FB
2240 VLANClientState *vc, **pvc;
2241 vc = qemu_mallocz(sizeof(VLANClientState));
2242 if (!vc)
2243 return NULL;
2244 vc->fd_read = fd_read;
d861b05e 2245 vc->fd_can_read = fd_can_read;
7c9d8e07
FB
2246 vc->opaque = opaque;
2247 vc->vlan = vlan;
2248
2249 vc->next = NULL;
2250 pvc = &vlan->first_client;
2251 while (*pvc != NULL)
2252 pvc = &(*pvc)->next;
2253 *pvc = vc;
2254 return vc;
c20709aa
FB
2255}
2256
d861b05e
PB
2257int qemu_can_send_packet(VLANClientState *vc1)
2258{
2259 VLANState *vlan = vc1->vlan;
2260 VLANClientState *vc;
2261
2262 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2263 if (vc != vc1) {
2264 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2265 return 0;
2266 }
2267 }
2268 return 1;
2269}
2270
7c9d8e07 2271void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
c20709aa 2272{
7c9d8e07
FB
2273 VLANState *vlan = vc1->vlan;
2274 VLANClientState *vc;
2275
2276#if 0
2277 printf("vlan %d send:\n", vlan->id);
2278 hex_dump(stdout, buf, size);
2279#endif
2280 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2281 if (vc != vc1) {
2282 vc->fd_read(vc->opaque, buf, size);
2283 }
2284 }
67b915a5
FB
2285}
2286
c20709aa
FB
2287#if defined(CONFIG_SLIRP)
2288
2289/* slirp network adapter */
2290
c20709aa 2291static int slirp_inited;
7c9d8e07 2292static VLANClientState *slirp_vc;
c20709aa
FB
2293
2294int slirp_can_output(void)
2295{
3b7f5d47 2296 return !slirp_vc || qemu_can_send_packet(slirp_vc);
c20709aa
FB
2297}
2298
2299void slirp_output(const uint8_t *pkt, int pkt_len)
67b915a5 2300{
c20709aa 2301#if 0
7c9d8e07 2302 printf("slirp output:\n");
c20709aa
FB
2303 hex_dump(stdout, pkt, pkt_len);
2304#endif
3b7f5d47
PB
2305 if (!slirp_vc)
2306 return;
7c9d8e07 2307 qemu_send_packet(slirp_vc, pkt, pkt_len);
67b915a5
FB
2308}
2309
7c9d8e07 2310static void slirp_receive(void *opaque, const uint8_t *buf, int size)
c20709aa
FB
2311{
2312#if 0
7c9d8e07 2313 printf("slirp input:\n");
c20709aa
FB
2314 hex_dump(stdout, buf, size);
2315#endif
2316 slirp_input(buf, size);
2317}
2318
7c9d8e07 2319static int net_slirp_init(VLANState *vlan)
c20709aa
FB
2320{
2321 if (!slirp_inited) {
2322 slirp_inited = 1;
2323 slirp_init();
2324 }
7c9d8e07 2325 slirp_vc = qemu_new_vlan_client(vlan,
d861b05e 2326 slirp_receive, NULL, NULL);
7c9d8e07 2327 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
9bf05444
FB
2328 return 0;
2329}
2330
2331static void net_slirp_redir(const char *redir_str)
2332{
2333 int is_udp;
2334 char buf[256], *r;
2335 const char *p;
2336 struct in_addr guest_addr;
2337 int host_port, guest_port;
2338
2339 if (!slirp_inited) {
2340 slirp_inited = 1;
2341 slirp_init();
2342 }
2343
2344 p = redir_str;
2345 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2346 goto fail;
2347 if (!strcmp(buf, "tcp")) {
2348 is_udp = 0;
2349 } else if (!strcmp(buf, "udp")) {
2350 is_udp = 1;
2351 } else {
2352 goto fail;
2353 }
2354
2355 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2356 goto fail;
2357 host_port = strtol(buf, &r, 0);
2358 if (r == buf)
2359 goto fail;
2360
2361 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2362 goto fail;
2363 if (buf[0] == '\0') {
2364 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2365 }
2366 if (!inet_aton(buf, &guest_addr))
2367 goto fail;
2368
2369 guest_port = strtol(p, &r, 0);
2370 if (r == p)
2371 goto fail;
2372
2373 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2374 fprintf(stderr, "qemu: could not set up redirection\n");
2375 exit(1);
2376 }
2377 return;
2378 fail:
2379 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2380 exit(1);
2381}
9d728e8c 2382
c94c8d64
FB
2383#ifndef _WIN32
2384
9d728e8c
FB
2385char smb_dir[1024];
2386
2387static void smb_exit(void)
2388{
2389 DIR *d;
2390 struct dirent *de;
2391 char filename[1024];
2392
2393 /* erase all the files in the directory */
2394 d = opendir(smb_dir);
2395 for(;;) {
2396 de = readdir(d);
2397 if (!de)
2398 break;
2399 if (strcmp(de->d_name, ".") != 0 &&
2400 strcmp(de->d_name, "..") != 0) {
2401 snprintf(filename, sizeof(filename), "%s/%s",
2402 smb_dir, de->d_name);
2403 unlink(filename);
2404 }
2405 }
03ffbb69 2406 closedir(d);
9d728e8c
FB
2407 rmdir(smb_dir);
2408}
2409
2410/* automatic user mode samba server configuration */
2411void net_slirp_smb(const char *exported_dir)
2412{
2413 char smb_conf[1024];
2414 char smb_cmdline[1024];
2415 FILE *f;
2416
2417 if (!slirp_inited) {
2418 slirp_inited = 1;
2419 slirp_init();
2420 }
2421
2422 /* XXX: better tmp dir construction */
2423 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2424 if (mkdir(smb_dir, 0700) < 0) {
2425 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2426 exit(1);
2427 }
2428 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2429
2430 f = fopen(smb_conf, "w");
2431 if (!f) {
2432 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2433 exit(1);
2434 }
2435 fprintf(f,
2436 "[global]\n"
157777ef
FB
2437 "private dir=%s\n"
2438 "smb ports=0\n"
2439 "socket address=127.0.0.1\n"
9d728e8c
FB
2440 "pid directory=%s\n"
2441 "lock directory=%s\n"
2442 "log file=%s/log.smbd\n"
2443 "smb passwd file=%s/smbpasswd\n"
03ffbb69 2444 "security = share\n"
9d728e8c
FB
2445 "[qemu]\n"
2446 "path=%s\n"
2447 "read only=no\n"
2448 "guest ok=yes\n",
2449 smb_dir,
157777ef 2450 smb_dir,
9d728e8c
FB
2451 smb_dir,
2452 smb_dir,
2453 smb_dir,
2454 exported_dir
2455 );
2456 fclose(f);
2457 atexit(smb_exit);
2458
2459 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2460 smb_conf);
2461
2462 slirp_add_exec(0, smb_cmdline, 4, 139);
2463}
9bf05444 2464
c94c8d64
FB
2465#endif /* !defined(_WIN32) */
2466
c20709aa
FB
2467#endif /* CONFIG_SLIRP */
2468
2469#if !defined(_WIN32)
7c9d8e07
FB
2470
2471typedef struct TAPState {
2472 VLANClientState *vc;
2473 int fd;
2474} TAPState;
2475
2476static void tap_receive(void *opaque, const uint8_t *buf, int size)
2477{
2478 TAPState *s = opaque;
2479 int ret;
2480 for(;;) {
2481 ret = write(s->fd, buf, size);
2482 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2483 } else {
2484 break;
2485 }
2486 }
2487}
2488
2489static void tap_send(void *opaque)
2490{
2491 TAPState *s = opaque;
2492 uint8_t buf[4096];
2493 int size;
2494
2495 size = read(s->fd, buf, sizeof(buf));
2496 if (size > 0) {
2497 qemu_send_packet(s->vc, buf, size);
2498 }
2499}
2500
2501/* fd support */
2502
2503static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2504{
2505 TAPState *s;
2506
2507 s = qemu_mallocz(sizeof(TAPState));
2508 if (!s)
2509 return NULL;
2510 s->fd = fd;
d861b05e 2511 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
7c9d8e07
FB
2512 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2513 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2514 return s;
2515}
2516
7d3505c5 2517#ifdef _BSD
7c9d8e07 2518static int tap_open(char *ifname, int ifname_size)
7d3505c5
FB
2519{
2520 int fd;
2521 char *dev;
2522 struct stat s;
67b915a5 2523
7d3505c5
FB
2524 fd = open("/dev/tap", O_RDWR);
2525 if (fd < 0) {
2526 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2527 return -1;
2528 }
2529
2530 fstat(fd, &s);
2531 dev = devname(s.st_rdev, S_IFCHR);
2532 pstrcpy(ifname, ifname_size, dev);
2533
2534 fcntl(fd, F_SETFL, O_NONBLOCK);
2535 return fd;
2536}
ec530c81
FB
2537#elif defined(__sun__)
2538static int tap_open(char *ifname, int ifname_size)
2539{
2540 fprintf(stderr, "warning: tap_open not yet implemented\n");
2541 return -1;
2542}
7d3505c5 2543#else
7c9d8e07 2544static int tap_open(char *ifname, int ifname_size)
330d0414 2545{
80cabfad 2546 struct ifreq ifr;
c4b1fcc0 2547 int fd, ret;
80cabfad
FB
2548
2549 fd = open("/dev/net/tun", O_RDWR);
2550 if (fd < 0) {
2551 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2552 return -1;
330d0414 2553 }
80cabfad
FB
2554 memset(&ifr, 0, sizeof(ifr));
2555 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
7c9d8e07
FB
2556 if (ifname[0] != '\0')
2557 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2558 else
2559 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
80cabfad
FB
2560 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2561 if (ret != 0) {
2562 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2563 close(fd);
2564 return -1;
2565 }
c4b1fcc0 2566 pstrcpy(ifname, ifname_size, ifr.ifr_name);
80cabfad 2567 fcntl(fd, F_SETFL, O_NONBLOCK);
c4b1fcc0
FB
2568 return fd;
2569}
7d3505c5 2570#endif
330d0414 2571
7c9d8e07
FB
2572static int net_tap_init(VLANState *vlan, const char *ifname1,
2573 const char *setup_script)
2574{
2575 TAPState *s;
2576 int pid, status, fd;
2577 char *args[3];
2578 char **parg;
2579 char ifname[128];
2580
2581 if (ifname1 != NULL)
2582 pstrcpy(ifname, sizeof(ifname), ifname1);
2583 else
2584 ifname[0] = '\0';
2585 fd = tap_open(ifname, sizeof(ifname));
2586 if (fd < 0)
2587 return -1;
2588
2589 if (!setup_script)
2590 setup_script = "";
2591 if (setup_script[0] != '\0') {
2592 /* try to launch network init script */
2593 pid = fork();
2594 if (pid >= 0) {
2595 if (pid == 0) {
2596 parg = args;
2597 *parg++ = (char *)setup_script;
2598 *parg++ = ifname;
2599 *parg++ = NULL;
2600 execv(setup_script, args);
4a38940d 2601 _exit(1);
7c9d8e07
FB
2602 }
2603 while (waitpid(pid, &status, 0) != pid);
2604 if (!WIFEXITED(status) ||
2605 WEXITSTATUS(status) != 0) {
2606 fprintf(stderr, "%s: could not launch network script\n",
2607 setup_script);
2608 return -1;
2609 }
2610 }
2611 }
2612 s = net_tap_fd_init(vlan, fd);
2613 if (!s)
2614 return -1;
2615 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2616 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2617 return 0;
2618}
2619
fd1dff4b
FB
2620#endif /* !_WIN32 */
2621
7c9d8e07
FB
2622/* network connection */
2623typedef struct NetSocketState {
2624 VLANClientState *vc;
2625 int fd;
2626 int state; /* 0 = getting length, 1 = getting data */
2627 int index;
2628 int packet_len;
2629 uint8_t buf[4096];
3d830459 2630 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
7c9d8e07
FB
2631} NetSocketState;
2632
2633typedef struct NetSocketListenState {
2634 VLANState *vlan;
2635 int fd;
2636} NetSocketListenState;
2637
2638/* XXX: we consider we can send the whole packet without blocking */
2639static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
c20709aa 2640{
7c9d8e07
FB
2641 NetSocketState *s = opaque;
2642 uint32_t len;
2643 len = htonl(size);
2644
fd1dff4b
FB
2645 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2646 send_all(s->fd, buf, size);
c20709aa
FB
2647}
2648
3d830459
FB
2649static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2650{
2651 NetSocketState *s = opaque;
2652 sendto(s->fd, buf, size, 0,
2653 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2654}
2655
7c9d8e07 2656static void net_socket_send(void *opaque)
c4b1fcc0 2657{
7c9d8e07 2658 NetSocketState *s = opaque;
fd1dff4b 2659 int l, size, err;
7c9d8e07
FB
2660 uint8_t buf1[4096];
2661 const uint8_t *buf;
2662
fd1dff4b
FB
2663 size = recv(s->fd, buf1, sizeof(buf1), 0);
2664 if (size < 0) {
2665 err = socket_error();
2666 if (err != EWOULDBLOCK)
2667 goto eoc;
2668 } else if (size == 0) {
7c9d8e07 2669 /* end of connection */
fd1dff4b 2670 eoc:
7c9d8e07 2671 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
fd1dff4b 2672 closesocket(s->fd);
7c9d8e07
FB
2673 return;
2674 }
2675 buf = buf1;
2676 while (size > 0) {
2677 /* reassemble a packet from the network */
2678 switch(s->state) {
2679 case 0:
2680 l = 4 - s->index;
2681 if (l > size)
2682 l = size;
2683 memcpy(s->buf + s->index, buf, l);
2684 buf += l;
2685 size -= l;
2686 s->index += l;
2687 if (s->index == 4) {
2688 /* got length */
2689 s->packet_len = ntohl(*(uint32_t *)s->buf);
2690 s->index = 0;
2691 s->state = 1;
2692 }
2693 break;
2694 case 1:
2695 l = s->packet_len - s->index;
2696 if (l > size)
2697 l = size;
2698 memcpy(s->buf + s->index, buf, l);
2699 s->index += l;
2700 buf += l;
2701 size -= l;
2702 if (s->index >= s->packet_len) {
2703 qemu_send_packet(s->vc, s->buf, s->packet_len);
2704 s->index = 0;
2705 s->state = 0;
2706 }
2707 break;
2708 }
2709 }
c20709aa
FB
2710}
2711
3d830459
FB
2712static void net_socket_send_dgram(void *opaque)
2713{
2714 NetSocketState *s = opaque;
2715 int size;
2716
2717 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2718 if (size < 0)
2719 return;
2720 if (size == 0) {
2721 /* end of connection */
2722 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2723 return;
2724 }
2725 qemu_send_packet(s->vc, s->buf, size);
2726}
2727
2728static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2729{
2730 struct ip_mreq imr;
2731 int fd;
2732 int val, ret;
2733 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2734 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
fd1dff4b
FB
2735 inet_ntoa(mcastaddr->sin_addr),
2736 (int)ntohl(mcastaddr->sin_addr.s_addr));
3d830459
FB
2737 return -1;
2738
2739 }
2740 fd = socket(PF_INET, SOCK_DGRAM, 0);
2741 if (fd < 0) {
2742 perror("socket(PF_INET, SOCK_DGRAM)");
2743 return -1;
2744 }
2745
fd1dff4b
FB
2746 val = 1;
2747 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2748 (const char *)&val, sizeof(val));
2749 if (ret < 0) {
2750 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2751 goto fail;
2752 }
2753
2754 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2755 if (ret < 0) {
2756 perror("bind");
2757 goto fail;
2758 }
2759
3d830459
FB
2760 /* Add host to multicast group */
2761 imr.imr_multiaddr = mcastaddr->sin_addr;
2762 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2763
fd1dff4b
FB
2764 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2765 (const char *)&imr, sizeof(struct ip_mreq));
3d830459
FB
2766 if (ret < 0) {
2767 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2768 goto fail;
2769 }
2770
2771 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2772 val = 1;
fd1dff4b
FB
2773 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2774 (const char *)&val, sizeof(val));
3d830459
FB
2775 if (ret < 0) {
2776 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2777 goto fail;
2778 }
2779
fd1dff4b 2780 socket_set_nonblock(fd);
3d830459
FB
2781 return fd;
2782fail:
2783 if (fd>=0) close(fd);
2784 return -1;
2785}
2786
2787static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2788 int is_connected)
2789{
2790 struct sockaddr_in saddr;
2791 int newfd;
2792 socklen_t saddr_len;
2793 NetSocketState *s;
2794
2795 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2796 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2797 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2798 */
2799
2800 if (is_connected) {
2801 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2802 /* must be bound */
2803 if (saddr.sin_addr.s_addr==0) {
2804 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2805 fd);
2806 return NULL;
2807 }
2808 /* clone dgram socket */
2809 newfd = net_socket_mcast_create(&saddr);
2810 if (newfd < 0) {
2811 /* error already reported by net_socket_mcast_create() */
2812 close(fd);
2813 return NULL;
2814 }
2815 /* clone newfd to fd, close newfd */
2816 dup2(newfd, fd);
2817 close(newfd);
2818
2819 } else {
2820 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2821 fd, strerror(errno));
2822 return NULL;
2823 }
2824 }
2825
2826 s = qemu_mallocz(sizeof(NetSocketState));
2827 if (!s)
2828 return NULL;
2829 s->fd = fd;
2830
d861b05e 2831 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3d830459
FB
2832 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2833
2834 /* mcast: save bound address as dst */
2835 if (is_connected) s->dgram_dst=saddr;
2836
2837 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2838 "socket: fd=%d (%s mcast=%s:%d)",
2839 fd, is_connected? "cloned" : "",
2840 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2841 return s;
2842}
2843
7c9d8e07 2844static void net_socket_connect(void *opaque)
c20709aa 2845{
7c9d8e07
FB
2846 NetSocketState *s = opaque;
2847 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2848}
c4b1fcc0 2849
3d830459 2850static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
7c9d8e07
FB
2851 int is_connected)
2852{
2853 NetSocketState *s;
2854 s = qemu_mallocz(sizeof(NetSocketState));
2855 if (!s)
2856 return NULL;
2857 s->fd = fd;
2858 s->vc = qemu_new_vlan_client(vlan,
d861b05e 2859 net_socket_receive, NULL, s);
7c9d8e07
FB
2860 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2861 "socket: fd=%d", fd);
2862 if (is_connected) {
2863 net_socket_connect(s);
2864 } else {
2865 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2866 }
2867 return s;
2868}
c4b1fcc0 2869
3d830459
FB
2870static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2871 int is_connected)
2872{
2873 int so_type=-1, optlen=sizeof(so_type);
2874
fd1dff4b 2875 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3d830459
FB
2876 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2877 return NULL;
2878 }
2879 switch(so_type) {
2880 case SOCK_DGRAM:
2881 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2882 case SOCK_STREAM:
2883 return net_socket_fd_init_stream(vlan, fd, is_connected);
2884 default:
2885 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2886 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2887 return net_socket_fd_init_stream(vlan, fd, is_connected);
2888 }
2889 return NULL;
2890}
2891
7c9d8e07
FB
2892static void net_socket_accept(void *opaque)
2893{
2894 NetSocketListenState *s = opaque;
2895 NetSocketState *s1;
2896 struct sockaddr_in saddr;
2897 socklen_t len;
2898 int fd;
2899
2900 for(;;) {
2901 len = sizeof(saddr);
2902 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2903 if (fd < 0 && errno != EINTR) {
2904 return;
2905 } else if (fd >= 0) {
2906 break;
80cabfad 2907 }
330d0414 2908 }
7c9d8e07
FB
2909 s1 = net_socket_fd_init(s->vlan, fd, 1);
2910 if (!s1) {
2911 close(fd);
2912 } else {
2913 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2914 "socket: connection from %s:%d",
2915 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2916 }
2917}
2918
2919static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2920{
2921 NetSocketListenState *s;
2922 int fd, val, ret;
2923 struct sockaddr_in saddr;
2924
2925 if (parse_host_port(&saddr, host_str) < 0)
2926 return -1;
2927
2928 s = qemu_mallocz(sizeof(NetSocketListenState));
2929 if (!s)
2930 return -1;
2931
2932 fd = socket(PF_INET, SOCK_STREAM, 0);
2933 if (fd < 0) {
2934 perror("socket");
2935 return -1;
2936 }
fd1dff4b 2937 socket_set_nonblock(fd);
7c9d8e07
FB
2938
2939 /* allow fast reuse */
2940 val = 1;
fd1dff4b 2941 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
7c9d8e07
FB
2942
2943 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2944 if (ret < 0) {
2945 perror("bind");
2946 return -1;
2947 }
2948 ret = listen(fd, 0);
2949 if (ret < 0) {
2950 perror("listen");
2951 return -1;
2952 }
2953 s->vlan = vlan;
2954 s->fd = fd;
2955 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
80cabfad 2956 return 0;
330d0414
FB
2957}
2958
7c9d8e07 2959static int net_socket_connect_init(VLANState *vlan, const char *host_str)
330d0414 2960{
7c9d8e07 2961 NetSocketState *s;
fd1dff4b 2962 int fd, connected, ret, err;
7c9d8e07
FB
2963 struct sockaddr_in saddr;
2964
2965 if (parse_host_port(&saddr, host_str) < 0)
2966 return -1;
2967
2968 fd = socket(PF_INET, SOCK_STREAM, 0);
2969 if (fd < 0) {
2970 perror("socket");
2971 return -1;
2972 }
fd1dff4b 2973 socket_set_nonblock(fd);
7c9d8e07
FB
2974
2975 connected = 0;
2976 for(;;) {
2977 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2978 if (ret < 0) {
fd1dff4b
FB
2979 err = socket_error();
2980 if (err == EINTR || err == EWOULDBLOCK) {
2981 } else if (err == EINPROGRESS) {
7c9d8e07
FB
2982 break;
2983 } else {
2984 perror("connect");
fd1dff4b 2985 closesocket(fd);
7c9d8e07
FB
2986 return -1;
2987 }
2988 } else {
2989 connected = 1;
2990 break;
2991 }
2992 }
2993 s = net_socket_fd_init(vlan, fd, connected);
2994 if (!s)
2995 return -1;
2996 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2997 "socket: connect to %s:%d",
2998 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
c20709aa 2999 return 0;
80cabfad 3000}
330d0414 3001
3d830459
FB
3002static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3003{
3004 NetSocketState *s;
3005 int fd;
3006 struct sockaddr_in saddr;
3007
3008 if (parse_host_port(&saddr, host_str) < 0)
3009 return -1;
3010
3011
3012 fd = net_socket_mcast_create(&saddr);
3013 if (fd < 0)
3014 return -1;
3015
3016 s = net_socket_fd_init(vlan, fd, 0);
3017 if (!s)
3018 return -1;
3019
3020 s->dgram_dst = saddr;
3021
3022 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3023 "socket: mcast=%s:%d",
3024 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3025 return 0;
3026
3027}
3028
7c9d8e07
FB
3029static int get_param_value(char *buf, int buf_size,
3030 const char *tag, const char *str)
3031{
3032 const char *p;
3033 char *q;
3034 char option[128];
3035
3036 p = str;
3037 for(;;) {
3038 q = option;
3039 while (*p != '\0' && *p != '=') {
3040 if ((q - option) < sizeof(option) - 1)
3041 *q++ = *p;
3042 p++;
3043 }
3044 *q = '\0';
3045 if (*p != '=')
3046 break;
3047 p++;
3048 if (!strcmp(tag, option)) {
3049 q = buf;
3050 while (*p != '\0' && *p != ',') {
3051 if ((q - buf) < buf_size - 1)
3052 *q++ = *p;
3053 p++;
3054 }
3055 *q = '\0';
3056 return q - buf;
3057 } else {
3058 while (*p != '\0' && *p != ',') {
3059 p++;
3060 }
3061 }
3062 if (*p != ',')
3063 break;
3064 p++;
3065 }
3066 return 0;
3067}
3068
3069int net_client_init(const char *str)
3070{
3071 const char *p;
3072 char *q;
3073 char device[64];
3074 char buf[1024];
3075 int vlan_id, ret;
3076 VLANState *vlan;
3077
3078 p = str;
3079 q = device;
3080 while (*p != '\0' && *p != ',') {
3081 if ((q - device) < sizeof(device) - 1)
3082 *q++ = *p;
3083 p++;
3084 }
3085 *q = '\0';
3086 if (*p == ',')
3087 p++;
3088 vlan_id = 0;
3089 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3090 vlan_id = strtol(buf, NULL, 0);
3091 }
3092 vlan = qemu_find_vlan(vlan_id);
3093 if (!vlan) {
3094 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3095 return -1;
3096 }
3097 if (!strcmp(device, "nic")) {
3098 NICInfo *nd;
3099 uint8_t *macaddr;
3100
3101 if (nb_nics >= MAX_NICS) {
3102 fprintf(stderr, "Too Many NICs\n");
3103 return -1;
3104 }
3105 nd = &nd_table[nb_nics];
3106 macaddr = nd->macaddr;
3107 macaddr[0] = 0x52;
3108 macaddr[1] = 0x54;
3109 macaddr[2] = 0x00;
3110 macaddr[3] = 0x12;
3111 macaddr[4] = 0x34;
3112 macaddr[5] = 0x56 + nb_nics;
3113
3114 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3115 if (parse_macaddr(macaddr, buf) < 0) {
3116 fprintf(stderr, "invalid syntax for ethernet address\n");
3117 return -1;
3118 }
3119 }
a41b2ff2
PB
3120 if (get_param_value(buf, sizeof(buf), "model", p)) {
3121 nd->model = strdup(buf);
3122 }
7c9d8e07
FB
3123 nd->vlan = vlan;
3124 nb_nics++;
3125 ret = 0;
3126 } else
3127 if (!strcmp(device, "none")) {
3128 /* does nothing. It is needed to signal that no network cards
3129 are wanted */
3130 ret = 0;
3131 } else
3132#ifdef CONFIG_SLIRP
3133 if (!strcmp(device, "user")) {
115defd1 3134 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3f423c9c 3135 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
115defd1 3136 }
7c9d8e07
FB
3137 ret = net_slirp_init(vlan);
3138 } else
3139#endif
7fb843f8
FB
3140#ifdef _WIN32
3141 if (!strcmp(device, "tap")) {
3142 char ifname[64];
3143 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3144 fprintf(stderr, "tap: no interface name\n");
3145 return -1;
3146 }
3147 ret = tap_win32_init(vlan, ifname);
3148 } else
3149#else
7c9d8e07
FB
3150 if (!strcmp(device, "tap")) {
3151 char ifname[64];
3152 char setup_script[1024];
3153 int fd;
3154 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3155 fd = strtol(buf, NULL, 0);
3156 ret = -1;
3157 if (net_tap_fd_init(vlan, fd))
3158 ret = 0;
3159 } else {
3160 get_param_value(ifname, sizeof(ifname), "ifname", p);
3161 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3162 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3163 }
3164 ret = net_tap_init(vlan, ifname, setup_script);
3165 }
3166 } else
fd1dff4b 3167#endif
7c9d8e07
FB
3168 if (!strcmp(device, "socket")) {
3169 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3170 int fd;
3171 fd = strtol(buf, NULL, 0);
3172 ret = -1;
3173 if (net_socket_fd_init(vlan, fd, 1))
3174 ret = 0;
3175 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3176 ret = net_socket_listen_init(vlan, buf);
3177 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3178 ret = net_socket_connect_init(vlan, buf);
3d830459
FB
3179 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3180 ret = net_socket_mcast_init(vlan, buf);
7c9d8e07
FB
3181 } else {
3182 fprintf(stderr, "Unknown socket options: %s\n", p);
3183 return -1;
3184 }
3185 } else
7c9d8e07
FB
3186 {
3187 fprintf(stderr, "Unknown network device: %s\n", device);
3188 return -1;
3189 }
3190 if (ret < 0) {
3191 fprintf(stderr, "Could not initialize device '%s'\n", device);
3192 }
3193
3194 return ret;
3195}
3196
3197void do_info_network(void)
3198{
3199 VLANState *vlan;
3200 VLANClientState *vc;
3201
3202 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3203 term_printf("VLAN %d devices:\n", vlan->id);
3204 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3205 term_printf(" %s\n", vc->info_str);
3206 }
3207}
3208
a594cfbf
FB
3209/***********************************************************/
3210/* USB devices */
3211
3212static int usb_device_add(const char *devname)
3213{
3214 const char *p;
3215 USBDevice *dev;
3216 int i;
3217
3218 if (!vm_usb_hub)
3219 return -1;
3220 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3221 if (!vm_usb_ports[i]->dev)
3222 break;
3223 }
3224 if (i == MAX_VM_USB_PORTS)
3225 return -1;
3226
3227 if (strstart(devname, "host:", &p)) {
3228 dev = usb_host_device_open(p);
3229 if (!dev)
3230 return -1;
3231 } else if (!strcmp(devname, "mouse")) {
3232 dev = usb_mouse_init();
3233 if (!dev)
3234 return -1;
09b26c5e
FB
3235 } else if (!strcmp(devname, "tablet")) {
3236 dev = usb_tablet_init();
3237 if (!dev)
3238 return -1;
a594cfbf
FB
3239 } else {
3240 return -1;
3241 }
3242 usb_attach(vm_usb_ports[i], dev);
3243 return 0;
3244}
3245
3246static int usb_device_del(const char *devname)
3247{
3248 USBDevice *dev;
3249 int bus_num, addr, i;
3250 const char *p;
3251
3252 if (!vm_usb_hub)
3253 return -1;
3254
3255 p = strchr(devname, '.');
3256 if (!p)
3257 return -1;
3258 bus_num = strtoul(devname, NULL, 0);
3259 addr = strtoul(p + 1, NULL, 0);
3260 if (bus_num != 0)
3261 return -1;
3262 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3263 dev = vm_usb_ports[i]->dev;
3264 if (dev && dev->addr == addr)
3265 break;
3266 }
3267 if (i == MAX_VM_USB_PORTS)
3268 return -1;
3269 usb_attach(vm_usb_ports[i], NULL);
3270 return 0;
3271}
3272
3273void do_usb_add(const char *devname)
3274{
3275 int ret;
3276 ret = usb_device_add(devname);
3277 if (ret < 0)
3278 term_printf("Could not add USB device '%s'\n", devname);
3279}
3280
3281void do_usb_del(const char *devname)
3282{
3283 int ret;
3284 ret = usb_device_del(devname);
3285 if (ret < 0)
3286 term_printf("Could not remove USB device '%s'\n", devname);
3287}
3288
3289void usb_info(void)
3290{
3291 USBDevice *dev;
3292 int i;
3293 const char *speed_str;
3294
3295 if (!vm_usb_hub) {
3296 term_printf("USB support not enabled\n");
3297 return;
3298 }
3299
3300 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3301 dev = vm_usb_ports[i]->dev;
3302 if (dev) {
3303 term_printf("Hub port %d:\n", i);
3304 switch(dev->speed) {
3305 case USB_SPEED_LOW:
3306 speed_str = "1.5";
3307 break;
3308 case USB_SPEED_FULL:
3309 speed_str = "12";
3310 break;
3311 case USB_SPEED_HIGH:
3312 speed_str = "480";
3313 break;
3314 default:
3315 speed_str = "?";
3316 break;
3317 }
3318 term_printf(" Device %d.%d, speed %s Mb/s\n",
3319 0, dev->addr, speed_str);
3320 }
3321 }
3322}
3323
f7cce898
FB
3324/***********************************************************/
3325/* pid file */
3326
3327static char *pid_filename;
3328
3329/* Remove PID file. Called on normal exit */
3330
3331static void remove_pidfile(void)
3332{
3333 unlink (pid_filename);
3334}
3335
3336static void create_pidfile(const char *filename)
3337{
3338 struct stat pidstat;
3339 FILE *f;
3340
3341 /* Try to write our PID to the named file */
3342 if (stat(filename, &pidstat) < 0) {
3343 if (errno == ENOENT) {
3344 if ((f = fopen (filename, "w")) == NULL) {
3345 perror("Opening pidfile");
3346 exit(1);
3347 }
3348 fprintf(f, "%d\n", getpid());
3349 fclose(f);
3350 pid_filename = qemu_strdup(filename);
3351 if (!pid_filename) {
3352 fprintf(stderr, "Could not save PID filename");
3353 exit(1);
3354 }
3355 atexit(remove_pidfile);
3356 }
3357 } else {
3358 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3359 filename);
3360 exit(1);
3361 }
3362}
3363
313aa567
FB
3364/***********************************************************/
3365/* dumb display */
3366
313aa567
FB
3367static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3368{
3369}
3370
3371static void dumb_resize(DisplayState *ds, int w, int h)
3372{
3373}
3374
3375static void dumb_refresh(DisplayState *ds)
3376{
95219897 3377 vga_hw_update();
313aa567
FB
3378}
3379
3380void dumb_display_init(DisplayState *ds)
3381{
3382 ds->data = NULL;
3383 ds->linesize = 0;
3384 ds->depth = 0;
3385 ds->dpy_update = dumb_update;
3386 ds->dpy_resize = dumb_resize;
3387 ds->dpy_refresh = dumb_refresh;
3388}
3389
3a51dee6 3390#if !defined(CONFIG_SOFTMMU)
f1510b2c 3391/***********************************************************/
0824d6fc
FB
3392/* cpu signal handler */
3393static void host_segv_handler(int host_signum, siginfo_t *info,
3394 void *puc)
3395{
3396 if (cpu_signal_handler(host_signum, info, puc))
3397 return;
8d11df9e
FB
3398 if (stdio_nb_clients > 0)
3399 term_exit();
0824d6fc
FB
3400 abort();
3401}
3a51dee6 3402#endif
0824d6fc 3403
8a7ddc38
FB
3404/***********************************************************/
3405/* I/O handling */
0824d6fc 3406
c4b1fcc0
FB
3407#define MAX_IO_HANDLERS 64
3408
3409typedef struct IOHandlerRecord {
3410 int fd;
7c9d8e07
FB
3411 IOCanRWHandler *fd_read_poll;
3412 IOHandler *fd_read;
3413 IOHandler *fd_write;
c4b1fcc0
FB
3414 void *opaque;
3415 /* temporary data */
3416 struct pollfd *ufd;
8a7ddc38 3417 struct IOHandlerRecord *next;
c4b1fcc0
FB
3418} IOHandlerRecord;
3419
8a7ddc38 3420static IOHandlerRecord *first_io_handler;
c4b1fcc0 3421
7c9d8e07
FB
3422/* XXX: fd_read_poll should be suppressed, but an API change is
3423 necessary in the character devices to suppress fd_can_read(). */
3424int qemu_set_fd_handler2(int fd,
3425 IOCanRWHandler *fd_read_poll,
3426 IOHandler *fd_read,
3427 IOHandler *fd_write,
3428 void *opaque)
c4b1fcc0 3429{
7c9d8e07 3430 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 3431
7c9d8e07
FB
3432 if (!fd_read && !fd_write) {
3433 pioh = &first_io_handler;
3434 for(;;) {
3435 ioh = *pioh;
3436 if (ioh == NULL)
3437 break;
3438 if (ioh->fd == fd) {
3439 *pioh = ioh->next;
fd1dff4b 3440 qemu_free(ioh);
7c9d8e07
FB
3441 break;
3442 }
3443 pioh = &ioh->next;
3444 }
3445 } else {
3446 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3447 if (ioh->fd == fd)
3448 goto found;
3449 }
3450 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3451 if (!ioh)
3452 return -1;
3453 ioh->next = first_io_handler;
3454 first_io_handler = ioh;
3455 found:
3456 ioh->fd = fd;
3457 ioh->fd_read_poll = fd_read_poll;
3458 ioh->fd_read = fd_read;
3459 ioh->fd_write = fd_write;
3460 ioh->opaque = opaque;
3461 }
c4b1fcc0
FB
3462 return 0;
3463}
3464
7c9d8e07
FB
3465int qemu_set_fd_handler(int fd,
3466 IOHandler *fd_read,
3467 IOHandler *fd_write,
3468 void *opaque)
8a7ddc38 3469{
7c9d8e07 3470 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
3471}
3472
f331110f
FB
3473/***********************************************************/
3474/* Polling handling */
3475
3476typedef struct PollingEntry {
3477 PollingFunc *func;
3478 void *opaque;
3479 struct PollingEntry *next;
3480} PollingEntry;
3481
3482static PollingEntry *first_polling_entry;
3483
3484int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3485{
3486 PollingEntry **ppe, *pe;
3487 pe = qemu_mallocz(sizeof(PollingEntry));
3488 if (!pe)
3489 return -1;
3490 pe->func = func;
3491 pe->opaque = opaque;
3492 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3493 *ppe = pe;
3494 return 0;
3495}
3496
3497void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3498{
3499 PollingEntry **ppe, *pe;
3500 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3501 pe = *ppe;
3502 if (pe->func == func && pe->opaque == opaque) {
3503 *ppe = pe->next;
3504 qemu_free(pe);
3505 break;
3506 }
3507 }
3508}
3509
8a7ddc38
FB
3510/***********************************************************/
3511/* savevm/loadvm support */
3512
3513void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
b4608c04 3514{
8a7ddc38 3515 fwrite(buf, 1, size, f);
b4608c04
FB
3516}
3517
8a7ddc38 3518void qemu_put_byte(QEMUFile *f, int v)
b4608c04 3519{
8a7ddc38
FB
3520 fputc(v, f);
3521}
3522
3523void qemu_put_be16(QEMUFile *f, unsigned int v)
3524{
3525 qemu_put_byte(f, v >> 8);
3526 qemu_put_byte(f, v);
3527}
3528
3529void qemu_put_be32(QEMUFile *f, unsigned int v)
3530{
3531 qemu_put_byte(f, v >> 24);
3532 qemu_put_byte(f, v >> 16);
3533 qemu_put_byte(f, v >> 8);
3534 qemu_put_byte(f, v);
3535}
3536
3537void qemu_put_be64(QEMUFile *f, uint64_t v)
3538{
3539 qemu_put_be32(f, v >> 32);
3540 qemu_put_be32(f, v);
3541}
3542
3543int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3544{
3545 return fread(buf, 1, size, f);
3546}
3547
3548int qemu_get_byte(QEMUFile *f)
3549{
3550 int v;
3551 v = fgetc(f);
3552 if (v == EOF)
3553 return 0;
3554 else
3555 return v;
3556}
3557
3558unsigned int qemu_get_be16(QEMUFile *f)
3559{
3560 unsigned int v;
3561 v = qemu_get_byte(f) << 8;
3562 v |= qemu_get_byte(f);
3563 return v;
3564}
3565
3566unsigned int qemu_get_be32(QEMUFile *f)
3567{
3568 unsigned int v;
3569 v = qemu_get_byte(f) << 24;
3570 v |= qemu_get_byte(f) << 16;
3571 v |= qemu_get_byte(f) << 8;
3572 v |= qemu_get_byte(f);
3573 return v;
3574}
3575
3576uint64_t qemu_get_be64(QEMUFile *f)
3577{
3578 uint64_t v;
3579 v = (uint64_t)qemu_get_be32(f) << 32;
3580 v |= qemu_get_be32(f);
3581 return v;
3582}
3583
3584int64_t qemu_ftell(QEMUFile *f)
3585{
3586 return ftell(f);
3587}
3588
3589int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3590{
3591 if (fseek(f, pos, whence) < 0)
3592 return -1;
3593 return ftell(f);
3594}
3595
3596typedef struct SaveStateEntry {
3597 char idstr[256];
3598 int instance_id;
3599 int version_id;
3600 SaveStateHandler *save_state;
3601 LoadStateHandler *load_state;
3602 void *opaque;
3603 struct SaveStateEntry *next;
3604} SaveStateEntry;
b4608c04 3605
8a7ddc38
FB
3606static SaveStateEntry *first_se;
3607
3608int register_savevm(const char *idstr,
3609 int instance_id,
3610 int version_id,
3611 SaveStateHandler *save_state,
3612 LoadStateHandler *load_state,
3613 void *opaque)
3614{
3615 SaveStateEntry *se, **pse;
3616
3617 se = qemu_malloc(sizeof(SaveStateEntry));
3618 if (!se)
3619 return -1;
3620 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3621 se->instance_id = instance_id;
3622 se->version_id = version_id;
3623 se->save_state = save_state;
3624 se->load_state = load_state;
3625 se->opaque = opaque;
3626 se->next = NULL;
3627
3628 /* add at the end of list */
3629 pse = &first_se;
3630 while (*pse != NULL)
3631 pse = &(*pse)->next;
3632 *pse = se;
3633 return 0;
3634}
3635
3636#define QEMU_VM_FILE_MAGIC 0x5145564d
3637#define QEMU_VM_FILE_VERSION 0x00000001
3638
3639int qemu_savevm(const char *filename)
3640{
3641 SaveStateEntry *se;
3642 QEMUFile *f;
3643 int len, len_pos, cur_pos, saved_vm_running, ret;
3644
3645 saved_vm_running = vm_running;
3646 vm_stop(0);
3647
3648 f = fopen(filename, "wb");
3649 if (!f) {
3650 ret = -1;
3651 goto the_end;
313aa567
FB
3652 }
3653
8a7ddc38
FB
3654 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3655 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3656
3657 for(se = first_se; se != NULL; se = se->next) {
3658 /* ID string */
3659 len = strlen(se->idstr);
3660 qemu_put_byte(f, len);
3661 qemu_put_buffer(f, se->idstr, len);
3662
3663 qemu_put_be32(f, se->instance_id);
3664 qemu_put_be32(f, se->version_id);
3665
3666 /* record size: filled later */
3667 len_pos = ftell(f);
3668 qemu_put_be32(f, 0);
3669
3670 se->save_state(f, se->opaque);
3671
3672 /* fill record size */
3673 cur_pos = ftell(f);
3674 len = ftell(f) - len_pos - 4;
3675 fseek(f, len_pos, SEEK_SET);
3676 qemu_put_be32(f, len);
3677 fseek(f, cur_pos, SEEK_SET);
3678 }
3679
3680 fclose(f);
3681 ret = 0;
3682 the_end:
3683 if (saved_vm_running)
3684 vm_start();
3685 return ret;
3686}
3687
3688static SaveStateEntry *find_se(const char *idstr, int instance_id)
3689{
3690 SaveStateEntry *se;
3691
3692 for(se = first_se; se != NULL; se = se->next) {
3693 if (!strcmp(se->idstr, idstr) &&
3694 instance_id == se->instance_id)
3695 return se;
3696 }
3697 return NULL;
3698}
3699
3700int qemu_loadvm(const char *filename)
3701{
3702 SaveStateEntry *se;
3703 QEMUFile *f;
3704 int len, cur_pos, ret, instance_id, record_len, version_id;
3705 int saved_vm_running;
3706 unsigned int v;
3707 char idstr[256];
3708
3709 saved_vm_running = vm_running;
3710 vm_stop(0);
3711
3712 f = fopen(filename, "rb");
3713 if (!f) {
3714 ret = -1;
3715 goto the_end;
3716 }
3717
3718 v = qemu_get_be32(f);
3719 if (v != QEMU_VM_FILE_MAGIC)
3720 goto fail;
3721 v = qemu_get_be32(f);
3722 if (v != QEMU_VM_FILE_VERSION) {
3723 fail:
3724 fclose(f);
3725 ret = -1;
3726 goto the_end;
3727 }
b4608c04 3728 for(;;) {
8a7ddc38
FB
3729 len = qemu_get_byte(f);
3730 if (feof(f))
cd4c3e88 3731 break;
8a7ddc38
FB
3732 qemu_get_buffer(f, idstr, len);
3733 idstr[len] = '\0';
3734 instance_id = qemu_get_be32(f);
3735 version_id = qemu_get_be32(f);
3736 record_len = qemu_get_be32(f);
3737#if 0
3738 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3739 idstr, instance_id, version_id, record_len);
3740#endif
3741 cur_pos = ftell(f);
3742 se = find_se(idstr, instance_id);
3743 if (!se) {
3744 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3745 instance_id, idstr);
3746 } else {
3747 ret = se->load_state(f, se->opaque, version_id);
3748 if (ret < 0) {
3749 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3750 instance_id, idstr);
3751 }
34865134 3752 }
8a7ddc38
FB
3753 /* always seek to exact end of record */
3754 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3755 }
3756 fclose(f);
3757 ret = 0;
3758 the_end:
3759 if (saved_vm_running)
3760 vm_start();
3761 return ret;
3762}
3763
3764/***********************************************************/
3765/* cpu save/restore */
3766
3767#if defined(TARGET_I386)
3768
3769static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3770{
02ba45c5 3771 qemu_put_be32(f, dt->selector);
20f32282 3772 qemu_put_betl(f, dt->base);
8a7ddc38
FB
3773 qemu_put_be32(f, dt->limit);
3774 qemu_put_be32(f, dt->flags);
3775}
3776
3777static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3778{
02ba45c5 3779 dt->selector = qemu_get_be32(f);
20f32282 3780 dt->base = qemu_get_betl(f);
8a7ddc38
FB
3781 dt->limit = qemu_get_be32(f);
3782 dt->flags = qemu_get_be32(f);
3783}
3784
3785void cpu_save(QEMUFile *f, void *opaque)
3786{
3787 CPUState *env = opaque;
664e0f19 3788 uint16_t fptag, fpus, fpuc, fpregs_format;
8a7ddc38
FB
3789 uint32_t hflags;
3790 int i;
664e0f19 3791
20f32282
FB
3792 for(i = 0; i < CPU_NB_REGS; i++)
3793 qemu_put_betls(f, &env->regs[i]);
3794 qemu_put_betls(f, &env->eip);
3795 qemu_put_betls(f, &env->eflags);
8a7ddc38
FB
3796 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3797 qemu_put_be32s(f, &hflags);
3798
3799 /* FPU */
3800 fpuc = env->fpuc;
3801 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3802 fptag = 0;
664e0f19
FB
3803 for(i = 0; i < 8; i++) {
3804 fptag |= ((!env->fptags[i]) << i);
8a7ddc38
FB
3805 }
3806
3807 qemu_put_be16s(f, &fpuc);
3808 qemu_put_be16s(f, &fpus);
3809 qemu_put_be16s(f, &fptag);
3810
664e0f19
FB
3811#ifdef USE_X86LDOUBLE
3812 fpregs_format = 0;
3813#else
3814 fpregs_format = 1;
3815#endif
3816 qemu_put_be16s(f, &fpregs_format);
3817
8a7ddc38 3818 for(i = 0; i < 8; i++) {
664e0f19 3819#ifdef USE_X86LDOUBLE
8636b5d8
FB
3820 {
3821 uint64_t mant;
3822 uint16_t exp;
3823 /* we save the real CPU data (in case of MMX usage only 'mant'
3824 contains the MMX register */
3825 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3826 qemu_put_be64(f, mant);
3827 qemu_put_be16(f, exp);
3828 }
664e0f19
FB
3829#else
3830 /* if we use doubles for float emulation, we save the doubles to
3831 avoid losing information in case of MMX usage. It can give
3832 problems if the image is restored on a CPU where long
3833 doubles are used instead. */
8636b5d8 3834 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
664e0f19 3835#endif
8a7ddc38
FB
3836 }
3837
3838 for(i = 0; i < 6; i++)
3839 cpu_put_seg(f, &env->segs[i]);
3840 cpu_put_seg(f, &env->ldt);
3841 cpu_put_seg(f, &env->tr);
3842 cpu_put_seg(f, &env->gdt);
3843 cpu_put_seg(f, &env->idt);
3844
3845 qemu_put_be32s(f, &env->sysenter_cs);
3846 qemu_put_be32s(f, &env->sysenter_esp);
3847 qemu_put_be32s(f, &env->sysenter_eip);
3848
20f32282
FB
3849 qemu_put_betls(f, &env->cr[0]);
3850 qemu_put_betls(f, &env->cr[2]);
3851 qemu_put_betls(f, &env->cr[3]);
3852 qemu_put_betls(f, &env->cr[4]);
8a7ddc38
FB
3853
3854 for(i = 0; i < 8; i++)
20f32282 3855 qemu_put_betls(f, &env->dr[i]);
8a7ddc38
FB
3856
3857 /* MMU */
3858 qemu_put_be32s(f, &env->a20_mask);
02536f8b 3859
664e0f19
FB
3860 /* XMM */
3861 qemu_put_be32s(f, &env->mxcsr);
02536f8b
FB
3862 for(i = 0; i < CPU_NB_REGS; i++) {
3863 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3864 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3865 }
3866
664e0f19 3867#ifdef TARGET_X86_64
02536f8b
FB
3868 qemu_put_be64s(f, &env->efer);
3869 qemu_put_be64s(f, &env->star);
3870 qemu_put_be64s(f, &env->lstar);
3871 qemu_put_be64s(f, &env->cstar);
3872 qemu_put_be64s(f, &env->fmask);
3873 qemu_put_be64s(f, &env->kernelgsbase);
3874#endif
8a7ddc38
FB
3875}
3876
8636b5d8 3877#ifdef USE_X86LDOUBLE
664e0f19
FB
3878/* XXX: add that in a FPU generic layer */
3879union x86_longdouble {
3880 uint64_t mant;
3881 uint16_t exp;
3882};
3883
3884#define MANTD1(fp) (fp & ((1LL << 52) - 1))
3885#define EXPBIAS1 1023
3886#define EXPD1(fp) ((fp >> 52) & 0x7FF)
3887#define SIGND1(fp) ((fp >> 32) & 0x80000000)
3888
3889static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3890{
3891 int e;
3892 /* mantissa */
3893 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3894 /* exponent + sign */
3895 e = EXPD1(temp) - EXPBIAS1 + 16383;
3896 e |= SIGND1(temp) >> 16;
3897 p->exp = e;
3898}
8636b5d8 3899#endif
664e0f19 3900
8a7ddc38
FB
3901int cpu_load(QEMUFile *f, void *opaque, int version_id)
3902{
3903 CPUState *env = opaque;
664e0f19 3904 int i, guess_mmx;
8a7ddc38 3905 uint32_t hflags;
664e0f19 3906 uint16_t fpus, fpuc, fptag, fpregs_format;
8a7ddc38 3907
664e0f19 3908 if (version_id != 3)
8a7ddc38 3909 return -EINVAL;
20f32282
FB
3910 for(i = 0; i < CPU_NB_REGS; i++)
3911 qemu_get_betls(f, &env->regs[i]);
3912 qemu_get_betls(f, &env->eip);
3913 qemu_get_betls(f, &env->eflags);
8a7ddc38
FB
3914 qemu_get_be32s(f, &hflags);
3915
3916 qemu_get_be16s(f, &fpuc);
3917 qemu_get_be16s(f, &fpus);
3918 qemu_get_be16s(f, &fptag);
664e0f19
FB
3919 qemu_get_be16s(f, &fpregs_format);
3920
3921 /* NOTE: we cannot always restore the FPU state if the image come
3922 from a host with a different 'USE_X86LDOUBLE' define. We guess
3923 if we are in an MMX state to restore correctly in that case. */
3924 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
8a7ddc38
FB
3925 for(i = 0; i < 8; i++) {
3926 uint64_t mant;
3927 uint16_t exp;
664e0f19
FB
3928
3929 switch(fpregs_format) {
3930 case 0:
3931 mant = qemu_get_be64(f);
3932 exp = qemu_get_be16(f);
3933#ifdef USE_X86LDOUBLE
3934 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3935#else
3936 /* difficult case */
3937 if (guess_mmx)
8636b5d8 3938 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
3939 else
3940 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3941#endif
3942 break;
3943 case 1:
3944 mant = qemu_get_be64(f);
3945#ifdef USE_X86LDOUBLE
8636b5d8
FB
3946 {
3947 union x86_longdouble *p;
3948 /* difficult case */
3949 p = (void *)&env->fpregs[i];
3950 if (guess_mmx) {
3951 p->mant = mant;
3952 p->exp = 0xffff;
3953 } else {
3954 fp64_to_fp80(p, mant);
3955 }
664e0f19
FB
3956 }
3957#else
8636b5d8 3958 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
3959#endif
3960 break;
3961 default:
3962 return -EINVAL;
3963 }
8a7ddc38
FB
3964 }
3965
3966 env->fpuc = fpuc;
7a0e1f41 3967 /* XXX: restore FPU round state */
8a7ddc38
FB
3968 env->fpstt = (fpus >> 11) & 7;
3969 env->fpus = fpus & ~0x3800;
664e0f19 3970 fptag ^= 0xff;
8a7ddc38 3971 for(i = 0; i < 8; i++) {
664e0f19 3972 env->fptags[i] = (fptag >> i) & 1;
8a7ddc38
FB
3973 }
3974
3975 for(i = 0; i < 6; i++)
3976 cpu_get_seg(f, &env->segs[i]);
3977 cpu_get_seg(f, &env->ldt);
3978 cpu_get_seg(f, &env->tr);
3979 cpu_get_seg(f, &env->gdt);
3980 cpu_get_seg(f, &env->idt);
3981
3982 qemu_get_be32s(f, &env->sysenter_cs);
3983 qemu_get_be32s(f, &env->sysenter_esp);
3984 qemu_get_be32s(f, &env->sysenter_eip);
3985
20f32282
FB
3986 qemu_get_betls(f, &env->cr[0]);
3987 qemu_get_betls(f, &env->cr[2]);
3988 qemu_get_betls(f, &env->cr[3]);
3989 qemu_get_betls(f, &env->cr[4]);
8a7ddc38
FB
3990
3991 for(i = 0; i < 8; i++)
20f32282 3992 qemu_get_betls(f, &env->dr[i]);
8a7ddc38
FB
3993
3994 /* MMU */
3995 qemu_get_be32s(f, &env->a20_mask);
3996
664e0f19 3997 qemu_get_be32s(f, &env->mxcsr);
02536f8b
FB
3998 for(i = 0; i < CPU_NB_REGS; i++) {
3999 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4000 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4001 }
4002
664e0f19 4003#ifdef TARGET_X86_64
02536f8b
FB
4004 qemu_get_be64s(f, &env->efer);
4005 qemu_get_be64s(f, &env->star);
4006 qemu_get_be64s(f, &env->lstar);
4007 qemu_get_be64s(f, &env->cstar);
4008 qemu_get_be64s(f, &env->fmask);
4009 qemu_get_be64s(f, &env->kernelgsbase);
4010#endif
4011
8a7ddc38
FB
4012 /* XXX: compute hflags from scratch, except for CPL and IIF */
4013 env->hflags = hflags;
4014 tlb_flush(env, 1);
4015 return 0;
4016}
4017
a541f297
FB
4018#elif defined(TARGET_PPC)
4019void cpu_save(QEMUFile *f, void *opaque)
4020{
4021}
4022
e95c8d51
FB
4023int cpu_load(QEMUFile *f, void *opaque, int version_id)
4024{
4025 return 0;
4026}
6af0bf9c
FB
4027
4028#elif defined(TARGET_MIPS)
4029void cpu_save(QEMUFile *f, void *opaque)
4030{
4031}
4032
4033int cpu_load(QEMUFile *f, void *opaque, int version_id)
4034{
4035 return 0;
4036}
4037
e95c8d51
FB
4038#elif defined(TARGET_SPARC)
4039void cpu_save(QEMUFile *f, void *opaque)
4040{
e80cfcfc
FB
4041 CPUState *env = opaque;
4042 int i;
4043 uint32_t tmp;
4044
4fa5d772
FB
4045 for(i = 0; i < 8; i++)
4046 qemu_put_betls(f, &env->gregs[i]);
4047 for(i = 0; i < NWINDOWS * 16; i++)
4048 qemu_put_betls(f, &env->regbase[i]);
e80cfcfc
FB
4049
4050 /* FPU */
4fa5d772
FB
4051 for(i = 0; i < TARGET_FPREGS; i++) {
4052 union {
4053 TARGET_FPREG_T f;
4054 target_ulong i;
4055 } u;
4056 u.f = env->fpr[i];
4057 qemu_put_betl(f, u.i);
4058 }
4059
4060 qemu_put_betls(f, &env->pc);
4061 qemu_put_betls(f, &env->npc);
4062 qemu_put_betls(f, &env->y);
e80cfcfc 4063 tmp = GET_PSR(env);
4fa5d772 4064 qemu_put_be32(f, tmp);
3475187d
FB
4065 qemu_put_betls(f, &env->fsr);
4066 qemu_put_betls(f, &env->tbr);
4067#ifndef TARGET_SPARC64
e80cfcfc 4068 qemu_put_be32s(f, &env->wim);
e80cfcfc
FB
4069 /* MMU */
4070 for(i = 0; i < 16; i++)
4071 qemu_put_be32s(f, &env->mmuregs[i]);
3475187d 4072#endif
e95c8d51
FB
4073}
4074
a541f297
FB
4075int cpu_load(QEMUFile *f, void *opaque, int version_id)
4076{
e80cfcfc
FB
4077 CPUState *env = opaque;
4078 int i;
4079 uint32_t tmp;
4080
4fa5d772
FB
4081 for(i = 0; i < 8; i++)
4082 qemu_get_betls(f, &env->gregs[i]);
4083 for(i = 0; i < NWINDOWS * 16; i++)
4084 qemu_get_betls(f, &env->regbase[i]);
e80cfcfc
FB
4085
4086 /* FPU */
4fa5d772
FB
4087 for(i = 0; i < TARGET_FPREGS; i++) {
4088 union {
4089 TARGET_FPREG_T f;
4090 target_ulong i;
4091 } u;
4092 u.i = qemu_get_betl(f);
4093 env->fpr[i] = u.f;
4094 }
4095
4096 qemu_get_betls(f, &env->pc);
4097 qemu_get_betls(f, &env->npc);
4098 qemu_get_betls(f, &env->y);
4099 tmp = qemu_get_be32(f);
4100 env->cwp = 0; /* needed to ensure that the wrapping registers are
4101 correctly updated */
e80cfcfc 4102 PUT_PSR(env, tmp);
3475187d
FB
4103 qemu_get_betls(f, &env->fsr);
4104 qemu_get_betls(f, &env->tbr);
4105#ifndef TARGET_SPARC64
e80cfcfc 4106 qemu_get_be32s(f, &env->wim);
e80cfcfc
FB
4107 /* MMU */
4108 for(i = 0; i < 16; i++)
4109 qemu_get_be32s(f, &env->mmuregs[i]);
3475187d 4110#endif
e80cfcfc 4111 tlb_flush(env, 1);
a541f297
FB
4112 return 0;
4113}
b5ff1b31
FB
4114
4115#elif defined(TARGET_ARM)
4116
4117/* ??? Need to implement these. */
4118void cpu_save(QEMUFile *f, void *opaque)
4119{
4120}
4121
4122int cpu_load(QEMUFile *f, void *opaque, int version_id)
4123{
4124 return 0;
4125}
4126
8a7ddc38
FB
4127#else
4128
4129#warning No CPU save/restore functions
4130
4131#endif
4132
4133/***********************************************************/
4134/* ram save/restore */
4135
4136/* we just avoid storing empty pages */
4137static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4138{
4139 int i, v;
4140
4141 v = buf[0];
4142 for(i = 1; i < len; i++) {
4143 if (buf[i] != v)
4144 goto normal_save;
4145 }
4146 qemu_put_byte(f, 1);
4147 qemu_put_byte(f, v);
4148 return;
4149 normal_save:
4150 qemu_put_byte(f, 0);
4151 qemu_put_buffer(f, buf, len);
4152}
4153
4154static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4155{
4156 int v;
4157
4158 v = qemu_get_byte(f);
4159 switch(v) {
4160 case 0:
4161 if (qemu_get_buffer(f, buf, len) != len)
4162 return -EIO;
4163 break;
4164 case 1:
4165 v = qemu_get_byte(f);
4166 memset(buf, v, len);
4167 break;
4168 default:
4169 return -EINVAL;
4170 }
4171 return 0;
4172}
4173
4174static void ram_save(QEMUFile *f, void *opaque)
4175{
4176 int i;
4177 qemu_put_be32(f, phys_ram_size);
4178 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4179 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4180 }
4181}
4182
4183static int ram_load(QEMUFile *f, void *opaque, int version_id)
4184{
4185 int i, ret;
4186
4187 if (version_id != 1)
4188 return -EINVAL;
4189 if (qemu_get_be32(f) != phys_ram_size)
4190 return -EINVAL;
4191 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4192 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4193 if (ret)
4194 return ret;
4195 }
4196 return 0;
4197}
4198
cc1daa40
FB
4199/***********************************************************/
4200/* machine registration */
4201
4202QEMUMachine *first_machine = NULL;
4203
4204int qemu_register_machine(QEMUMachine *m)
4205{
4206 QEMUMachine **pm;
4207 pm = &first_machine;
4208 while (*pm != NULL)
4209 pm = &(*pm)->next;
4210 m->next = NULL;
4211 *pm = m;
4212 return 0;
4213}
4214
4215QEMUMachine *find_machine(const char *name)
4216{
4217 QEMUMachine *m;
4218
4219 for(m = first_machine; m != NULL; m = m->next) {
4220 if (!strcmp(m->name, name))
4221 return m;
4222 }
4223 return NULL;
4224}
4225
8a7ddc38
FB
4226/***********************************************************/
4227/* main execution loop */
4228
4229void gui_update(void *opaque)
4230{
4231 display_state.dpy_refresh(&display_state);
4232 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4233}
4234
0bd48850
FB
4235struct vm_change_state_entry {
4236 VMChangeStateHandler *cb;
4237 void *opaque;
4238 LIST_ENTRY (vm_change_state_entry) entries;
4239};
4240
4241static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4242
4243VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4244 void *opaque)
4245{
4246 VMChangeStateEntry *e;
4247
4248 e = qemu_mallocz(sizeof (*e));
4249 if (!e)
4250 return NULL;
4251
4252 e->cb = cb;
4253 e->opaque = opaque;
4254 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4255 return e;
4256}
4257
4258void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4259{
4260 LIST_REMOVE (e, entries);
4261 qemu_free (e);
4262}
4263
4264static void vm_state_notify(int running)
4265{
4266 VMChangeStateEntry *e;
4267
4268 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4269 e->cb(e->opaque, running);
4270 }
4271}
4272
8a7ddc38 4273/* XXX: support several handlers */
0bd48850
FB
4274static VMStopHandler *vm_stop_cb;
4275static void *vm_stop_opaque;
8a7ddc38
FB
4276
4277int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4278{
4279 vm_stop_cb = cb;
4280 vm_stop_opaque = opaque;
4281 return 0;
4282}
4283
4284void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4285{
4286 vm_stop_cb = NULL;
4287}
4288
4289void vm_start(void)
4290{
4291 if (!vm_running) {
4292 cpu_enable_ticks();
4293 vm_running = 1;
0bd48850 4294 vm_state_notify(1);
8a7ddc38
FB
4295 }
4296}
4297
4298void vm_stop(int reason)
4299{
4300 if (vm_running) {
4301 cpu_disable_ticks();
4302 vm_running = 0;
4303 if (reason != 0) {
4304 if (vm_stop_cb) {
4305 vm_stop_cb(vm_stop_opaque, reason);
4306 }
34865134 4307 }
0bd48850 4308 vm_state_notify(0);
8a7ddc38
FB
4309 }
4310}
4311
bb0c6722
FB
4312/* reset/shutdown handler */
4313
4314typedef struct QEMUResetEntry {
4315 QEMUResetHandler *func;
4316 void *opaque;
4317 struct QEMUResetEntry *next;
4318} QEMUResetEntry;
4319
4320static QEMUResetEntry *first_reset_entry;
4321static int reset_requested;
4322static int shutdown_requested;
3475187d 4323static int powerdown_requested;
bb0c6722
FB
4324
4325void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4326{
4327 QEMUResetEntry **pre, *re;
4328
4329 pre = &first_reset_entry;
4330 while (*pre != NULL)
4331 pre = &(*pre)->next;
4332 re = qemu_mallocz(sizeof(QEMUResetEntry));
4333 re->func = func;
4334 re->opaque = opaque;
4335 re->next = NULL;
4336 *pre = re;
4337}
4338
4339void qemu_system_reset(void)
4340{
4341 QEMUResetEntry *re;
4342
4343 /* reset all devices */
4344 for(re = first_reset_entry; re != NULL; re = re->next) {
4345 re->func(re->opaque);
4346 }
4347}
4348
4349void qemu_system_reset_request(void)
4350{
4351 reset_requested = 1;
6a00d601
FB
4352 if (cpu_single_env)
4353 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
4354}
4355
4356void qemu_system_shutdown_request(void)
4357{
4358 shutdown_requested = 1;
6a00d601
FB
4359 if (cpu_single_env)
4360 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
4361}
4362
3475187d
FB
4363void qemu_system_powerdown_request(void)
4364{
4365 powerdown_requested = 1;
6a00d601
FB
4366 if (cpu_single_env)
4367 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
4368}
4369
5905b2e5 4370void main_loop_wait(int timeout)
8a7ddc38 4371{
8a7ddc38 4372 IOHandlerRecord *ioh, *ioh_next;
fd1dff4b
FB
4373 fd_set rfds, wfds;
4374 int ret, nfds;
4375 struct timeval tv;
f331110f
FB
4376 PollingEntry *pe;
4377
c4b1fcc0 4378
f331110f
FB
4379 /* XXX: need to suppress polling by better using win32 events */
4380 ret = 0;
4381 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4382 ret |= pe->func(pe->opaque);
4383 }
38e205a2 4384#ifdef _WIN32
f331110f 4385 if (ret == 0 && timeout > 0) {
fd1dff4b 4386 Sleep(timeout);
f331110f 4387 }
fd1dff4b
FB
4388#endif
4389 /* poll any events */
4390 /* XXX: separate device handlers from system ones */
4391 nfds = -1;
4392 FD_ZERO(&rfds);
4393 FD_ZERO(&wfds);
4394 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4395 if (ioh->fd_read &&
4396 (!ioh->fd_read_poll ||
4397 ioh->fd_read_poll(ioh->opaque) != 0)) {
4398 FD_SET(ioh->fd, &rfds);
4399 if (ioh->fd > nfds)
4400 nfds = ioh->fd;
4401 }
4402 if (ioh->fd_write) {
4403 FD_SET(ioh->fd, &wfds);
4404 if (ioh->fd > nfds)
4405 nfds = ioh->fd;
4406 }
4407 }
4408
4409 tv.tv_sec = 0;
4410#ifdef _WIN32
4411 tv.tv_usec = 0;
38e205a2 4412#else
fd1dff4b
FB
4413 tv.tv_usec = timeout * 1000;
4414#endif
4415 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4416 if (ret > 0) {
4417 /* XXX: better handling of removal */
4418 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4419 ioh_next = ioh->next;
4420 if (FD_ISSET(ioh->fd, &rfds)) {
4421 ioh->fd_read(ioh->opaque);
7c9d8e07 4422 }
fd1dff4b
FB
4423 if (FD_ISSET(ioh->fd, &wfds)) {
4424 ioh->fd_write(ioh->opaque);
c4b1fcc0 4425 }
b4608c04 4426 }
fd1dff4b 4427 }
7fb843f8
FB
4428#ifdef _WIN32
4429 tap_win32_poll();
4430#endif
fd1dff4b 4431
c20709aa 4432#if defined(CONFIG_SLIRP)
fd1dff4b
FB
4433 /* XXX: merge with the previous select() */
4434 if (slirp_inited) {
4435 fd_set rfds, wfds, xfds;
4436 int nfds;
4437 struct timeval tv;
4438
4439 nfds = -1;
4440 FD_ZERO(&rfds);
4441 FD_ZERO(&wfds);
4442 FD_ZERO(&xfds);
4443 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4444 tv.tv_sec = 0;
4445 tv.tv_usec = 0;
4446 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4447 if (ret >= 0) {
4448 slirp_select_poll(&rfds, &wfds, &xfds);
c20709aa 4449 }
fd1dff4b 4450 }
67b915a5 4451#endif
b4608c04 4452
fd1dff4b
FB
4453 if (vm_running) {
4454 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4455 qemu_get_clock(vm_clock));
4456 /* run dma transfers, if any */
4457 DMA_run();
4458 }
4459
4460 /* real time timers */
4461 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4462 qemu_get_clock(rt_clock));
5905b2e5
FB
4463}
4464
6a00d601
FB
4465static CPUState *cur_cpu;
4466
5905b2e5
FB
4467int main_loop(void)
4468{
4469 int ret, timeout;
89bfc105
FB
4470#ifdef CONFIG_PROFILER
4471 int64_t ti;
4472#endif
6a00d601 4473 CPUState *env;
5905b2e5 4474
6a00d601 4475 cur_cpu = first_cpu;
5905b2e5
FB
4476 for(;;) {
4477 if (vm_running) {
15a76449
FB
4478
4479 env = cur_cpu;
4480 for(;;) {
4481 /* get next cpu */
4482 env = env->next_cpu;
4483 if (!env)
4484 env = first_cpu;
89bfc105
FB
4485#ifdef CONFIG_PROFILER
4486 ti = profile_getclock();
4487#endif
6a00d601 4488 ret = cpu_exec(env);
89bfc105
FB
4489#ifdef CONFIG_PROFILER
4490 qemu_time += profile_getclock() - ti;
4491#endif
15a76449
FB
4492 if (ret != EXCP_HALTED)
4493 break;
4494 /* all CPUs are halted ? */
4495 if (env == cur_cpu) {
4496 ret = EXCP_HLT;
4497 break;
4498 }
4499 }
4500 cur_cpu = env;
4501
5905b2e5 4502 if (shutdown_requested) {
3475187d 4503 ret = EXCP_INTERRUPT;
5905b2e5
FB
4504 break;
4505 }
4506 if (reset_requested) {
4507 reset_requested = 0;
4508 qemu_system_reset();
3475187d
FB
4509 ret = EXCP_INTERRUPT;
4510 }
4511 if (powerdown_requested) {
4512 powerdown_requested = 0;
4513 qemu_system_powerdown();
4514 ret = EXCP_INTERRUPT;
5905b2e5
FB
4515 }
4516 if (ret == EXCP_DEBUG) {
4517 vm_stop(EXCP_DEBUG);
4518 }
4519 /* if hlt instruction, we wait until the next IRQ */
4520 /* XXX: use timeout computed from timers */
3475187d 4521 if (ret == EXCP_HLT)
5905b2e5
FB
4522 timeout = 10;
4523 else
4524 timeout = 0;
4525 } else {
4526 timeout = 10;
4527 }
89bfc105
FB
4528#ifdef CONFIG_PROFILER
4529 ti = profile_getclock();
4530#endif
5905b2e5 4531 main_loop_wait(timeout);
89bfc105
FB
4532#ifdef CONFIG_PROFILER
4533 dev_time += profile_getclock() - ti;
4534#endif
b4608c04 4535 }
34865134
FB
4536 cpu_disable_ticks();
4537 return ret;
b4608c04
FB
4538}
4539
0824d6fc
FB
4540void help(void)
4541{
f5a8510c 4542 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
0db63474 4543 "usage: %s [options] [disk_image]\n"
0824d6fc 4544 "\n"
a20dd508 4545 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 4546 "\n"
a20dd508 4547 "Standard options:\n"
cc1daa40 4548 "-M machine select emulated machine (-M ? for list)\n"
c45886db 4549 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
36b486bb
FB
4550 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4551 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
c4b1fcc0 4552 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
9e89a4be 4553 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
a20dd508 4554 "-snapshot write to temporary files instead of disk image files\n"
a00bad7e 4555 "-m megs set virtual RAM size to megs MB [default=%d]\n"
91fc2119 4556 "-smp n set the number of CPUs to 'n' [default=1]\n"
c4b1fcc0 4557 "-nographic disable graphical output and redirect serial I/Os to console\n"
4ca0074c 4558#ifndef _WIN32
3d11d0eb 4559 "-k language use keyboard layout (for example \"fr\" for French)\n"
4ca0074c 4560#endif
1d14ffa9 4561#ifdef HAS_AUDIO
1d14ffa9 4562 "-audio-help print list of audio drivers and their options\n"
c0fe3827
FB
4563 "-soundhw c1,... enable audio support\n"
4564 " and only specified sound cards (comma separated list)\n"
4565 " use -soundhw ? to get the list of supported cards\n"
6a36d84e 4566 " use -soundhw all to enable all of them\n"
1d14ffa9 4567#endif
89980284 4568 "-localtime set the real time clock to local time [default=utc]\n"
d63d307f 4569 "-full-screen start in full screen\n"
a09db21f
FB
4570#ifdef TARGET_I386
4571 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4572#endif
b389dbfb
FB
4573 "-usb enable the USB driver (will be the default soon)\n"
4574 "-usbdevice name add the host or guest USB device 'name'\n"
6f7e9aec
FB
4575#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4576 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
bb0c6722 4577#endif
c4b1fcc0
FB
4578 "\n"
4579 "Network options:\n"
a41b2ff2 4580 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7c9d8e07 4581 " create a new Network Interface Card and connect it to VLAN 'n'\n"
c20709aa 4582#ifdef CONFIG_SLIRP
115defd1
PB
4583 "-net user[,vlan=n][,hostname=host]\n"
4584 " connect the user mode network stack to VLAN 'n' and send\n"
4585 " hostname 'host' to DHCP clients\n"
7c9d8e07 4586#endif
7fb843f8
FB
4587#ifdef _WIN32
4588 "-net tap[,vlan=n],ifname=name\n"
4589 " connect the host TAP network interface to VLAN 'n'\n"
4590#else
7c9d8e07
FB
4591 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4592 " connect the host TAP network interface to VLAN 'n' and use\n"
4593 " the network script 'file' (default=%s);\n"
4594 " use 'fd=h' to connect to an already opened TAP interface\n"
7fb843f8 4595#endif
6a00d601 4596 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7c9d8e07 4597 " connect the vlan 'n' to another VLAN using a socket connection\n"
3d830459
FB
4598 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4599 " connect the vlan 'n' to multicast maddr and port\n"
7c9d8e07
FB
4600 "-net none use it alone to have zero network devices; if no -net option\n"
4601 " is provided, the default is '-net nic -net user'\n"
4602 "\n"
4603#ifdef CONFIG_SLIRP
4604 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4605#ifndef _WIN32
4606 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
c94c8d64 4607#endif
9bf05444 4608 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7c9d8e07 4609 " redirect TCP or UDP connections from host to guest [-net user]\n"
c20709aa 4610#endif
a20dd508 4611 "\n"
c4b1fcc0 4612 "Linux boot specific:\n"
a20dd508
FB
4613 "-kernel bzImage use 'bzImage' as kernel image\n"
4614 "-append cmdline use 'cmdline' as kernel command line\n"
4615 "-initrd file use 'file' as initial ram disk\n"
fc01f7e7 4616 "\n"
330d0414 4617 "Debug/Expert options:\n"
82c643ff
FB
4618 "-monitor dev redirect the monitor to char device 'dev'\n"
4619 "-serial dev redirect the serial port to char device 'dev'\n"
6508fe59 4620 "-parallel dev redirect the parallel port to char device 'dev'\n"
f7cce898 4621 "-pidfile file Write PID to 'file'\n"
cd6f1169 4622 "-S freeze CPU at startup (use 'c' to start execution)\n"
a20dd508
FB
4623 "-s wait gdb connection to port %d\n"
4624 "-p port change gdb connection port\n"
f193c797 4625 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
46d4767d
FB
4626 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4627 " translation (t=none or lba) (usually qemu can guess them)\n"
a20dd508 4628 "-L path set the directory for the BIOS and VGA BIOS\n"
d993e026
FB
4629#ifdef USE_KQEMU
4630 "-no-kqemu disable KQEMU kernel module usage\n"
4631#endif
77fef8c1
FB
4632#ifdef USE_CODE_COPY
4633 "-no-code-copy disable code copy acceleration\n"
4634#endif
bb0c6722 4635#ifdef TARGET_I386
1bfe856e
FB
4636 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4637 " (default is CL-GD5446 PCI VGA)\n"
bb0c6722 4638#endif
d63d307f 4639 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
24236869 4640 "-vnc display start a VNC server on display\n"
0824d6fc 4641 "\n"
82c643ff 4642 "During emulation, the following keys are useful:\n"
032a8c9e
FB
4643 "ctrl-alt-f toggle full screen\n"
4644 "ctrl-alt-n switch to virtual console 'n'\n"
4645 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
4646 "\n"
4647 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4648 ,
0db63474
FB
4649#ifdef CONFIG_SOFTMMU
4650 "qemu",
4651#else
4652 "qemu-fast",
4653#endif
a00bad7e 4654 DEFAULT_RAM_SIZE,
7c9d8e07 4655#ifndef _WIN32
a00bad7e 4656 DEFAULT_NETWORK_SCRIPT,
7c9d8e07 4657#endif
6e44ba7f
FB
4658 DEFAULT_GDBSTUB_PORT,
4659 "/tmp/qemu.log");
0db63474
FB
4660#ifndef CONFIG_SOFTMMU
4661 printf("\n"
4662 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4663 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4664 "PC emulation.\n");
4665#endif
0824d6fc
FB
4666 exit(1);
4667}
4668
cd6f1169
FB
4669#define HAS_ARG 0x0001
4670
4671enum {
4672 QEMU_OPTION_h,
4673
cc1daa40 4674 QEMU_OPTION_M,
cd6f1169
FB
4675 QEMU_OPTION_fda,
4676 QEMU_OPTION_fdb,
4677 QEMU_OPTION_hda,
4678 QEMU_OPTION_hdb,
4679 QEMU_OPTION_hdc,
4680 QEMU_OPTION_hdd,
4681 QEMU_OPTION_cdrom,
4682 QEMU_OPTION_boot,
4683 QEMU_OPTION_snapshot,
4684 QEMU_OPTION_m,
4685 QEMU_OPTION_nographic,
1d14ffa9 4686#ifdef HAS_AUDIO
1d14ffa9
FB
4687 QEMU_OPTION_audio_help,
4688 QEMU_OPTION_soundhw,
4689#endif
cd6f1169 4690
7c9d8e07 4691 QEMU_OPTION_net,
c7f74643 4692 QEMU_OPTION_tftp,
9d728e8c 4693 QEMU_OPTION_smb,
9bf05444 4694 QEMU_OPTION_redir,
cd6f1169
FB
4695
4696 QEMU_OPTION_kernel,
4697 QEMU_OPTION_append,
4698 QEMU_OPTION_initrd,
4699
4700 QEMU_OPTION_S,
4701 QEMU_OPTION_s,
4702 QEMU_OPTION_p,
4703 QEMU_OPTION_d,
4704 QEMU_OPTION_hdachs,
4705 QEMU_OPTION_L,
4706 QEMU_OPTION_no_code_copy,
3d11d0eb 4707 QEMU_OPTION_k,
ee22c2f7 4708 QEMU_OPTION_localtime,
1f04275e 4709 QEMU_OPTION_cirrusvga,
e9b137c2 4710 QEMU_OPTION_g,
1bfe856e 4711 QEMU_OPTION_std_vga,
82c643ff
FB
4712 QEMU_OPTION_monitor,
4713 QEMU_OPTION_serial,
6508fe59 4714 QEMU_OPTION_parallel,
d63d307f
FB
4715 QEMU_OPTION_loadvm,
4716 QEMU_OPTION_full_screen,
f7cce898 4717 QEMU_OPTION_pidfile,
d993e026 4718 QEMU_OPTION_no_kqemu,
89bfc105 4719 QEMU_OPTION_kernel_kqemu,
a09db21f 4720 QEMU_OPTION_win2k_hack,
bb36d470 4721 QEMU_OPTION_usb,
a594cfbf 4722 QEMU_OPTION_usbdevice,
6a00d601 4723 QEMU_OPTION_smp,
24236869 4724 QEMU_OPTION_vnc,
cd6f1169
FB
4725};
4726
4727typedef struct QEMUOption {
4728 const char *name;
4729 int flags;
4730 int index;
4731} QEMUOption;
4732
4733const QEMUOption qemu_options[] = {
4734 { "h", 0, QEMU_OPTION_h },
4735
cc1daa40 4736 { "M", HAS_ARG, QEMU_OPTION_M },
cd6f1169
FB
4737 { "fda", HAS_ARG, QEMU_OPTION_fda },
4738 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4739 { "hda", HAS_ARG, QEMU_OPTION_hda },
4740 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4741 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4742 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4743 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4744 { "boot", HAS_ARG, QEMU_OPTION_boot },
4745 { "snapshot", 0, QEMU_OPTION_snapshot },
4746 { "m", HAS_ARG, QEMU_OPTION_m },
4747 { "nographic", 0, QEMU_OPTION_nographic },
3d11d0eb 4748 { "k", HAS_ARG, QEMU_OPTION_k },
1d14ffa9 4749#ifdef HAS_AUDIO
1d14ffa9
FB
4750 { "audio-help", 0, QEMU_OPTION_audio_help },
4751 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4752#endif
cd6f1169 4753
7c9d8e07 4754 { "net", HAS_ARG, QEMU_OPTION_net},
158156d1 4755#ifdef CONFIG_SLIRP
c7f74643 4756 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
c94c8d64 4757#ifndef _WIN32
9d728e8c 4758 { "smb", HAS_ARG, QEMU_OPTION_smb },
c94c8d64 4759#endif
9bf05444 4760 { "redir", HAS_ARG, QEMU_OPTION_redir },
158156d1 4761#endif
cd6f1169
FB
4762
4763 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4764 { "append", HAS_ARG, QEMU_OPTION_append },
4765 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4766
4767 { "S", 0, QEMU_OPTION_S },
4768 { "s", 0, QEMU_OPTION_s },
4769 { "p", HAS_ARG, QEMU_OPTION_p },
4770 { "d", HAS_ARG, QEMU_OPTION_d },
4771 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4772 { "L", HAS_ARG, QEMU_OPTION_L },
4773 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
d993e026
FB
4774#ifdef USE_KQEMU
4775 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
89bfc105 4776 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
d993e026 4777#endif
6f7e9aec 4778#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2 4779 { "g", 1, QEMU_OPTION_g },
77d4bc34 4780#endif
ee22c2f7 4781 { "localtime", 0, QEMU_OPTION_localtime },
1bfe856e 4782 { "std-vga", 0, QEMU_OPTION_std_vga },
82c643ff
FB
4783 { "monitor", 1, QEMU_OPTION_monitor },
4784 { "serial", 1, QEMU_OPTION_serial },
6508fe59 4785 { "parallel", 1, QEMU_OPTION_parallel },
d63d307f
FB
4786 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4787 { "full-screen", 0, QEMU_OPTION_full_screen },
f7cce898 4788 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
a09db21f 4789 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
a594cfbf 4790 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6a00d601 4791 { "smp", HAS_ARG, QEMU_OPTION_smp },
24236869 4792 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
a09db21f 4793
1f04275e 4794 /* temporary options */
a594cfbf 4795 { "usb", 0, QEMU_OPTION_usb },
1f04275e 4796 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
cd6f1169 4797 { NULL },
fc01f7e7
FB
4798};
4799
77fef8c1
FB
4800#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4801
4802/* this stack is only used during signal handling */
4803#define SIGNAL_STACK_SIZE 32768
4804
4805static uint8_t *signal_stack;
4806
4807#endif
4808
5905b2e5
FB
4809/* password input */
4810
4811static BlockDriverState *get_bdrv(int index)
4812{
4813 BlockDriverState *bs;
4814
4815 if (index < 4) {
4816 bs = bs_table[index];
4817 } else if (index < 6) {
4818 bs = fd_table[index - 4];
4819 } else {
4820 bs = NULL;
4821 }
4822 return bs;
4823}
4824
4825static void read_passwords(void)
4826{
4827 BlockDriverState *bs;
4828 int i, j;
4829 char password[256];
4830
4831 for(i = 0; i < 6; i++) {
4832 bs = get_bdrv(i);
4833 if (bs && bdrv_is_encrypted(bs)) {
4834 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4835 for(j = 0; j < 3; j++) {
4836 monitor_readline("Password: ",
4837 1, password, sizeof(password));
4838 if (bdrv_set_key(bs, password) == 0)
4839 break;
4840 term_printf("invalid password\n");
4841 }
4842 }
4843 }
4844}
4845
cc1daa40
FB
4846/* XXX: currently we cannot use simultaneously different CPUs */
4847void register_machines(void)
4848{
4849#if defined(TARGET_I386)
4850 qemu_register_machine(&pc_machine);
3dbbdc25 4851 qemu_register_machine(&isapc_machine);
cc1daa40
FB
4852#elif defined(TARGET_PPC)
4853 qemu_register_machine(&heathrow_machine);
4854 qemu_register_machine(&core99_machine);
4855 qemu_register_machine(&prep_machine);
6af0bf9c
FB
4856#elif defined(TARGET_MIPS)
4857 qemu_register_machine(&mips_machine);
cc1daa40 4858#elif defined(TARGET_SPARC)
3475187d
FB
4859#ifdef TARGET_SPARC64
4860 qemu_register_machine(&sun4u_machine);
4861#else
cc1daa40
FB
4862 qemu_register_machine(&sun4m_machine);
4863#endif
b5ff1b31 4864#elif defined(TARGET_ARM)
40f137e1
PB
4865 qemu_register_machine(&integratorcp926_machine);
4866 qemu_register_machine(&integratorcp1026_machine);
cdbdb648 4867 qemu_register_machine(&versatilepb_machine);
16406950 4868 qemu_register_machine(&versatileab_machine);
27c7ca7e
FB
4869#elif defined(TARGET_SH4)
4870 qemu_register_machine(&shix_machine);
b5ff1b31
FB
4871#else
4872#error unsupported CPU
3475187d 4873#endif
cc1daa40
FB
4874}
4875
1d14ffa9 4876#ifdef HAS_AUDIO
6a36d84e 4877struct soundhw soundhw[] = {
fd06c375
FB
4878#ifdef TARGET_I386
4879 {
4880 "pcspk",
4881 "PC speaker",
4882 0,
4883 1,
4884 { .init_isa = pcspk_audio_init }
4885 },
4886#endif
6a36d84e
FB
4887 {
4888 "sb16",
4889 "Creative Sound Blaster 16",
4890 0,
4891 1,
4892 { .init_isa = SB16_init }
4893 },
4894
1d14ffa9 4895#ifdef CONFIG_ADLIB
6a36d84e
FB
4896 {
4897 "adlib",
1d14ffa9 4898#ifdef HAS_YMF262
6a36d84e 4899 "Yamaha YMF262 (OPL3)",
1d14ffa9 4900#else
6a36d84e 4901 "Yamaha YM3812 (OPL2)",
1d14ffa9 4902#endif
6a36d84e
FB
4903 0,
4904 1,
4905 { .init_isa = Adlib_init }
4906 },
1d14ffa9 4907#endif
6a36d84e 4908
1d14ffa9 4909#ifdef CONFIG_GUS
6a36d84e
FB
4910 {
4911 "gus",
4912 "Gravis Ultrasound GF1",
4913 0,
4914 1,
4915 { .init_isa = GUS_init }
4916 },
1d14ffa9 4917#endif
6a36d84e
FB
4918
4919 {
4920 "es1370",
4921 "ENSONIQ AudioPCI ES1370",
4922 0,
4923 0,
4924 { .init_pci = es1370_init }
4925 },
4926
4927 { NULL, NULL, 0, 0, { NULL } }
4928};
4929
4930static void select_soundhw (const char *optarg)
4931{
4932 struct soundhw *c;
4933
4934 if (*optarg == '?') {
4935 show_valid_cards:
4936
4937 printf ("Valid sound card names (comma separated):\n");
4938 for (c = soundhw; c->name; ++c) {
4939 printf ("%-11s %s\n", c->name, c->descr);
4940 }
4941 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
4942 exit (*optarg != '?');
4943 }
4944 else {
6a36d84e 4945 size_t l;
1d14ffa9
FB
4946 const char *p;
4947 char *e;
4948 int bad_card = 0;
4949
6a36d84e
FB
4950 if (!strcmp (optarg, "all")) {
4951 for (c = soundhw; c->name; ++c) {
4952 c->enabled = 1;
4953 }
4954 return;
4955 }
1d14ffa9 4956
6a36d84e 4957 p = optarg;
1d14ffa9
FB
4958 while (*p) {
4959 e = strchr (p, ',');
4960 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
4961
4962 for (c = soundhw; c->name; ++c) {
4963 if (!strncmp (c->name, p, l)) {
4964 c->enabled = 1;
1d14ffa9
FB
4965 break;
4966 }
4967 }
6a36d84e
FB
4968
4969 if (!c->name) {
1d14ffa9
FB
4970 if (l > 80) {
4971 fprintf (stderr,
4972 "Unknown sound card name (too big to show)\n");
4973 }
4974 else {
4975 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4976 (int) l, p);
4977 }
4978 bad_card = 1;
4979 }
4980 p += l + (e != NULL);
4981 }
4982
4983 if (bad_card)
4984 goto show_valid_cards;
4985 }
4986}
4987#endif
4988
7c9d8e07 4989#define MAX_NET_CLIENTS 32
c20709aa 4990
0824d6fc
FB
4991int main(int argc, char **argv)
4992{
67b915a5
FB
4993#ifdef CONFIG_GDBSTUB
4994 int use_gdbstub, gdbstub_port;
4995#endif
cc1daa40 4996 int i, cdrom_index;
1ccde1cb 4997 int snapshot, linux_boot;
7f7f9873 4998 const char *initrd_filename;
c45886db 4999 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
a20dd508 5000 const char *kernel_filename, *kernel_cmdline;
313aa567 5001 DisplayState *ds = &display_state;
46d4767d 5002 int cyls, heads, secs, translation;
a541f297 5003 int start_emulation = 1;
7c9d8e07
FB
5004 char net_clients[MAX_NET_CLIENTS][256];
5005 int nb_net_clients;
cd6f1169
FB
5006 int optind;
5007 const char *r, *optarg;
82c643ff
FB
5008 CharDriverState *monitor_hd;
5009 char monitor_device[128];
8d11df9e
FB
5010 char serial_devices[MAX_SERIAL_PORTS][128];
5011 int serial_device_index;
6508fe59
FB
5012 char parallel_devices[MAX_PARALLEL_PORTS][128];
5013 int parallel_device_index;
d63d307f 5014 const char *loadvm = NULL;
cc1daa40 5015 QEMUMachine *machine;
a594cfbf
FB
5016 char usb_devices[MAX_VM_USB_PORTS][128];
5017 int usb_devices_index;
0bd48850
FB
5018
5019 LIST_INIT (&vm_change_state_head);
67b915a5 5020#if !defined(CONFIG_SOFTMMU)
0824d6fc
FB
5021 /* we never want that malloc() uses mmap() */
5022 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
67b915a5 5023#endif
cc1daa40
FB
5024 register_machines();
5025 machine = first_machine;
fc01f7e7 5026 initrd_filename = NULL;
c45886db
FB
5027 for(i = 0; i < MAX_FD; i++)
5028 fd_filename[i] = NULL;
fc01f7e7
FB
5029 for(i = 0; i < MAX_DISKS; i++)
5030 hd_filename[i] = NULL;
a00bad7e 5031 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
313aa567 5032 vga_ram_size = VGA_RAM_SIZE;
0ced6589 5033 bios_size = BIOS_SIZE;
67b915a5 5034#ifdef CONFIG_GDBSTUB
b4608c04
FB
5035 use_gdbstub = 0;
5036 gdbstub_port = DEFAULT_GDBSTUB_PORT;
67b915a5 5037#endif
33e3963e 5038 snapshot = 0;
a20dd508
FB
5039 nographic = 0;
5040 kernel_filename = NULL;
5041 kernel_cmdline = "";
cc1daa40
FB
5042#ifdef TARGET_PPC
5043 cdrom_index = 1;
5044#else
5045 cdrom_index = 2;
5046#endif
c4b1fcc0 5047 cyls = heads = secs = 0;
46d4767d 5048 translation = BIOS_ATA_TRANSLATION_AUTO;
82c643ff 5049 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
c4b1fcc0 5050
8d11df9e
FB
5051 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5052 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5053 serial_devices[i][0] = '\0';
5054 serial_device_index = 0;
5055
6508fe59
FB
5056 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5057 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5058 parallel_devices[i][0] = '\0';
5059 parallel_device_index = 0;
5060
a594cfbf
FB
5061 usb_devices_index = 0;
5062
7c9d8e07
FB
5063 nb_net_clients = 0;
5064
5065 nb_nics = 0;
702c651c 5066 /* default mac address of the first network interface */
82c643ff 5067
cd6f1169 5068 optind = 1;
0824d6fc 5069 for(;;) {
cd6f1169 5070 if (optind >= argc)
0824d6fc 5071 break;
cd6f1169
FB
5072 r = argv[optind];
5073 if (r[0] != '-') {
5074 hd_filename[0] = argv[optind++];
5075 } else {
5076 const QEMUOption *popt;
5077
5078 optind++;
5079 popt = qemu_options;
5080 for(;;) {
5081 if (!popt->name) {
5082 fprintf(stderr, "%s: invalid option -- '%s'\n",
5083 argv[0], r);
5084 exit(1);
5085 }
5086 if (!strcmp(popt->name, r + 1))
5087 break;
5088 popt++;
5089 }
5090 if (popt->flags & HAS_ARG) {
5091 if (optind >= argc) {
5092 fprintf(stderr, "%s: option '%s' requires an argument\n",
5093 argv[0], r);
5094 exit(1);
5095 }
5096 optarg = argv[optind++];
5097 } else {
5098 optarg = NULL;
5099 }
5100
5101 switch(popt->index) {
cc1daa40
FB
5102 case QEMU_OPTION_M:
5103 machine = find_machine(optarg);
5104 if (!machine) {
5105 QEMUMachine *m;
5106 printf("Supported machines are:\n");
5107 for(m = first_machine; m != NULL; m = m->next) {
5108 printf("%-10s %s%s\n",
5109 m->name, m->desc,
5110 m == first_machine ? " (default)" : "");
5111 }
5112 exit(1);
5113 }
5114 break;
cd6f1169 5115 case QEMU_OPTION_initrd:
fc01f7e7
FB
5116 initrd_filename = optarg;
5117 break;
cd6f1169 5118 case QEMU_OPTION_hda:
cd6f1169 5119 case QEMU_OPTION_hdb:
cc1daa40
FB
5120 case QEMU_OPTION_hdc:
5121 case QEMU_OPTION_hdd:
5122 {
5123 int hd_index;
5124 hd_index = popt->index - QEMU_OPTION_hda;
5125 hd_filename[hd_index] = optarg;
5126 if (hd_index == cdrom_index)
5127 cdrom_index = -1;
5128 }
fc01f7e7 5129 break;
cd6f1169 5130 case QEMU_OPTION_snapshot:
33e3963e
FB
5131 snapshot = 1;
5132 break;
cd6f1169 5133 case QEMU_OPTION_hdachs:
330d0414 5134 {
330d0414
FB
5135 const char *p;
5136 p = optarg;
5137 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
5138 if (cyls < 1 || cyls > 16383)
5139 goto chs_fail;
330d0414
FB
5140 if (*p != ',')
5141 goto chs_fail;
5142 p++;
5143 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
5144 if (heads < 1 || heads > 16)
5145 goto chs_fail;
330d0414
FB
5146 if (*p != ',')
5147 goto chs_fail;
5148 p++;
5149 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
5150 if (secs < 1 || secs > 63)
5151 goto chs_fail;
5152 if (*p == ',') {
5153 p++;
5154 if (!strcmp(p, "none"))
5155 translation = BIOS_ATA_TRANSLATION_NONE;
5156 else if (!strcmp(p, "lba"))
5157 translation = BIOS_ATA_TRANSLATION_LBA;
5158 else if (!strcmp(p, "auto"))
5159 translation = BIOS_ATA_TRANSLATION_AUTO;
5160 else
5161 goto chs_fail;
5162 } else if (*p != '\0') {
c4b1fcc0 5163 chs_fail:
46d4767d
FB
5164 fprintf(stderr, "qemu: invalid physical CHS format\n");
5165 exit(1);
c4b1fcc0 5166 }
330d0414
FB
5167 }
5168 break;
cd6f1169 5169 case QEMU_OPTION_nographic:
82c643ff 5170 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8d11df9e 5171 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
a20dd508
FB
5172 nographic = 1;
5173 break;
cd6f1169 5174 case QEMU_OPTION_kernel:
a20dd508
FB
5175 kernel_filename = optarg;
5176 break;
cd6f1169 5177 case QEMU_OPTION_append:
a20dd508 5178 kernel_cmdline = optarg;
313aa567 5179 break;
cd6f1169 5180 case QEMU_OPTION_cdrom:
cc1daa40
FB
5181 if (cdrom_index >= 0) {
5182 hd_filename[cdrom_index] = optarg;
5183 }
36b486bb 5184 break;
cd6f1169 5185 case QEMU_OPTION_boot:
36b486bb 5186 boot_device = optarg[0];
9e89a4be 5187 if (boot_device != 'a' &&
6f7e9aec
FB
5188#ifdef TARGET_SPARC
5189 // Network boot
5190 boot_device != 'n' &&
5191#endif
c45886db 5192 boot_device != 'c' && boot_device != 'd') {
36b486bb
FB
5193 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5194 exit(1);
5195 }
5196 break;
cd6f1169 5197 case QEMU_OPTION_fda:
c45886db
FB
5198 fd_filename[0] = optarg;
5199 break;
cd6f1169 5200 case QEMU_OPTION_fdb:
c45886db
FB
5201 fd_filename[1] = optarg;
5202 break;
cd6f1169 5203 case QEMU_OPTION_no_code_copy:
77fef8c1
FB
5204 code_copy_enabled = 0;
5205 break;
7c9d8e07
FB
5206 case QEMU_OPTION_net:
5207 if (nb_net_clients >= MAX_NET_CLIENTS) {
5208 fprintf(stderr, "qemu: too many network clients\n");
c4b1fcc0
FB
5209 exit(1);
5210 }
7c9d8e07
FB
5211 pstrcpy(net_clients[nb_net_clients],
5212 sizeof(net_clients[0]),
5213 optarg);
5214 nb_net_clients++;
702c651c 5215 break;
c7f74643
FB
5216#ifdef CONFIG_SLIRP
5217 case QEMU_OPTION_tftp:
c7f74643 5218 tftp_prefix = optarg;
9bf05444 5219 break;
c94c8d64 5220#ifndef _WIN32
9d728e8c
FB
5221 case QEMU_OPTION_smb:
5222 net_slirp_smb(optarg);
5223 break;
c94c8d64 5224#endif
9bf05444
FB
5225 case QEMU_OPTION_redir:
5226 net_slirp_redir(optarg);
5227 break;
c7f74643 5228#endif
1d14ffa9 5229#ifdef HAS_AUDIO
1d14ffa9
FB
5230 case QEMU_OPTION_audio_help:
5231 AUD_help ();
5232 exit (0);
5233 break;
5234 case QEMU_OPTION_soundhw:
5235 select_soundhw (optarg);
5236 break;
5237#endif
cd6f1169 5238 case QEMU_OPTION_h:
0824d6fc 5239 help();
cd6f1169
FB
5240 break;
5241 case QEMU_OPTION_m:
5242 ram_size = atoi(optarg) * 1024 * 1024;
5243 if (ram_size <= 0)
5244 help();
5245 if (ram_size > PHYS_RAM_MAX_SIZE) {
5246 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5247 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5248 exit(1);
5249 }
5250 break;
5251 case QEMU_OPTION_d:
5252 {
5253 int mask;
5254 CPULogItem *item;
5255
5256 mask = cpu_str_to_log_mask(optarg);
5257 if (!mask) {
5258 printf("Log items (comma separated):\n");
f193c797
FB
5259 for(item = cpu_log_items; item->mask != 0; item++) {
5260 printf("%-10s %s\n", item->name, item->help);
5261 }
5262 exit(1);
cd6f1169
FB
5263 }
5264 cpu_set_log(mask);
f193c797 5265 }
cd6f1169 5266 break;
67b915a5 5267#ifdef CONFIG_GDBSTUB
cd6f1169
FB
5268 case QEMU_OPTION_s:
5269 use_gdbstub = 1;
5270 break;
5271 case QEMU_OPTION_p:
5272 gdbstub_port = atoi(optarg);
5273 break;
67b915a5 5274#endif
cd6f1169
FB
5275 case QEMU_OPTION_L:
5276 bios_dir = optarg;
5277 break;
5278 case QEMU_OPTION_S:
5279 start_emulation = 0;
5280 break;
3d11d0eb
FB
5281 case QEMU_OPTION_k:
5282 keyboard_layout = optarg;
5283 break;
ee22c2f7
FB
5284 case QEMU_OPTION_localtime:
5285 rtc_utc = 0;
5286 break;
1f04275e
FB
5287 case QEMU_OPTION_cirrusvga:
5288 cirrus_vga_enabled = 1;
5289 break;
1bfe856e
FB
5290 case QEMU_OPTION_std_vga:
5291 cirrus_vga_enabled = 0;
5292 break;
e9b137c2
FB
5293 case QEMU_OPTION_g:
5294 {
5295 const char *p;
5296 int w, h, depth;
5297 p = optarg;
5298 w = strtol(p, (char **)&p, 10);
5299 if (w <= 0) {
5300 graphic_error:
5301 fprintf(stderr, "qemu: invalid resolution or depth\n");
5302 exit(1);
5303 }
5304 if (*p != 'x')
5305 goto graphic_error;
5306 p++;
5307 h = strtol(p, (char **)&p, 10);
5308 if (h <= 0)
5309 goto graphic_error;
5310 if (*p == 'x') {
5311 p++;
5312 depth = strtol(p, (char **)&p, 10);
5313 if (depth != 8 && depth != 15 && depth != 16 &&
5314 depth != 24 && depth != 32)
5315 goto graphic_error;
5316 } else if (*p == '\0') {
5317 depth = graphic_depth;
5318 } else {
5319 goto graphic_error;
5320 }
5321
5322 graphic_width = w;
5323 graphic_height = h;
5324 graphic_depth = depth;
5325 }
5326 break;
82c643ff
FB
5327 case QEMU_OPTION_monitor:
5328 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5329 break;
5330 case QEMU_OPTION_serial:
8d11df9e
FB
5331 if (serial_device_index >= MAX_SERIAL_PORTS) {
5332 fprintf(stderr, "qemu: too many serial ports\n");
5333 exit(1);
5334 }
5335 pstrcpy(serial_devices[serial_device_index],
5336 sizeof(serial_devices[0]), optarg);
5337 serial_device_index++;
82c643ff 5338 break;
6508fe59
FB
5339 case QEMU_OPTION_parallel:
5340 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5341 fprintf(stderr, "qemu: too many parallel ports\n");
5342 exit(1);
5343 }
5344 pstrcpy(parallel_devices[parallel_device_index],
5345 sizeof(parallel_devices[0]), optarg);
5346 parallel_device_index++;
5347 break;
d63d307f
FB
5348 case QEMU_OPTION_loadvm:
5349 loadvm = optarg;
5350 break;
5351 case QEMU_OPTION_full_screen:
5352 full_screen = 1;
5353 break;
f7cce898
FB
5354 case QEMU_OPTION_pidfile:
5355 create_pidfile(optarg);
5356 break;
a09db21f
FB
5357#ifdef TARGET_I386
5358 case QEMU_OPTION_win2k_hack:
5359 win2k_install_hack = 1;
5360 break;
5361#endif
d993e026
FB
5362#ifdef USE_KQEMU
5363 case QEMU_OPTION_no_kqemu:
5364 kqemu_allowed = 0;
5365 break;
89bfc105
FB
5366 case QEMU_OPTION_kernel_kqemu:
5367 kqemu_allowed = 2;
5368 break;
d993e026 5369#endif
bb36d470
FB
5370 case QEMU_OPTION_usb:
5371 usb_enabled = 1;
5372 break;
a594cfbf
FB
5373 case QEMU_OPTION_usbdevice:
5374 usb_enabled = 1;
5375 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5376 fprintf(stderr, "Too many USB devices\n");
5377 exit(1);
5378 }
5379 pstrcpy(usb_devices[usb_devices_index],
5380 sizeof(usb_devices[usb_devices_index]),
5381 optarg);
5382 usb_devices_index++;
5383 break;
6a00d601
FB
5384 case QEMU_OPTION_smp:
5385 smp_cpus = atoi(optarg);
ba3c64fb 5386 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6a00d601
FB
5387 fprintf(stderr, "Invalid number of CPUs\n");
5388 exit(1);
5389 }
5390 break;
24236869
FB
5391 case QEMU_OPTION_vnc:
5392 vnc_display = atoi(optarg);
5393 if (vnc_display < 0) {
5394 fprintf(stderr, "Invalid VNC display\n");
5395 exit(1);
5396 }
5397 break;
cd6f1169 5398 }
0824d6fc
FB
5399 }
5400 }
330d0414 5401
ff3fbb30
FB
5402#ifdef USE_KQEMU
5403 if (smp_cpus > 1)
5404 kqemu_allowed = 0;
5405#endif
a20dd508 5406 linux_boot = (kernel_filename != NULL);
330d0414 5407
cc1daa40
FB
5408 if (!linux_boot &&
5409 hd_filename[0] == '\0' &&
5410 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
c45886db 5411 fd_filename[0] == '\0')
0824d6fc 5412 help();
8f2b1fb0
FB
5413
5414 /* boot to cd by default if no hard disk */
d0309311
FB
5415 if (hd_filename[0] == '\0' && boot_device == 'c') {
5416 if (fd_filename[0] != '\0')
5417 boot_device = 'a';
5418 else
5419 boot_device = 'd';
5420 }
0824d6fc 5421
dc887a4d
FB
5422#if !defined(CONFIG_SOFTMMU)
5423 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5424 {
5425 static uint8_t stdout_buf[4096];
5426 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5427 }
5428#else
b118d61e 5429 setvbuf(stdout, NULL, _IOLBF, 0);
dc887a4d 5430#endif
7c9d8e07 5431
fd1dff4b
FB
5432#ifdef _WIN32
5433 socket_init();
5434#endif
5435
7c9d8e07
FB
5436 /* init network clients */
5437 if (nb_net_clients == 0) {
5438 /* if no clients, we use a default config */
5439 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5440 "nic");
5441 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5442 "user");
5443 nb_net_clients = 2;
c20709aa
FB
5444 }
5445
7c9d8e07
FB
5446 for(i = 0;i < nb_net_clients; i++) {
5447 if (net_client_init(net_clients[i]) < 0)
5448 exit(1);
702c651c 5449 }
f1510b2c 5450
0824d6fc 5451 /* init the memory */
0ced6589 5452 phys_ram_size = ram_size + vga_ram_size + bios_size;
7f7f9873
FB
5453
5454#ifdef CONFIG_SOFTMMU
d993e026 5455 phys_ram_base = qemu_vmalloc(phys_ram_size);
7f7f9873
FB
5456 if (!phys_ram_base) {
5457 fprintf(stderr, "Could not allocate physical memory\n");
0824d6fc
FB
5458 exit(1);
5459 }
7f7f9873
FB
5460#else
5461 /* as we must map the same page at several addresses, we must use
5462 a fd */
5463 {
5464 const char *tmpdir;
5465
5466 tmpdir = getenv("QEMU_TMPDIR");
5467 if (!tmpdir)
5468 tmpdir = "/tmp";
5469 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5470 if (mkstemp(phys_ram_file) < 0) {
5471 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5472 phys_ram_file);
5473 exit(1);
5474 }
5475 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5476 if (phys_ram_fd < 0) {
5477 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5478 phys_ram_file);
5479 exit(1);
5480 }
1ccde1cb 5481 ftruncate(phys_ram_fd, phys_ram_size);
7f7f9873 5482 unlink(phys_ram_file);
1ccde1cb
FB
5483 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5484 phys_ram_size,
7f7f9873
FB
5485 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5486 phys_ram_fd, 0);
5487 if (phys_ram_base == MAP_FAILED) {
5488 fprintf(stderr, "Could not map physical memory\n");
5489 exit(1);
5490 }
5491 }
5492#endif
0824d6fc 5493
c4b1fcc0 5494 /* we always create the cdrom drive, even if no disk is there */
5905b2e5 5495 bdrv_init();
cc1daa40
FB
5496 if (cdrom_index >= 0) {
5497 bs_table[cdrom_index] = bdrv_new("cdrom");
5498 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
c4b1fcc0
FB
5499 }
5500
33e3963e
FB
5501 /* open the virtual block devices */
5502 for(i = 0; i < MAX_DISKS; i++) {
5503 if (hd_filename[i]) {
33e3963e 5504 if (!bs_table[i]) {
c4b1fcc0
FB
5505 char buf[64];
5506 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5507 bs_table[i] = bdrv_new(buf);
5508 }
5509 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5905b2e5 5510 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
33e3963e
FB
5511 hd_filename[i]);
5512 exit(1);
5513 }
46d4767d 5514 if (i == 0 && cyls != 0) {
c4b1fcc0 5515 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
46d4767d
FB
5516 bdrv_set_translation_hint(bs_table[i], translation);
5517 }
c4b1fcc0
FB
5518 }
5519 }
5520
5521 /* we always create at least one floppy disk */
5522 fd_table[0] = bdrv_new("fda");
5523 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5524
5525 for(i = 0; i < MAX_FD; i++) {
5526 if (fd_filename[i]) {
5527 if (!fd_table[i]) {
5528 char buf[64];
5529 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5530 fd_table[i] = bdrv_new(buf);
5531 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5532 }
5533 if (fd_filename[i] != '\0') {
5534 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
c20709aa 5535 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
c4b1fcc0
FB
5536 fd_filename[i]);
5537 exit(1);
5538 }
5539 }
33e3963e
FB
5540 }
5541 }
5542
a594cfbf
FB
5543 /* init USB devices */
5544 if (usb_enabled) {
5545 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5546 for(i = 0; i < usb_devices_index; i++) {
5547 if (usb_device_add(usb_devices[i]) < 0) {
5548 fprintf(stderr, "Warning: could not add USB device %s\n",
5549 usb_devices[i]);
5550 }
5551 }
5552 }
5553
6a00d601 5554 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
8a7ddc38
FB
5555 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5556
330d0414 5557 init_ioports();
80cabfad 5558 cpu_calibrate_ticks();
0824d6fc 5559
313aa567 5560 /* terminal init */
a20dd508 5561 if (nographic) {
313aa567 5562 dumb_display_init(ds);
45a8f3ca 5563 } else if (vnc_display != -1) {
24236869 5564 vnc_display_init(ds, vnc_display);
313aa567 5565 } else {
5b0753e0 5566#if defined(CONFIG_SDL)
d63d307f 5567 sdl_display_init(ds, full_screen);
5b0753e0
FB
5568#elif defined(CONFIG_COCOA)
5569 cocoa_display_init(ds, full_screen);
313aa567
FB
5570#else
5571 dumb_display_init(ds);
5572#endif
5573 }
0824d6fc 5574
82c643ff
FB
5575 monitor_hd = qemu_chr_open(monitor_device);
5576 if (!monitor_hd) {
5577 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5578 exit(1);
5579 }
5580 monitor_init(monitor_hd, !nographic);
5581
8d11df9e
FB
5582 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5583 if (serial_devices[i][0] != '\0') {
5584 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5585 if (!serial_hds[i]) {
5586 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5587 serial_devices[i]);
5588 exit(1);
5589 }
5590 if (!strcmp(serial_devices[i], "vc"))
5591 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5592 }
82c643ff 5593 }
82c643ff 5594
6508fe59
FB
5595 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5596 if (parallel_devices[i][0] != '\0') {
5597 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5598 if (!parallel_hds[i]) {
5599 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5600 parallel_devices[i]);
5601 exit(1);
5602 }
5603 if (!strcmp(parallel_devices[i], "vc"))
5604 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5605 }
5606 }
5607
0824d6fc 5608 /* setup cpu signal handlers for MMU / self modifying code handling */
77fef8c1 5609#if !defined(CONFIG_SOFTMMU)
8a7ddc38 5610
77fef8c1
FB
5611#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5612 {
5613 stack_t stk;
73332e5c 5614 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
77fef8c1
FB
5615 stk.ss_sp = signal_stack;
5616 stk.ss_size = SIGNAL_STACK_SIZE;
5617 stk.ss_flags = 0;
5618
5619 if (sigaltstack(&stk, NULL) < 0) {
5620 perror("sigaltstack");
5621 exit(1);
5622 }
5623 }
5624#endif
8a7ddc38
FB
5625 {
5626 struct sigaction act;
77fef8c1 5627
8a7ddc38
FB
5628 sigfillset(&act.sa_mask);
5629 act.sa_flags = SA_SIGINFO;
77fef8c1 5630#if defined (TARGET_I386) && defined(USE_CODE_COPY)
8a7ddc38 5631 act.sa_flags |= SA_ONSTACK;
77fef8c1 5632#endif
8a7ddc38
FB
5633 act.sa_sigaction = host_segv_handler;
5634 sigaction(SIGSEGV, &act, NULL);
5635 sigaction(SIGBUS, &act, NULL);
77fef8c1 5636#if defined (TARGET_I386) && defined(USE_CODE_COPY)
8a7ddc38 5637 sigaction(SIGFPE, &act, NULL);
77fef8c1 5638#endif
8a7ddc38 5639 }
3a51dee6 5640#endif
0824d6fc 5641
67b915a5 5642#ifndef _WIN32
8a7ddc38
FB
5643 {
5644 struct sigaction act;
5645 sigfillset(&act.sa_mask);
5646 act.sa_flags = 0;
5647 act.sa_handler = SIG_IGN;
5648 sigaction(SIGPIPE, &act, NULL);
5649 }
67b915a5 5650#endif
73332e5c
FB
5651 init_timers();
5652
cc1daa40
FB
5653 machine->init(ram_size, vga_ram_size, boot_device,
5654 ds, fd_filename, snapshot,
5655 kernel_filename, kernel_cmdline, initrd_filename);
73332e5c 5656
8a7ddc38
FB
5657 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5658 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7f7f9873 5659
67b915a5 5660#ifdef CONFIG_GDBSTUB
b4608c04 5661 if (use_gdbstub) {
8a7ddc38
FB
5662 if (gdbserver_start(gdbstub_port) < 0) {
5663 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5664 gdbstub_port);
5665 exit(1);
5666 } else {
5667 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5668 }
67b915a5
FB
5669 } else
5670#endif
d63d307f
FB
5671 if (loadvm)
5672 qemu_loadvm(loadvm);
5673
67b915a5 5674 {
5905b2e5
FB
5675 /* XXX: simplify init */
5676 read_passwords();
5677 if (start_emulation) {
5678 vm_start();
5679 }
0824d6fc 5680 }
8a7ddc38 5681 main_loop();
40c3bac3 5682 quit_timers();
0824d6fc
FB
5683 return 0;
5684}