]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
machine struct - use C99 initializers (Jes Sorensen)
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 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 */
87ecb68b
PB
24#include "hw/hw.h"
25#include "hw/boards.h"
26#include "hw/usb.h"
27#include "hw/pcmcia.h"
28#include "hw/pc.h"
87ecb68b
PB
29#include "hw/audiodev.h"
30#include "hw/isa.h"
2e4d9fb1 31#include "hw/baum.h"
1ae26a18 32#include "hw/bt.h"
87ecb68b
PB
33#include "net.h"
34#include "console.h"
35#include "sysemu.h"
36#include "gdbstub.h"
37#include "qemu-timer.h"
38#include "qemu-char.h"
39#include "block.h"
40#include "audio/audio.h"
67b915a5 41
0824d6fc 42#include <unistd.h>
0824d6fc
FB
43#include <fcntl.h>
44#include <signal.h>
45#include <time.h>
0824d6fc 46#include <errno.h>
67b915a5 47#include <sys/time.h>
c88676f8 48#include <zlib.h>
67b915a5
FB
49
50#ifndef _WIN32
51#include <sys/times.h>
f1510b2c 52#include <sys/wait.h>
67b915a5
FB
53#include <termios.h>
54#include <sys/poll.h>
55#include <sys/mman.h>
f1510b2c
FB
56#include <sys/ioctl.h>
57#include <sys/socket.h>
c94c8d64 58#include <netinet/in.h>
9d728e8c 59#include <dirent.h>
7c9d8e07 60#include <netdb.h>
cb4b976b
TS
61#include <sys/select.h>
62#include <arpa/inet.h>
7d3505c5
FB
63#ifdef _BSD
64#include <sys/stat.h>
128ab2ff 65#if !defined(__APPLE__) && !defined(__OpenBSD__)
7d3505c5 66#include <libutil.h>
83fb7adf 67#endif
128ab2ff
BS
68#ifdef __OpenBSD__
69#include <net/if.h>
70#endif
5c40d2bd
TS
71#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72#include <freebsd/stdlib.h>
7d3505c5 73#else
223f0d72 74#ifdef __linux__
f1510b2c
FB
75#include <linux/if.h>
76#include <linux/if_tun.h>
7d3505c5
FB
77#include <pty.h>
78#include <malloc.h>
fd872598 79#include <linux/rtc.h>
bd494f4c
TS
80
81/* For the benefit of older linux systems which don't supply it,
82 we use a local copy of hpet.h. */
83/* #include <linux/hpet.h> */
84#include "hpet.h"
85
e57a8c0e 86#include <linux/ppdev.h>
5867c88a 87#include <linux/parport.h>
223f0d72
BS
88#endif
89#ifdef __sun__
d5d10bc3
TS
90#include <sys/stat.h>
91#include <sys/ethernet.h>
92#include <sys/sockio.h>
d5d10bc3
TS
93#include <netinet/arp.h>
94#include <netinet/in.h>
95#include <netinet/in_systm.h>
96#include <netinet/ip.h>
97#include <netinet/ip_icmp.h> // must come after ip.h
98#include <netinet/udp.h>
99#include <netinet/tcp.h>
100#include <net/if.h>
101#include <syslog.h>
102#include <stropts.h>
67b915a5 103#endif
7d3505c5 104#endif
ec530c81 105#endif
67b915a5 106
03ff3ca3
AL
107#include "qemu_socket.h"
108
c20709aa
FB
109#if defined(CONFIG_SLIRP)
110#include "libslirp.h"
111#endif
112
9892fbfb
BS
113#if defined(__OpenBSD__)
114#include <util.h>
115#endif
116
8a16d273
TS
117#if defined(CONFIG_VDE)
118#include <libvdeplug.h>
119#endif
120
67b915a5 121#ifdef _WIN32
7d3505c5 122#include <malloc.h>
67b915a5 123#include <sys/timeb.h>
4fddf62a 124#include <mmsystem.h>
67b915a5
FB
125#define getopt_long_only getopt_long
126#define memalign(align, size) malloc(size)
127#endif
128
73332e5c 129#ifdef CONFIG_SDL
96bcd4f8 130#ifdef __APPLE__
83fb7adf 131#include <SDL/SDL.h>
96bcd4f8 132#endif
73332e5c 133#endif /* CONFIG_SDL */
0824d6fc 134
5b0753e0
FB
135#ifdef CONFIG_COCOA
136#undef main
137#define main qemu_main
138#endif /* CONFIG_COCOA */
139
0824d6fc 140#include "disas.h"
fc01f7e7 141
8a7ddc38 142#include "exec-all.h"
0824d6fc 143
5a67135a 144#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
b46a8906 145#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
a14d6c8c
PB
146#ifdef __sun__
147#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
148#else
149#define SMBD_COMMAND "/usr/sbin/smbd"
150#endif
f1510b2c 151
0824d6fc 152//#define DEBUG_UNUSED_IOPORT
fd872598 153//#define DEBUG_IOPORT
9dc63a1e
BS
154//#define DEBUG_NET
155//#define DEBUG_SLIRP
330d0414 156
77d4bc34
FB
157#ifdef TARGET_PPC
158#define DEFAULT_RAM_SIZE 144
159#else
1bfe856e 160#define DEFAULT_RAM_SIZE 128
77d4bc34 161#endif
313aa567 162
0d92ed30
PB
163/* Max number of USB devices that can be specified on the commandline. */
164#define MAX_USB_CMDLINE 8
165
7dea1da4
FB
166/* XXX: use a two level table to limit memory usage */
167#define MAX_IOPORTS 65536
0824d6fc 168
80cabfad 169const char *bios_dir = CONFIG_QEMU_SHAREDIR;
1192dad8 170const char *bios_name = NULL;
dbed7e40
BS
171static void *ioport_opaque[MAX_IOPORTS];
172static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
e4bcb14c 174/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
faea38e7 175 to store the VM snapshots */
e4bcb14c
TS
176DriveInfo drives_table[MAX_DRIVES+1];
177int nb_drives;
faea38e7 178/* point to the block driver where the snapshots are managed */
dbed7e40
BS
179static BlockDriverState *bs_snapshots;
180static int vga_ram_size;
cb5a7aa8 181enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
313aa567 182static DisplayState display_state;
a20dd508 183int nographic;
dbed7e40 184static int curses;
3d11d0eb 185const char* keyboard_layout = NULL;
313aa567 186int64_t ticks_per_sec;
00f82b8a 187ram_addr_t ram_size;
c4b1fcc0 188int nb_nics;
7c9d8e07 189NICInfo nd_table[MAX_NICS];
8a7ddc38 190int vm_running;
f6503059
AZ
191static int rtc_utc = 1;
192static int rtc_date_offset = -1; /* -1 means no change */
1bfe856e 193int cirrus_vga_enabled = 1;
d34cab9f 194int vmsvga_enabled = 0;
d827220b
FB
195#ifdef TARGET_SPARC
196int graphic_width = 1024;
197int graphic_height = 768;
eee0b836 198int graphic_depth = 8;
d827220b 199#else
1bfe856e
FB
200int graphic_width = 800;
201int graphic_height = 600;
e9b137c2 202int graphic_depth = 15;
eee0b836 203#endif
dbed7e40
BS
204static int full_screen = 0;
205static int no_frame = 0;
667accab 206int no_quit = 0;
8d11df9e 207CharDriverState *serial_hds[MAX_SERIAL_PORTS];
6508fe59 208CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
a09db21f
FB
209#ifdef TARGET_I386
210int win2k_install_hack = 0;
211#endif
bb36d470 212int usb_enabled = 0;
7c9d8e07 213static VLANState *first_vlan;
6a00d601 214int smp_cpus = 1;
73fc9742 215const char *vnc_display;
d3e9db93 216#if defined(TARGET_SPARC)
ba3c64fb 217#define MAX_CPUS 16
d3e9db93
FB
218#elif defined(TARGET_I386)
219#define MAX_CPUS 255
ba3c64fb 220#else
d3e9db93 221#define MAX_CPUS 1
ba3c64fb 222#endif
6515b203 223int acpi_enabled = 1;
52ca8d6a 224int fd_bootchk = 1;
d1beab82 225int no_reboot = 0;
b2f76161 226int no_shutdown = 0;
9467cd46 227int cursor_hide = 1;
a171fe39 228int graphic_rotate = 0;
71e3ceb8 229int daemonize = 0;
9ae02555
TS
230const char *option_rom[MAX_OPTION_ROMS];
231int nb_option_roms;
8e71621f 232int semihosting_enabled = 0;
2b8f2d41
AZ
233#ifdef TARGET_ARM
234int old_param = 0;
235#endif
c35734b2 236const char *qemu_name;
3780e197 237int alt_grab = 0;
66508601
BS
238#ifdef TARGET_SPARC
239unsigned int nb_prom_envs = 0;
240const char *prom_envs[MAX_PROM_ENVS];
241#endif
dbed7e40
BS
242static int nb_drives_opt;
243static struct drive_opt {
609497ab
AZ
244 const char *file;
245 char opt[1024];
246} drives_opt[MAX_DRIVES];
0824d6fc 247
ee5605e5
AZ
248static CPUState *cur_cpu;
249static CPUState *next_cpu;
76ea08f9 250static int event_pending = 1;
bf20dc07 251/* Conversion factor from emulated instructions to virtual clock ticks. */
2e70f6ef 252static int icount_time_shift;
bf20dc07 253/* Arbitrarily pick 1MIPS as the minimum allowable speed. */
2e70f6ef
PB
254#define MAX_ICOUNT_SHIFT 10
255/* Compensate for varying guest execution speed. */
256static int64_t qemu_icount_bias;
dbed7e40
BS
257static QEMUTimer *icount_rt_timer;
258static QEMUTimer *icount_vm_timer;
ee5605e5 259
8fcb1b90
BS
260uint8_t qemu_uuid[16];
261
aeb30be6
AZ
262#define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
263
0824d6fc 264/***********************************************************/
26aa7d72
FB
265/* x86 ISA bus support */
266
267target_phys_addr_t isa_mem_base = 0;
3de388f6 268PicState2 *isa_pic;
0824d6fc 269
477e3edf
AL
270static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
271static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
272
273static uint32_t ioport_read(int index, uint32_t address)
274{
275 static IOPortReadFunc *default_func[3] = {
276 default_ioport_readb,
277 default_ioport_readw,
278 default_ioport_readl
279 };
280 IOPortReadFunc *func = ioport_read_table[index][address];
281 if (!func)
282 func = default_func[index];
283 return func(ioport_opaque[address], address);
284}
285
286static void ioport_write(int index, uint32_t address, uint32_t data)
287{
288 static IOPortWriteFunc *default_func[3] = {
289 default_ioport_writeb,
290 default_ioport_writew,
291 default_ioport_writel
292 };
293 IOPortWriteFunc *func = ioport_write_table[index][address];
294 if (!func)
295 func = default_func[index];
296 func(ioport_opaque[address], address, data);
297}
298
9596ebb7 299static uint32_t default_ioport_readb(void *opaque, uint32_t address)
0824d6fc
FB
300{
301#ifdef DEBUG_UNUSED_IOPORT
1196be37 302 fprintf(stderr, "unused inb: port=0x%04x\n", address);
0824d6fc 303#endif
fc01f7e7 304 return 0xff;
0824d6fc
FB
305}
306
9596ebb7 307static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
0824d6fc
FB
308{
309#ifdef DEBUG_UNUSED_IOPORT
1196be37 310 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
0824d6fc
FB
311#endif
312}
313
314/* default is to make two byte accesses */
9596ebb7 315static uint32_t default_ioport_readw(void *opaque, uint32_t address)
0824d6fc
FB
316{
317 uint32_t data;
477e3edf 318 data = ioport_read(0, address);
db45c29a 319 address = (address + 1) & (MAX_IOPORTS - 1);
477e3edf 320 data |= ioport_read(0, address) << 8;
0824d6fc
FB
321 return data;
322}
323
9596ebb7 324static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
0824d6fc 325{
477e3edf 326 ioport_write(0, address, data & 0xff);
db45c29a 327 address = (address + 1) & (MAX_IOPORTS - 1);
477e3edf 328 ioport_write(0, address, (data >> 8) & 0xff);
0824d6fc
FB
329}
330
9596ebb7 331static uint32_t default_ioport_readl(void *opaque, uint32_t address)
0824d6fc 332{
fc01f7e7 333#ifdef DEBUG_UNUSED_IOPORT
1196be37 334 fprintf(stderr, "unused inl: port=0x%04x\n", address);
fc01f7e7
FB
335#endif
336 return 0xffffffff;
0824d6fc
FB
337}
338
9596ebb7 339static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
0824d6fc 340{
fc01f7e7 341#ifdef DEBUG_UNUSED_IOPORT
1196be37 342 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
fc01f7e7 343#endif
0824d6fc
FB
344}
345
fc01f7e7 346/* size is the word size in byte */
5fafdf24 347int register_ioport_read(int start, int length, int size,
c4b1fcc0 348 IOPortReadFunc *func, void *opaque)
f1510b2c 349{
fc01f7e7 350 int i, bsize;
f1510b2c 351
c4b1fcc0 352 if (size == 1) {
fc01f7e7 353 bsize = 0;
c4b1fcc0 354 } else if (size == 2) {
fc01f7e7 355 bsize = 1;
c4b1fcc0 356 } else if (size == 4) {
fc01f7e7 357 bsize = 2;
c4b1fcc0 358 } else {
88fdf56f 359 hw_error("register_ioport_read: invalid size");
fc01f7e7 360 return -1;
c4b1fcc0
FB
361 }
362 for(i = start; i < start + length; i += size) {
fc01f7e7 363 ioport_read_table[bsize][i] = func;
c4b1fcc0 364 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
88fdf56f 365 hw_error("register_ioport_read: invalid opaque");
c4b1fcc0
FB
366 ioport_opaque[i] = opaque;
367 }
f1510b2c
FB
368 return 0;
369}
370
fc01f7e7 371/* size is the word size in byte */
5fafdf24 372int register_ioport_write(int start, int length, int size,
c4b1fcc0 373 IOPortWriteFunc *func, void *opaque)
f1510b2c 374{
fc01f7e7 375 int i, bsize;
f1510b2c 376
c4b1fcc0 377 if (size == 1) {
fc01f7e7 378 bsize = 0;
c4b1fcc0 379 } else if (size == 2) {
fc01f7e7 380 bsize = 1;
c4b1fcc0 381 } else if (size == 4) {
fc01f7e7 382 bsize = 2;
c4b1fcc0 383 } else {
88fdf56f 384 hw_error("register_ioport_write: invalid size");
fc01f7e7 385 return -1;
c4b1fcc0
FB
386 }
387 for(i = start; i < start + length; i += size) {
fc01f7e7 388 ioport_write_table[bsize][i] = func;
88fdf56f
AZ
389 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
390 hw_error("register_ioport_write: invalid opaque");
c4b1fcc0
FB
391 ioport_opaque[i] = opaque;
392 }
f1510b2c
FB
393 return 0;
394}
395
69b91039
FB
396void isa_unassign_ioport(int start, int length)
397{
398 int i;
399
400 for(i = start; i < start + length; i++) {
401 ioport_read_table[0][i] = default_ioport_readb;
402 ioport_read_table[1][i] = default_ioport_readw;
403 ioport_read_table[2][i] = default_ioport_readl;
404
405 ioport_write_table[0][i] = default_ioport_writeb;
406 ioport_write_table[1][i] = default_ioport_writew;
407 ioport_write_table[2][i] = default_ioport_writel;
408 }
409}
410
20f32282
FB
411/***********************************************************/
412
c45886db 413void cpu_outb(CPUState *env, int addr, int val)
0824d6fc 414{
fd872598
FB
415#ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "outb: %04x %02x\n", addr, val);
3b46e624 418#endif
477e3edf 419 ioport_write(0, addr, val);
89bfc105
FB
420#ifdef USE_KQEMU
421 if (env)
422 env->last_io_time = cpu_get_time_fast();
423#endif
0824d6fc
FB
424}
425
c45886db 426void cpu_outw(CPUState *env, int addr, int val)
0824d6fc 427{
fd872598
FB
428#ifdef DEBUG_IOPORT
429 if (loglevel & CPU_LOG_IOPORT)
430 fprintf(logfile, "outw: %04x %04x\n", addr, val);
3b46e624 431#endif
477e3edf 432 ioport_write(1, addr, val);
89bfc105
FB
433#ifdef USE_KQEMU
434 if (env)
435 env->last_io_time = cpu_get_time_fast();
436#endif
0824d6fc
FB
437}
438
c45886db 439void cpu_outl(CPUState *env, int addr, int val)
0824d6fc 440{
fd872598
FB
441#ifdef DEBUG_IOPORT
442 if (loglevel & CPU_LOG_IOPORT)
443 fprintf(logfile, "outl: %04x %08x\n", addr, val);
444#endif
477e3edf 445 ioport_write(2, addr, val);
89bfc105
FB
446#ifdef USE_KQEMU
447 if (env)
448 env->last_io_time = cpu_get_time_fast();
449#endif
0824d6fc
FB
450}
451
c45886db 452int cpu_inb(CPUState *env, int addr)
0824d6fc 453{
fd872598 454 int val;
477e3edf 455 val = ioport_read(0, addr);
fd872598
FB
456#ifdef DEBUG_IOPORT
457 if (loglevel & CPU_LOG_IOPORT)
458 fprintf(logfile, "inb : %04x %02x\n", addr, val);
89bfc105
FB
459#endif
460#ifdef USE_KQEMU
461 if (env)
462 env->last_io_time = cpu_get_time_fast();
fd872598
FB
463#endif
464 return val;
0824d6fc
FB
465}
466
c45886db 467int cpu_inw(CPUState *env, int addr)
0824d6fc 468{
fd872598 469 int val;
477e3edf 470 val = ioport_read(1, addr);
fd872598
FB
471#ifdef DEBUG_IOPORT
472 if (loglevel & CPU_LOG_IOPORT)
473 fprintf(logfile, "inw : %04x %04x\n", addr, val);
89bfc105
FB
474#endif
475#ifdef USE_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
fd872598
FB
478#endif
479 return val;
0824d6fc
FB
480}
481
c45886db 482int cpu_inl(CPUState *env, int addr)
0824d6fc 483{
fd872598 484 int val;
477e3edf 485 val = ioport_read(2, addr);
fd872598
FB
486#ifdef DEBUG_IOPORT
487 if (loglevel & CPU_LOG_IOPORT)
488 fprintf(logfile, "inl : %04x %08x\n", addr, val);
89bfc105
FB
489#endif
490#ifdef USE_KQEMU
491 if (env)
492 env->last_io_time = cpu_get_time_fast();
fd872598
FB
493#endif
494 return val;
0824d6fc
FB
495}
496
497/***********************************************************/
0824d6fc
FB
498void hw_error(const char *fmt, ...)
499{
500 va_list ap;
6a00d601 501 CPUState *env;
0824d6fc
FB
502
503 va_start(ap, fmt);
504 fprintf(stderr, "qemu: hardware error: ");
505 vfprintf(stderr, fmt, ap);
506 fprintf(stderr, "\n");
6a00d601
FB
507 for(env = first_cpu; env != NULL; env = env->next_cpu) {
508 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
0824d6fc 509#ifdef TARGET_I386
6a00d601 510 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
c45886db 511#else
6a00d601 512 cpu_dump_state(env, stderr, fprintf, 0);
0824d6fc 513#endif
6a00d601 514 }
0824d6fc
FB
515 va_end(ap);
516 abort();
517}
518
63066f4f
FB
519/***********************************************************/
520/* keyboard/mouse */
521
522static QEMUPutKBDEvent *qemu_put_kbd_event;
523static void *qemu_put_kbd_event_opaque;
455204eb
TS
524static QEMUPutMouseEntry *qemu_put_mouse_event_head;
525static QEMUPutMouseEntry *qemu_put_mouse_event_current;
63066f4f
FB
526
527void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
528{
529 qemu_put_kbd_event_opaque = opaque;
530 qemu_put_kbd_event = func;
531}
532
455204eb
TS
533QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
534 void *opaque, int absolute,
535 const char *name)
63066f4f 536{
455204eb
TS
537 QEMUPutMouseEntry *s, *cursor;
538
539 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
540 if (!s)
541 return NULL;
542
543 s->qemu_put_mouse_event = func;
544 s->qemu_put_mouse_event_opaque = opaque;
545 s->qemu_put_mouse_event_absolute = absolute;
546 s->qemu_put_mouse_event_name = qemu_strdup(name);
547 s->next = NULL;
548
549 if (!qemu_put_mouse_event_head) {
550 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
551 return s;
552 }
553
554 cursor = qemu_put_mouse_event_head;
555 while (cursor->next != NULL)
556 cursor = cursor->next;
557
558 cursor->next = s;
559 qemu_put_mouse_event_current = s;
560
561 return s;
562}
563
564void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
565{
566 QEMUPutMouseEntry *prev = NULL, *cursor;
567
568 if (!qemu_put_mouse_event_head || entry == NULL)
569 return;
570
571 cursor = qemu_put_mouse_event_head;
572 while (cursor != NULL && cursor != entry) {
573 prev = cursor;
574 cursor = cursor->next;
575 }
576
577 if (cursor == NULL) // does not exist or list empty
578 return;
579 else if (prev == NULL) { // entry is head
580 qemu_put_mouse_event_head = cursor->next;
581 if (qemu_put_mouse_event_current == entry)
582 qemu_put_mouse_event_current = cursor->next;
583 qemu_free(entry->qemu_put_mouse_event_name);
584 qemu_free(entry);
585 return;
586 }
587
588 prev->next = entry->next;
589
590 if (qemu_put_mouse_event_current == entry)
591 qemu_put_mouse_event_current = prev;
592
593 qemu_free(entry->qemu_put_mouse_event_name);
594 qemu_free(entry);
63066f4f
FB
595}
596
597void kbd_put_keycode(int keycode)
598{
599 if (qemu_put_kbd_event) {
600 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
601 }
602}
603
604void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
605{
455204eb
TS
606 QEMUPutMouseEvent *mouse_event;
607 void *mouse_event_opaque;
a171fe39 608 int width;
455204eb
TS
609
610 if (!qemu_put_mouse_event_current) {
611 return;
612 }
613
614 mouse_event =
615 qemu_put_mouse_event_current->qemu_put_mouse_event;
616 mouse_event_opaque =
617 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
618
619 if (mouse_event) {
a171fe39
AZ
620 if (graphic_rotate) {
621 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
622 width = 0x7fff;
623 else
b94ed577 624 width = graphic_width - 1;
a171fe39
AZ
625 mouse_event(mouse_event_opaque,
626 width - dy, dx, dz, buttons_state);
627 } else
628 mouse_event(mouse_event_opaque,
629 dx, dy, dz, buttons_state);
63066f4f
FB
630 }
631}
632
09b26c5e
FB
633int kbd_mouse_is_absolute(void)
634{
455204eb
TS
635 if (!qemu_put_mouse_event_current)
636 return 0;
637
638 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
639}
640
641void do_info_mice(void)
642{
643 QEMUPutMouseEntry *cursor;
644 int index = 0;
645
646 if (!qemu_put_mouse_event_head) {
647 term_printf("No mouse devices connected\n");
648 return;
649 }
650
651 term_printf("Mouse devices available:\n");
652 cursor = qemu_put_mouse_event_head;
653 while (cursor != NULL) {
654 term_printf("%c Mouse #%d: %s\n",
655 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
656 index, cursor->qemu_put_mouse_event_name);
657 index++;
658 cursor = cursor->next;
659 }
660}
661
662void do_mouse_set(int index)
663{
664 QEMUPutMouseEntry *cursor;
665 int i = 0;
666
667 if (!qemu_put_mouse_event_head) {
668 term_printf("No mouse devices connected\n");
669 return;
670 }
671
672 cursor = qemu_put_mouse_event_head;
673 while (cursor != NULL && index != i) {
674 i++;
675 cursor = cursor->next;
676 }
677
678 if (cursor != NULL)
679 qemu_put_mouse_event_current = cursor;
680 else
681 term_printf("Mouse at given index not found\n");
09b26c5e
FB
682}
683
1dce7c3c
FB
684/* compute with 96 bit intermediate result: (a*b)/c */
685uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
0824d6fc 686{
1dce7c3c
FB
687 union {
688 uint64_t ll;
689 struct {
690#ifdef WORDS_BIGENDIAN
691 uint32_t high, low;
692#else
693 uint32_t low, high;
3b46e624 694#endif
1dce7c3c
FB
695 } l;
696 } u, res;
697 uint64_t rl, rh;
0824d6fc 698
1dce7c3c
FB
699 u.ll = a;
700 rl = (uint64_t)u.l.low * (uint64_t)b;
701 rh = (uint64_t)u.l.high * (uint64_t)b;
702 rh += (rl >> 32);
703 res.l.high = rh / c;
704 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
705 return res.ll;
34865134
FB
706}
707
1dce7c3c
FB
708/***********************************************************/
709/* real time host monotonic timer */
34865134 710
1dce7c3c 711#define QEMU_TIMER_BASE 1000000000LL
34865134 712
1dce7c3c 713#ifdef WIN32
0824d6fc 714
1dce7c3c 715static int64_t clock_freq;
1115dde7 716
1dce7c3c 717static void init_get_clock(void)
1115dde7 718{
a8e5ac33
FB
719 LARGE_INTEGER freq;
720 int ret;
1dce7c3c
FB
721 ret = QueryPerformanceFrequency(&freq);
722 if (ret == 0) {
723 fprintf(stderr, "Could not calibrate ticks\n");
724 exit(1);
725 }
726 clock_freq = freq.QuadPart;
1115dde7
FB
727}
728
1dce7c3c 729static int64_t get_clock(void)
b8076a74 730{
1dce7c3c
FB
731 LARGE_INTEGER ti;
732 QueryPerformanceCounter(&ti);
733 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
b8076a74
FB
734}
735
1dce7c3c 736#else
90cb9493 737
1dce7c3c
FB
738static int use_rt_clock;
739
740static void init_get_clock(void)
90cb9493 741{
1dce7c3c
FB
742 use_rt_clock = 0;
743#if defined(__linux__)
744 {
745 struct timespec ts;
746 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
747 use_rt_clock = 1;
748 }
749 }
750#endif
90cb9493
FB
751}
752
1dce7c3c 753static int64_t get_clock(void)
fdbb4691 754{
1dce7c3c
FB
755#if defined(__linux__)
756 if (use_rt_clock) {
757 struct timespec ts;
758 clock_gettime(CLOCK_MONOTONIC, &ts);
759 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
5fafdf24 760 } else
fdbb4691 761#endif
1dce7c3c
FB
762 {
763 /* XXX: using gettimeofday leads to problems if the date
764 changes, so it should be avoided. */
765 struct timeval tv;
766 gettimeofday(&tv, NULL);
767 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
768 }
fdbb4691 769}
34865134
FB
770#endif
771
2e70f6ef
PB
772/* Return the virtual CPU time, based on the instruction counter. */
773static int64_t cpu_get_icount(void)
774{
775 int64_t icount;
776 CPUState *env = cpu_single_env;;
777 icount = qemu_icount;
778 if (env) {
779 if (!can_do_io(env))
780 fprintf(stderr, "Bad clock read\n");
781 icount -= (env->icount_decr.u16.low + env->icount_extra);
782 }
783 return qemu_icount_bias + (icount << icount_time_shift);
784}
785
1dce7c3c
FB
786/***********************************************************/
787/* guest cycle counter */
788
eade0f19 789static int64_t cpu_ticks_prev;
34865134 790static int64_t cpu_ticks_offset;
1dce7c3c 791static int64_t cpu_clock_offset;
8a7ddc38 792static int cpu_ticks_enabled;
34865134 793
1dce7c3c
FB
794/* return the host CPU cycle counter and handle stop/restart */
795int64_t cpu_get_ticks(void)
34865134 796{
2e70f6ef
PB
797 if (use_icount) {
798 return cpu_get_icount();
799 }
8a7ddc38
FB
800 if (!cpu_ticks_enabled) {
801 return cpu_ticks_offset;
802 } else {
eade0f19
FB
803 int64_t ticks;
804 ticks = cpu_get_real_ticks();
805 if (cpu_ticks_prev > ticks) {
806 /* Note: non increasing ticks may happen if the host uses
807 software suspend */
808 cpu_ticks_offset += cpu_ticks_prev - ticks;
809 }
810 cpu_ticks_prev = ticks;
811 return ticks + cpu_ticks_offset;
8a7ddc38 812 }
34865134
FB
813}
814
1dce7c3c
FB
815/* return the host CPU monotonic timer and handle stop/restart */
816static int64_t cpu_get_clock(void)
817{
818 int64_t ti;
819 if (!cpu_ticks_enabled) {
820 return cpu_clock_offset;
821 } else {
822 ti = get_clock();
823 return ti + cpu_clock_offset;
824 }
825}
826
34865134
FB
827/* enable cpu_get_ticks() */
828void cpu_enable_ticks(void)
829{
8a7ddc38
FB
830 if (!cpu_ticks_enabled) {
831 cpu_ticks_offset -= cpu_get_real_ticks();
1dce7c3c 832 cpu_clock_offset -= get_clock();
8a7ddc38
FB
833 cpu_ticks_enabled = 1;
834 }
34865134
FB
835}
836
837/* disable cpu_get_ticks() : the clock is stopped. You must not call
838 cpu_get_ticks() after that. */
839void cpu_disable_ticks(void)
840{
8a7ddc38
FB
841 if (cpu_ticks_enabled) {
842 cpu_ticks_offset = cpu_get_ticks();
1dce7c3c 843 cpu_clock_offset = cpu_get_clock();
8a7ddc38
FB
844 cpu_ticks_enabled = 0;
845 }
34865134
FB
846}
847
1dce7c3c
FB
848/***********************************************************/
849/* timers */
5fafdf24 850
8a7ddc38
FB
851#define QEMU_TIMER_REALTIME 0
852#define QEMU_TIMER_VIRTUAL 1
853
854struct QEMUClock {
855 int type;
856 /* XXX: add frequency */
857};
858
859struct QEMUTimer {
860 QEMUClock *clock;
861 int64_t expire_time;
862 QEMUTimerCB *cb;
863 void *opaque;
864 struct QEMUTimer *next;
865};
866
c8994013
TS
867struct qemu_alarm_timer {
868 char const *name;
efe75411 869 unsigned int flags;
c8994013
TS
870
871 int (*start)(struct qemu_alarm_timer *t);
872 void (*stop)(struct qemu_alarm_timer *t);
efe75411 873 void (*rearm)(struct qemu_alarm_timer *t);
c8994013
TS
874 void *priv;
875};
876
efe75411 877#define ALARM_FLAG_DYNTICKS 0x1
d5d08334 878#define ALARM_FLAG_EXPIRED 0x2
efe75411
TS
879
880static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
881{
882 return t->flags & ALARM_FLAG_DYNTICKS;
883}
884
885static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
886{
887 if (!alarm_has_dynticks(t))
888 return;
889
890 t->rearm(t);
891}
892
893/* TODO: MIN_TIMER_REARM_US should be optimized */
894#define MIN_TIMER_REARM_US 250
895
c8994013 896static struct qemu_alarm_timer *alarm_timer;
8a7ddc38 897
40c3bac3 898#ifdef _WIN32
c8994013
TS
899
900struct qemu_alarm_win32 {
901 MMRESULT timerId;
902 HANDLE host_alarm;
903 unsigned int period;
904} alarm_win32_data = {0, NULL, -1};
905
906static int win32_start_timer(struct qemu_alarm_timer *t);
907static void win32_stop_timer(struct qemu_alarm_timer *t);
efe75411 908static void win32_rearm_timer(struct qemu_alarm_timer *t);
c8994013 909
40c3bac3 910#else
c8994013
TS
911
912static int unix_start_timer(struct qemu_alarm_timer *t);
913static void unix_stop_timer(struct qemu_alarm_timer *t);
914
231c6586
TS
915#ifdef __linux__
916
efe75411
TS
917static int dynticks_start_timer(struct qemu_alarm_timer *t);
918static void dynticks_stop_timer(struct qemu_alarm_timer *t);
919static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
920
c40ec5a9
TS
921static int hpet_start_timer(struct qemu_alarm_timer *t);
922static void hpet_stop_timer(struct qemu_alarm_timer *t);
923
c8994013
TS
924static int rtc_start_timer(struct qemu_alarm_timer *t);
925static void rtc_stop_timer(struct qemu_alarm_timer *t);
926
efe75411 927#endif /* __linux__ */
8a7ddc38 928
c8994013
TS
929#endif /* _WIN32 */
930
2e70f6ef 931/* Correlation between real and virtual time is always going to be
bf20dc07 932 fairly approximate, so ignore small variation.
2e70f6ef
PB
933 When the guest is idle real and virtual time will be aligned in
934 the IO wait loop. */
935#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
936
937static void icount_adjust(void)
938{
939 int64_t cur_time;
940 int64_t cur_icount;
941 int64_t delta;
942 static int64_t last_delta;
943 /* If the VM is not running, then do nothing. */
944 if (!vm_running)
945 return;
946
947 cur_time = cpu_get_clock();
948 cur_icount = qemu_get_clock(vm_clock);
949 delta = cur_icount - cur_time;
950 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
951 if (delta > 0
952 && last_delta + ICOUNT_WOBBLE < delta * 2
953 && icount_time_shift > 0) {
954 /* The guest is getting too far ahead. Slow time down. */
955 icount_time_shift--;
956 }
957 if (delta < 0
958 && last_delta - ICOUNT_WOBBLE > delta * 2
959 && icount_time_shift < MAX_ICOUNT_SHIFT) {
960 /* The guest is getting too far behind. Speed time up. */
961 icount_time_shift++;
962 }
963 last_delta = delta;
964 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
965}
966
967static void icount_adjust_rt(void * opaque)
968{
969 qemu_mod_timer(icount_rt_timer,
970 qemu_get_clock(rt_clock) + 1000);
971 icount_adjust();
972}
973
974static void icount_adjust_vm(void * opaque)
975{
976 qemu_mod_timer(icount_vm_timer,
977 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
978 icount_adjust();
979}
980
981static void init_icount_adjust(void)
982{
983 /* Have both realtime and virtual time triggers for speed adjustment.
984 The realtime trigger catches emulated time passing too slowly,
985 the virtual time trigger catches emulated time passing too fast.
986 Realtime triggers occur even when idle, so use them less frequently
987 than VM triggers. */
988 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
989 qemu_mod_timer(icount_rt_timer,
990 qemu_get_clock(rt_clock) + 1000);
991 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
992 qemu_mod_timer(icount_vm_timer,
993 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
994}
995
c8994013 996static struct qemu_alarm_timer alarm_timers[] = {
efe75411 997#ifndef _WIN32
231c6586 998#ifdef __linux__
efe75411
TS
999 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1000 dynticks_stop_timer, dynticks_rearm_timer, NULL},
c40ec5a9 1001 /* HPET - if available - is preferred */
efe75411 1002 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
c40ec5a9 1003 /* ...otherwise try RTC */
efe75411 1004 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
c8994013 1005#endif
efe75411 1006 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
c8994013 1007#else
efe75411
TS
1008 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1009 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1010 {"win32", 0, win32_start_timer,
1011 win32_stop_timer, NULL, &alarm_win32_data},
c8994013
TS
1012#endif
1013 {NULL, }
1014};
1015
3f47aa8c 1016static void show_available_alarms(void)
f3dcfada
TS
1017{
1018 int i;
1019
1020 printf("Available alarm timers, in order of precedence:\n");
1021 for (i = 0; alarm_timers[i].name; i++)
1022 printf("%s\n", alarm_timers[i].name);
1023}
1024
1025static void configure_alarms(char const *opt)
1026{
1027 int i;
1028 int cur = 0;
1029 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1030 char *arg;
1031 char *name;
2e70f6ef 1032 struct qemu_alarm_timer tmp;
f3dcfada 1033
3adda04c 1034 if (!strcmp(opt, "?")) {
f3dcfada
TS
1035 show_available_alarms();
1036 exit(0);
1037 }
1038
1039 arg = strdup(opt);
1040
1041 /* Reorder the array */
1042 name = strtok(arg, ",");
1043 while (name) {
e2b577e5 1044 for (i = 0; i < count && alarm_timers[i].name; i++) {
f3dcfada
TS
1045 if (!strcmp(alarm_timers[i].name, name))
1046 break;
1047 }
1048
1049 if (i == count) {
1050 fprintf(stderr, "Unknown clock %s\n", name);
1051 goto next;
1052 }
1053
1054 if (i < cur)
1055 /* Ignore */
1056 goto next;
1057
1058 /* Swap */
1059 tmp = alarm_timers[i];
1060 alarm_timers[i] = alarm_timers[cur];
1061 alarm_timers[cur] = tmp;
1062
1063 cur++;
1064next:
1065 name = strtok(NULL, ",");
1066 }
1067
1068 free(arg);
1069
1070 if (cur) {
2e70f6ef 1071 /* Disable remaining timers */
f3dcfada
TS
1072 for (i = cur; i < count; i++)
1073 alarm_timers[i].name = NULL;
3adda04c
AJ
1074 } else {
1075 show_available_alarms();
1076 exit(1);
f3dcfada 1077 }
f3dcfada
TS
1078}
1079
c8994013
TS
1080QEMUClock *rt_clock;
1081QEMUClock *vm_clock;
1082
1083static QEMUTimer *active_timers[2];
1084
9596ebb7 1085static QEMUClock *qemu_new_clock(int type)
8a7ddc38
FB
1086{
1087 QEMUClock *clock;
1088 clock = qemu_mallocz(sizeof(QEMUClock));
1089 if (!clock)
1090 return NULL;
1091 clock->type = type;
1092 return clock;
1093}
1094
1095QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1096{
1097 QEMUTimer *ts;
1098
1099 ts = qemu_mallocz(sizeof(QEMUTimer));
1100 ts->clock = clock;
1101 ts->cb = cb;
1102 ts->opaque = opaque;
1103 return ts;
1104}
1105
1106void qemu_free_timer(QEMUTimer *ts)
1107{
1108 qemu_free(ts);
1109}
1110
1111/* stop a timer, but do not dealloc it */
1112void qemu_del_timer(QEMUTimer *ts)
1113{
1114 QEMUTimer **pt, *t;
1115
1116 /* NOTE: this code must be signal safe because
1117 qemu_timer_expired() can be called from a signal. */
1118 pt = &active_timers[ts->clock->type];
1119 for(;;) {
1120 t = *pt;
1121 if (!t)
1122 break;
1123 if (t == ts) {
1124 *pt = t->next;
1125 break;
1126 }
1127 pt = &t->next;
1128 }
1129}
1130
1131/* modify the current timer so that it will be fired when current_time
1132 >= expire_time. The corresponding callback will be called. */
1133void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1134{
1135 QEMUTimer **pt, *t;
1136
1137 qemu_del_timer(ts);
1138
1139 /* add the timer in the sorted list */
1140 /* NOTE: this code must be signal safe because
1141 qemu_timer_expired() can be called from a signal. */
1142 pt = &active_timers[ts->clock->type];
1143 for(;;) {
1144 t = *pt;
1145 if (!t)
1146 break;
5fafdf24 1147 if (t->expire_time > expire_time)
8a7ddc38
FB
1148 break;
1149 pt = &t->next;
1150 }
1151 ts->expire_time = expire_time;
1152 ts->next = *pt;
1153 *pt = ts;
d5d08334
AZ
1154
1155 /* Rearm if necessary */
2e70f6ef
PB
1156 if (pt == &active_timers[ts->clock->type]) {
1157 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1158 qemu_rearm_alarm_timer(alarm_timer);
1159 }
1160 /* Interrupt execution to force deadline recalculation. */
1161 if (use_icount && cpu_single_env) {
1162 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1163 }
1164 }
8a7ddc38
FB
1165}
1166
1167int qemu_timer_pending(QEMUTimer *ts)
1168{
1169 QEMUTimer *t;
1170 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1171 if (t == ts)
1172 return 1;
1173 }
1174 return 0;
1175}
1176
1177static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1178{
1179 if (!timer_head)
1180 return 0;
1181 return (timer_head->expire_time <= current_time);
1182}
1183
1184static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1185{
1186 QEMUTimer *ts;
3b46e624 1187
8a7ddc38
FB
1188 for(;;) {
1189 ts = *ptimer_head;
e95c8d51 1190 if (!ts || ts->expire_time > current_time)
8a7ddc38
FB
1191 break;
1192 /* remove timer from the list before calling the callback */
1193 *ptimer_head = ts->next;
1194 ts->next = NULL;
3b46e624 1195
8a7ddc38
FB
1196 /* run the callback (the timer list can be modified) */
1197 ts->cb(ts->opaque);
1198 }
1199}
1200
1201int64_t qemu_get_clock(QEMUClock *clock)
1202{
1203 switch(clock->type) {
1204 case QEMU_TIMER_REALTIME:
1dce7c3c 1205 return get_clock() / 1000000;
8a7ddc38
FB
1206 default:
1207 case QEMU_TIMER_VIRTUAL:
2e70f6ef
PB
1208 if (use_icount) {
1209 return cpu_get_icount();
1210 } else {
1211 return cpu_get_clock();
1212 }
8a7ddc38
FB
1213 }
1214}
1215
1dce7c3c
FB
1216static void init_timers(void)
1217{
1218 init_get_clock();
1219 ticks_per_sec = QEMU_TIMER_BASE;
1220 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1221 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1222}
1223
8a7ddc38
FB
1224/* save a timer */
1225void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1226{
1227 uint64_t expire_time;
1228
1229 if (qemu_timer_pending(ts)) {
1230 expire_time = ts->expire_time;
1231 } else {
1232 expire_time = -1;
1233 }
1234 qemu_put_be64(f, expire_time);
1235}
1236
1237void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1238{
1239 uint64_t expire_time;
1240
1241 expire_time = qemu_get_be64(f);
1242 if (expire_time != -1) {
1243 qemu_mod_timer(ts, expire_time);
1244 } else {
1245 qemu_del_timer(ts);
1246 }
1247}
1248
1249static void timer_save(QEMUFile *f, void *opaque)
1250{
1251 if (cpu_ticks_enabled) {
1252 hw_error("cannot save state if virtual timers are running");
1253 }
bee8d684
TS
1254 qemu_put_be64(f, cpu_ticks_offset);
1255 qemu_put_be64(f, ticks_per_sec);
1256 qemu_put_be64(f, cpu_clock_offset);
8a7ddc38
FB
1257}
1258
1259static int timer_load(QEMUFile *f, void *opaque, int version_id)
1260{
c88676f8 1261 if (version_id != 1 && version_id != 2)
8a7ddc38
FB
1262 return -EINVAL;
1263 if (cpu_ticks_enabled) {
1264 return -EINVAL;
1265 }
bee8d684
TS
1266 cpu_ticks_offset=qemu_get_be64(f);
1267 ticks_per_sec=qemu_get_be64(f);
c88676f8 1268 if (version_id == 2) {
bee8d684 1269 cpu_clock_offset=qemu_get_be64(f);
c88676f8 1270 }
8a7ddc38
FB
1271 return 0;
1272}
1273
67b915a5 1274#ifdef _WIN32
5fafdf24 1275void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
67b915a5
FB
1276 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1277#else
8a7ddc38 1278static void host_alarm_handler(int host_signum)
67b915a5 1279#endif
8a7ddc38 1280{
02ba45c5
FB
1281#if 0
1282#define DISP_FREQ 1000
1283 {
1284 static int64_t delta_min = INT64_MAX;
1285 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1286 static int count;
1287 ti = qemu_get_clock(vm_clock);
1288 if (last_clock != 0) {
1289 delta = ti - last_clock;
1290 if (delta < delta_min)
1291 delta_min = delta;
1292 if (delta > delta_max)
1293 delta_max = delta;
1294 delta_cum += delta;
1295 if (++count == DISP_FREQ) {
26a76461 1296 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
02ba45c5
FB
1297 muldiv64(delta_min, 1000000, ticks_per_sec),
1298 muldiv64(delta_max, 1000000, ticks_per_sec),
1299 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1300 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1301 count = 0;
1302 delta_min = INT64_MAX;
1303 delta_max = 0;
1304 delta_cum = 0;
1305 }
1306 }
1307 last_clock = ti;
1308 }
1309#endif
efe75411 1310 if (alarm_has_dynticks(alarm_timer) ||
2e70f6ef
PB
1311 (!use_icount &&
1312 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1313 qemu_get_clock(vm_clock))) ||
8a7ddc38
FB
1314 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1315 qemu_get_clock(rt_clock))) {
06d9f2f7 1316#ifdef _WIN32
c8994013
TS
1317 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1318 SetEvent(data->host_alarm);
06d9f2f7 1319#endif
ee5605e5
AZ
1320 CPUState *env = next_cpu;
1321
d5d08334
AZ
1322 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1323
4f8eb8da
AZ
1324 if (env) {
1325 /* stop the currently executing cpu because a timer occured */
1326 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
a332e112 1327#ifdef USE_KQEMU
4f8eb8da
AZ
1328 if (env->kqemu_enabled) {
1329 kqemu_cpu_interrupt(env);
1330 }
ee5605e5 1331#endif
4f8eb8da 1332 }
ee5605e5 1333 event_pending = 1;
8a7ddc38
FB
1334 }
1335}
1336
2e70f6ef 1337static int64_t qemu_next_deadline(void)
efe75411 1338{
2e70f6ef 1339 int64_t delta;
efe75411
TS
1340
1341 if (active_timers[QEMU_TIMER_VIRTUAL]) {
2e70f6ef
PB
1342 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1343 qemu_get_clock(vm_clock);
1344 } else {
1345 /* To avoid problems with overflow limit this to 2^32. */
1346 delta = INT32_MAX;
efe75411
TS
1347 }
1348
2e70f6ef
PB
1349 if (delta < 0)
1350 delta = 0;
efe75411 1351
2e70f6ef
PB
1352 return delta;
1353}
1354
8632fb9a 1355#if defined(__linux__) || defined(_WIN32)
2e70f6ef
PB
1356static uint64_t qemu_next_deadline_dyntick(void)
1357{
1358 int64_t delta;
1359 int64_t rtdelta;
1360
1361 if (use_icount)
1362 delta = INT32_MAX;
1363 else
1364 delta = (qemu_next_deadline() + 999) / 1000;
1365
1366 if (active_timers[QEMU_TIMER_REALTIME]) {
1367 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1368 qemu_get_clock(rt_clock))*1000;
1369 if (rtdelta < delta)
1370 delta = rtdelta;
1371 }
1372
1373 if (delta < MIN_TIMER_REARM_US)
1374 delta = MIN_TIMER_REARM_US;
1375
1376 return delta;
efe75411 1377}
8632fb9a 1378#endif
efe75411 1379
fd872598
FB
1380#ifndef _WIN32
1381
829309c7
FB
1382#if defined(__linux__)
1383
fd872598
FB
1384#define RTC_FREQ 1024
1385
c8994013
TS
1386static void enable_sigio_timer(int fd)
1387{
1388 struct sigaction act;
1389
1390 /* timer signal */
1391 sigfillset(&act.sa_mask);
1392 act.sa_flags = 0;
c8994013
TS
1393 act.sa_handler = host_alarm_handler;
1394
1395 sigaction(SIGIO, &act, NULL);
1396 fcntl(fd, F_SETFL, O_ASYNC);
1397 fcntl(fd, F_SETOWN, getpid());
1398}
829309c7 1399
c40ec5a9
TS
1400static int hpet_start_timer(struct qemu_alarm_timer *t)
1401{
1402 struct hpet_info info;
1403 int r, fd;
1404
1405 fd = open("/dev/hpet", O_RDONLY);
1406 if (fd < 0)
1407 return -1;
1408
1409 /* Set frequency */
1410 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1411 if (r < 0) {
1412 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1413 "error, but for better emulation accuracy type:\n"
1414 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1415 goto fail;
1416 }
1417
1418 /* Check capabilities */
1419 r = ioctl(fd, HPET_INFO, &info);
1420 if (r < 0)
1421 goto fail;
1422
1423 /* Enable periodic mode */
1424 r = ioctl(fd, HPET_EPI, 0);
1425 if (info.hi_flags && (r < 0))
1426 goto fail;
1427
1428 /* Enable interrupt */
1429 r = ioctl(fd, HPET_IE_ON, 0);
1430 if (r < 0)
1431 goto fail;
1432
1433 enable_sigio_timer(fd);
fcdc2129 1434 t->priv = (void *)(long)fd;
c40ec5a9
TS
1435
1436 return 0;
1437fail:
1438 close(fd);
1439 return -1;
1440}
1441
1442static void hpet_stop_timer(struct qemu_alarm_timer *t)
1443{
fcdc2129 1444 int fd = (long)t->priv;
c40ec5a9
TS
1445
1446 close(fd);
1447}
1448
c8994013 1449static int rtc_start_timer(struct qemu_alarm_timer *t)
fd872598 1450{
c8994013 1451 int rtc_fd;
b5a23ad4 1452 unsigned long current_rtc_freq = 0;
c8994013 1453
aeb30be6 1454 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
fd872598
FB
1455 if (rtc_fd < 0)
1456 return -1;
b5a23ad4
AZ
1457 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1458 if (current_rtc_freq != RTC_FREQ &&
1459 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
fd872598
FB
1460 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1461 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1462 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1463 goto fail;
1464 }
1465 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1466 fail:
1467 close(rtc_fd);
1468 return -1;
1469 }
c8994013
TS
1470
1471 enable_sigio_timer(rtc_fd);
1472
fcdc2129 1473 t->priv = (void *)(long)rtc_fd;
c8994013 1474
fd872598
FB
1475 return 0;
1476}
1477
c8994013 1478static void rtc_stop_timer(struct qemu_alarm_timer *t)
829309c7 1479{
fcdc2129 1480 int rtc_fd = (long)t->priv;
c8994013
TS
1481
1482 close(rtc_fd);
829309c7
FB
1483}
1484
efe75411
TS
1485static int dynticks_start_timer(struct qemu_alarm_timer *t)
1486{
1487 struct sigevent ev;
1488 timer_t host_timer;
1489 struct sigaction act;
1490
1491 sigfillset(&act.sa_mask);
1492 act.sa_flags = 0;
efe75411
TS
1493 act.sa_handler = host_alarm_handler;
1494
1495 sigaction(SIGALRM, &act, NULL);
1496
1497 ev.sigev_value.sival_int = 0;
1498 ev.sigev_notify = SIGEV_SIGNAL;
1499 ev.sigev_signo = SIGALRM;
1500
1501 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1502 perror("timer_create");
1503
1504 /* disable dynticks */
1505 fprintf(stderr, "Dynamic Ticks disabled\n");
1506
1507 return -1;
1508 }
1509
1510 t->priv = (void *)host_timer;
1511
1512 return 0;
1513}
1514
1515static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1516{
1517 timer_t host_timer = (timer_t)t->priv;
1518
1519 timer_delete(host_timer);
1520}
1521
1522static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1523{
1524 timer_t host_timer = (timer_t)t->priv;
1525 struct itimerspec timeout;
1526 int64_t nearest_delta_us = INT64_MAX;
1527 int64_t current_us;
1528
1529 if (!active_timers[QEMU_TIMER_REALTIME] &&
1530 !active_timers[QEMU_TIMER_VIRTUAL])
d5d08334 1531 return;
efe75411 1532
2e70f6ef 1533 nearest_delta_us = qemu_next_deadline_dyntick();
efe75411
TS
1534
1535 /* check whether a timer is already running */
1536 if (timer_gettime(host_timer, &timeout)) {
1537 perror("gettime");
1538 fprintf(stderr, "Internal timer error: aborting\n");
1539 exit(1);
1540 }
1541 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1542 if (current_us && current_us <= nearest_delta_us)
1543 return;
1544
1545 timeout.it_interval.tv_sec = 0;
1546 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1547 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1548 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1549 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1550 perror("settime");
1551 fprintf(stderr, "Internal timer error: aborting\n");
1552 exit(1);
1553 }
1554}
1555
70744b3a 1556#endif /* defined(__linux__) */
231c6586 1557
c8994013
TS
1558static int unix_start_timer(struct qemu_alarm_timer *t)
1559{
1560 struct sigaction act;
1561 struct itimerval itv;
1562 int err;
1563
1564 /* timer signal */
1565 sigfillset(&act.sa_mask);
1566 act.sa_flags = 0;
c8994013
TS
1567 act.sa_handler = host_alarm_handler;
1568
1569 sigaction(SIGALRM, &act, NULL);
1570
1571 itv.it_interval.tv_sec = 0;
1572 /* for i386 kernel 2.6 to get 1 ms */
1573 itv.it_interval.tv_usec = 999;
1574 itv.it_value.tv_sec = 0;
1575 itv.it_value.tv_usec = 10 * 1000;
1576
1577 err = setitimer(ITIMER_REAL, &itv, NULL);
1578 if (err)
1579 return -1;
1580
1581 return 0;
1582}
1583
1584static void unix_stop_timer(struct qemu_alarm_timer *t)
1585{
1586 struct itimerval itv;
1587
1588 memset(&itv, 0, sizeof(itv));
1589 setitimer(ITIMER_REAL, &itv, NULL);
1590}
1591
829309c7 1592#endif /* !defined(_WIN32) */
fd872598 1593
c8994013
TS
1594#ifdef _WIN32
1595
1596static int win32_start_timer(struct qemu_alarm_timer *t)
1597{
1598 TIMECAPS tc;
1599 struct qemu_alarm_win32 *data = t->priv;
efe75411 1600 UINT flags;
c8994013
TS
1601
1602 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1603 if (!data->host_alarm) {
1604 perror("Failed CreateEvent");
c396a7f0 1605 return -1;
c8994013
TS
1606 }
1607
1608 memset(&tc, 0, sizeof(tc));
1609 timeGetDevCaps(&tc, sizeof(tc));
1610
1611 if (data->period < tc.wPeriodMin)
1612 data->period = tc.wPeriodMin;
1613
1614 timeBeginPeriod(data->period);
1615
efe75411
TS
1616 flags = TIME_CALLBACK_FUNCTION;
1617 if (alarm_has_dynticks(t))
1618 flags |= TIME_ONESHOT;
1619 else
1620 flags |= TIME_PERIODIC;
1621
c8994013
TS
1622 data->timerId = timeSetEvent(1, // interval (ms)
1623 data->period, // resolution
1624 host_alarm_handler, // function
1625 (DWORD)t, // parameter
efe75411 1626 flags);
c8994013
TS
1627
1628 if (!data->timerId) {
1629 perror("Failed to initialize win32 alarm timer");
1630
1631 timeEndPeriod(data->period);
1632 CloseHandle(data->host_alarm);
1633 return -1;
1634 }
1635
1636 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1637
1638 return 0;
1639}
1640
1641static void win32_stop_timer(struct qemu_alarm_timer *t)
1642{
1643 struct qemu_alarm_win32 *data = t->priv;
1644
1645 timeKillEvent(data->timerId);
1646 timeEndPeriod(data->period);
1647
1648 CloseHandle(data->host_alarm);
1649}
1650
efe75411
TS
1651static void win32_rearm_timer(struct qemu_alarm_timer *t)
1652{
1653 struct qemu_alarm_win32 *data = t->priv;
1654 uint64_t nearest_delta_us;
1655
1656 if (!active_timers[QEMU_TIMER_REALTIME] &&
1657 !active_timers[QEMU_TIMER_VIRTUAL])
d5d08334 1658 return;
efe75411 1659
2e70f6ef 1660 nearest_delta_us = qemu_next_deadline_dyntick();
efe75411
TS
1661 nearest_delta_us /= 1000;
1662
1663 timeKillEvent(data->timerId);
1664
1665 data->timerId = timeSetEvent(1,
1666 data->period,
1667 host_alarm_handler,
1668 (DWORD)t,
1669 TIME_ONESHOT | TIME_PERIODIC);
1670
1671 if (!data->timerId) {
1672 perror("Failed to re-arm win32 alarm timer");
1673
1674 timeEndPeriod(data->period);
1675 CloseHandle(data->host_alarm);
1676 exit(1);
1677 }
1678}
1679
c8994013
TS
1680#endif /* _WIN32 */
1681
1dce7c3c 1682static void init_timer_alarm(void)
8a7ddc38 1683{
223f0d72 1684 struct qemu_alarm_timer *t = NULL;
c8994013
TS
1685 int i, err = -1;
1686
1687 for (i = 0; alarm_timers[i].name; i++) {
1688 t = &alarm_timers[i];
1689
c8994013
TS
1690 err = t->start(t);
1691 if (!err)
1692 break;
67b915a5 1693 }
fd872598 1694
c8994013
TS
1695 if (err) {
1696 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1697 fprintf(stderr, "Terminating\n");
1698 exit(1);
67b915a5 1699 }
c8994013
TS
1700
1701 alarm_timer = t;
8a7ddc38
FB
1702}
1703
9596ebb7 1704static void quit_timers(void)
40c3bac3 1705{
c8994013
TS
1706 alarm_timer->stop(alarm_timer);
1707 alarm_timer = NULL;
40c3bac3
FB
1708}
1709
f6503059
AZ
1710/***********************************************************/
1711/* host time/date access */
1712void qemu_get_timedate(struct tm *tm, int offset)
1713{
1714 time_t ti;
1715 struct tm *ret;
1716
1717 time(&ti);
1718 ti += offset;
1719 if (rtc_date_offset == -1) {
1720 if (rtc_utc)
1721 ret = gmtime(&ti);
1722 else
1723 ret = localtime(&ti);
1724 } else {
1725 ti -= rtc_date_offset;
1726 ret = gmtime(&ti);
1727 }
1728
1729 memcpy(tm, ret, sizeof(struct tm));
1730}
1731
1732int qemu_timedate_diff(struct tm *tm)
1733{
1734 time_t seconds;
1735
1736 if (rtc_date_offset == -1)
1737 if (rtc_utc)
1738 seconds = mktimegm(tm);
1739 else
1740 seconds = mktime(tm);
1741 else
1742 seconds = mktimegm(tm) + rtc_date_offset;
1743
1744 return seconds - time(NULL);
1745}
1746
c4b1fcc0 1747/***********************************************************/
82c643ff 1748/* character device */
313aa567 1749
e5b0bc44
PB
1750static void qemu_chr_event(CharDriverState *s, int event)
1751{
1752 if (!s->chr_event)
1753 return;
1754 s->chr_event(s->handler_opaque, event);
1755}
1756
86e94dea
TS
1757static void qemu_chr_reset_bh(void *opaque)
1758{
1759 CharDriverState *s = opaque;
e5b0bc44 1760 qemu_chr_event(s, CHR_EVENT_RESET);
86e94dea
TS
1761 qemu_bh_delete(s->bh);
1762 s->bh = NULL;
1763}
1764
1765void qemu_chr_reset(CharDriverState *s)
1766{
1767 if (s->bh == NULL) {
1768 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1769 qemu_bh_schedule(s->bh);
1770 }
1771}
1772
82c643ff
FB
1773int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1774{
1775 return s->chr_write(s, buf, len);
1776}
67b915a5 1777
e57a8c0e 1778int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
f8d179e3 1779{
e57a8c0e
FB
1780 if (!s->chr_ioctl)
1781 return -ENOTSUP;
1782 return s->chr_ioctl(s, cmd, arg);
f8d179e3
FB
1783}
1784
e5b0bc44
PB
1785int qemu_chr_can_read(CharDriverState *s)
1786{
1787 if (!s->chr_can_read)
1788 return 0;
1789 return s->chr_can_read(s->handler_opaque);
1790}
1791
1792void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1793{
1794 s->chr_read(s->handler_opaque, buf, len);
1795}
1796
bd9bdce6
AZ
1797void qemu_chr_accept_input(CharDriverState *s)
1798{
1799 if (s->chr_accept_input)
1800 s->chr_accept_input(s);
1801}
e5b0bc44 1802
82c643ff 1803void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
67b915a5 1804{
82c643ff
FB
1805 char buf[4096];
1806 va_list ap;
1807 va_start(ap, fmt);
1808 vsnprintf(buf, sizeof(buf), fmt, ap);
ffe8ab83 1809 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
82c643ff 1810 va_end(ap);
67b915a5
FB
1811}
1812
5905b2e5
FB
1813void qemu_chr_send_event(CharDriverState *s, int event)
1814{
1815 if (s->chr_send_event)
1816 s->chr_send_event(s, event);
1817}
1818
5fafdf24
TS
1819void qemu_chr_add_handlers(CharDriverState *s,
1820 IOCanRWHandler *fd_can_read,
e5b0bc44
PB
1821 IOReadHandler *fd_read,
1822 IOEventHandler *fd_event,
1823 void *opaque)
82c643ff 1824{
e5b0bc44
PB
1825 s->chr_can_read = fd_can_read;
1826 s->chr_read = fd_read;
1827 s->chr_event = fd_event;
1828 s->handler_opaque = opaque;
1829 if (s->chr_update_read_handler)
1830 s->chr_update_read_handler(s);
82c643ff 1831}
3b46e624 1832
82c643ff 1833static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
313aa567 1834{
82c643ff
FB
1835 return len;
1836}
1837
52f61fde 1838static CharDriverState *qemu_chr_open_null(void)
82c643ff
FB
1839{
1840 CharDriverState *chr;
1841
1842 chr = qemu_mallocz(sizeof(CharDriverState));
1843 if (!chr)
1844 return NULL;
1845 chr->chr_write = null_chr_write;
82c643ff
FB
1846 return chr;
1847}
1848
20d8a3ed
TS
1849/* MUX driver for serial I/O splitting */
1850static int term_timestamps;
1851static int64_t term_timestamps_start;
9c1de612 1852#define MAX_MUX 4
bd9bdce6
AZ
1853#define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1854#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
20d8a3ed
TS
1855typedef struct {
1856 IOCanRWHandler *chr_can_read[MAX_MUX];
1857 IOReadHandler *chr_read[MAX_MUX];
1858 IOEventHandler *chr_event[MAX_MUX];
1859 void *ext_opaque[MAX_MUX];
1860 CharDriverState *drv;
bd9bdce6
AZ
1861 unsigned char buffer[MUX_BUFFER_SIZE];
1862 int prod;
1863 int cons;
20d8a3ed
TS
1864 int mux_cnt;
1865 int term_got_escape;
1866 int max_size;
1867} MuxDriver;
1868
1869
1870static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1871{
1872 MuxDriver *d = chr->opaque;
1873 int ret;
1874 if (!term_timestamps) {
1875 ret = d->drv->chr_write(d->drv, buf, len);
1876 } else {
1877 int i;
1878
1879 ret = 0;
1880 for(i = 0; i < len; i++) {
1881 ret += d->drv->chr_write(d->drv, buf+i, 1);
1882 if (buf[i] == '\n') {
1883 char buf1[64];
1884 int64_t ti;
1885 int secs;
1886
1887 ti = get_clock();
1888 if (term_timestamps_start == -1)
1889 term_timestamps_start = ti;
1890 ti -= term_timestamps_start;
1891 secs = ti / 1000000000;
1892 snprintf(buf1, sizeof(buf1),
1893 "[%02d:%02d:%02d.%03d] ",
1894 secs / 3600,
1895 (secs / 60) % 60,
1896 secs % 60,
1897 (int)((ti / 1000000) % 1000));
ffe8ab83 1898 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
20d8a3ed
TS
1899 }
1900 }
1901 }
1902 return ret;
1903}
1904
7ccfb2eb 1905static const char * const mux_help[] = {
20d8a3ed
TS
1906 "% h print this help\n\r",
1907 "% x exit emulator\n\r",
1908 "% s save disk data back to file (if -snapshot)\n\r",
1909 "% t toggle console timestamps\n\r"
1910 "% b send break (magic sysrq)\n\r",
1911 "% c switch between console and monitor\n\r",
1912 "% % sends %\n\r",
1913 NULL
1914};
1915
1916static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1917static void mux_print_help(CharDriverState *chr)
1918{
1919 int i, j;
1920 char ebuf[15] = "Escape-Char";
1921 char cbuf[50] = "\n\r";
1922
1923 if (term_escape_char > 0 && term_escape_char < 26) {
363a37d5
BS
1924 snprintf(cbuf, sizeof(cbuf), "\n\r");
1925 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
20d8a3ed 1926 } else {
363a37d5
BS
1927 snprintf(cbuf, sizeof(cbuf),
1928 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1929 term_escape_char);
20d8a3ed 1930 }
ffe8ab83 1931 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
20d8a3ed
TS
1932 for (i = 0; mux_help[i] != NULL; i++) {
1933 for (j=0; mux_help[i][j] != '\0'; j++) {
1934 if (mux_help[i][j] == '%')
ffe8ab83 1935 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
20d8a3ed 1936 else
ffe8ab83 1937 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
20d8a3ed
TS
1938 }
1939 }
1940}
1941
1942static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1943{
1944 if (d->term_got_escape) {
1945 d->term_got_escape = 0;
1946 if (ch == term_escape_char)
1947 goto send_char;
1948 switch(ch) {
1949 case '?':
1950 case 'h':
1951 mux_print_help(chr);
1952 break;
1953 case 'x':
1954 {
7ccfb2eb 1955 const char *term = "QEMU: Terminated\n\r";
ffe8ab83 1956 chr->chr_write(chr,(uint8_t *)term,strlen(term));
20d8a3ed
TS
1957 exit(0);
1958 break;
1959 }
1960 case 's':
1961 {
1962 int i;
e4bcb14c
TS
1963 for (i = 0; i < nb_drives; i++) {
1964 bdrv_commit(drives_table[i].bdrv);
20d8a3ed
TS
1965 }
1966 }
1967 break;
1968 case 'b':
36ddb83b 1969 qemu_chr_event(chr, CHR_EVENT_BREAK);
20d8a3ed
TS
1970 break;
1971 case 'c':
1972 /* Switch to the next registered device */
1973 chr->focus++;
1974 if (chr->focus >= d->mux_cnt)
1975 chr->focus = 0;
1976 break;
1977 case 't':
1978 term_timestamps = !term_timestamps;
1979 term_timestamps_start = -1;
1980 break;
1981 }
1982 } else if (ch == term_escape_char) {
1983 d->term_got_escape = 1;
1984 } else {
1985 send_char:
1986 return 1;
1987 }
1988 return 0;
1989}
1990
bd9bdce6
AZ
1991static void mux_chr_accept_input(CharDriverState *chr)
1992{
1993 int m = chr->focus;
1994 MuxDriver *d = chr->opaque;
1995
1996 while (d->prod != d->cons &&
1997 d->chr_can_read[m] &&
1998 d->chr_can_read[m](d->ext_opaque[m])) {
1999 d->chr_read[m](d->ext_opaque[m],
2000 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2001 }
2002}
2003
20d8a3ed
TS
2004static int mux_chr_can_read(void *opaque)
2005{
2006 CharDriverState *chr = opaque;
2007 MuxDriver *d = chr->opaque;
bd9bdce6
AZ
2008
2009 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2010 return 1;
20d8a3ed 2011 if (d->chr_can_read[chr->focus])
bd9bdce6 2012 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
20d8a3ed
TS
2013 return 0;
2014}
2015
2016static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2017{
2018 CharDriverState *chr = opaque;
2019 MuxDriver *d = chr->opaque;
bd9bdce6 2020 int m = chr->focus;
20d8a3ed 2021 int i;
bd9bdce6
AZ
2022
2023 mux_chr_accept_input (opaque);
2024
20d8a3ed 2025 for(i = 0; i < size; i++)
bd9bdce6
AZ
2026 if (mux_proc_byte(chr, d, buf[i])) {
2027 if (d->prod == d->cons &&
2028 d->chr_can_read[m] &&
2029 d->chr_can_read[m](d->ext_opaque[m]))
2030 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2031 else
2032 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2033 }
20d8a3ed
TS
2034}
2035
2036static void mux_chr_event(void *opaque, int event)
2037{
2038 CharDriverState *chr = opaque;
2039 MuxDriver *d = chr->opaque;
2040 int i;
2041
2042 /* Send the event to all registered listeners */
2043 for (i = 0; i < d->mux_cnt; i++)
2044 if (d->chr_event[i])
2045 d->chr_event[i](d->ext_opaque[i], event);
2046}
2047
2048static void mux_chr_update_read_handler(CharDriverState *chr)
2049{
2050 MuxDriver *d = chr->opaque;
2051
2052 if (d->mux_cnt >= MAX_MUX) {
2053 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2054 return;
2055 }
2056 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2057 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2058 d->chr_read[d->mux_cnt] = chr->chr_read;
2059 d->chr_event[d->mux_cnt] = chr->chr_event;
2060 /* Fix up the real driver with mux routines */
2061 if (d->mux_cnt == 0) {
2062 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2063 mux_chr_event, chr);
2064 }
2065 chr->focus = d->mux_cnt;
2066 d->mux_cnt++;
2067}
2068
9596ebb7 2069static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
20d8a3ed
TS
2070{
2071 CharDriverState *chr;
2072 MuxDriver *d;
2073
2074 chr = qemu_mallocz(sizeof(CharDriverState));
2075 if (!chr)
2076 return NULL;
2077 d = qemu_mallocz(sizeof(MuxDriver));
2078 if (!d) {
2079 free(chr);
2080 return NULL;
2081 }
2082
2083 chr->opaque = d;
2084 d->drv = drv;
2085 chr->focus = -1;
2086 chr->chr_write = mux_chr_write;
2087 chr->chr_update_read_handler = mux_chr_update_read_handler;
bd9bdce6 2088 chr->chr_accept_input = mux_chr_accept_input;
20d8a3ed
TS
2089 return chr;
2090}
2091
2092
fd1dff4b 2093#ifdef _WIN32
82c643ff 2094
fd1dff4b
FB
2095static void socket_cleanup(void)
2096{
2097 WSACleanup();
2098}
82c643ff 2099
fd1dff4b
FB
2100static int socket_init(void)
2101{
2102 WSADATA Data;
2103 int ret, err;
2104
2105 ret = WSAStartup(MAKEWORD(2,2), &Data);
2106 if (ret != 0) {
2107 err = WSAGetLastError();
2108 fprintf(stderr, "WSAStartup: %d\n", err);
2109 return -1;
2110 }
2111 atexit(socket_cleanup);
2112 return 0;
2113}
2114
2115static int send_all(int fd, const uint8_t *buf, int len1)
2116{
2117 int ret, len;
3b46e624 2118
fd1dff4b
FB
2119 len = len1;
2120 while (len > 0) {
2121 ret = send(fd, buf, len, 0);
2122 if (ret < 0) {
2123 int errno;
2124 errno = WSAGetLastError();
2125 if (errno != WSAEWOULDBLOCK) {
2126 return -1;
2127 }
2128 } else if (ret == 0) {
2129 break;
2130 } else {
2131 buf += ret;
2132 len -= ret;
2133 }
2134 }
2135 return len1 - len;
2136}
2137
fd1dff4b
FB
2138#else
2139
1d96905d
FB
2140static int unix_write(int fd, const uint8_t *buf, int len1)
2141{
2142 int ret, len;
2143
2144 len = len1;
2145 while (len > 0) {
2146 ret = write(fd, buf, len);
2147 if (ret < 0) {
2148 if (errno != EINTR && errno != EAGAIN)
2149 return -1;
2150 } else if (ret == 0) {
2151 break;
2152 } else {
2153 buf += ret;
2154 len -= ret;
2155 }
2156 }
2157 return len1 - len;
2158}
2159
fd1dff4b
FB
2160static inline int send_all(int fd, const uint8_t *buf, int len1)
2161{
2162 return unix_write(fd, buf, len1);
2163}
fd1dff4b
FB
2164#endif /* !_WIN32 */
2165
2166#ifndef _WIN32
2167
2168typedef struct {
2169 int fd_in, fd_out;
fd1dff4b
FB
2170 int max_size;
2171} FDCharDriver;
2172
20d8a3ed
TS
2173#define STDIO_MAX_CLIENTS 1
2174static int stdio_nb_clients = 0;
fd1dff4b 2175
82c643ff
FB
2176static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2177{
2178 FDCharDriver *s = chr->opaque;
1d96905d 2179 return unix_write(s->fd_out, buf, len);
82c643ff
FB
2180}
2181
7c9d8e07
FB
2182static int fd_chr_read_poll(void *opaque)
2183{
2184 CharDriverState *chr = opaque;
2185 FDCharDriver *s = chr->opaque;
2186
e5b0bc44 2187 s->max_size = qemu_chr_can_read(chr);
7c9d8e07
FB
2188 return s->max_size;
2189}
2190
2191static void fd_chr_read(void *opaque)
2192{
2193 CharDriverState *chr = opaque;
2194 FDCharDriver *s = chr->opaque;
2195 int size, len;
2196 uint8_t buf[1024];
3b46e624 2197
7c9d8e07
FB
2198 len = sizeof(buf);
2199 if (len > s->max_size)
2200 len = s->max_size;
2201 if (len == 0)
2202 return;
2203 size = read(s->fd_in, buf, len);
188157fe
PB
2204 if (size == 0) {
2205 /* FD has been closed. Remove it from the active list. */
2206 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2207 return;
2208 }
7c9d8e07 2209 if (size > 0) {
e5b0bc44 2210 qemu_chr_read(chr, buf, size);
7c9d8e07
FB
2211 }
2212}
2213
e5b0bc44 2214static void fd_chr_update_read_handler(CharDriverState *chr)
82c643ff
FB
2215{
2216 FDCharDriver *s = chr->opaque;
2217
f8d179e3
FB
2218 if (s->fd_in >= 0) {
2219 if (nographic && s->fd_in == 0) {
f8d179e3 2220 } else {
5fafdf24 2221 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
7c9d8e07 2222 fd_chr_read, NULL, chr);
f8d179e3 2223 }
82c643ff
FB
2224 }
2225}
2226
a11d070e
AZ
2227static void fd_chr_close(struct CharDriverState *chr)
2228{
2229 FDCharDriver *s = chr->opaque;
2230
2231 if (s->fd_in >= 0) {
2232 if (nographic && s->fd_in == 0) {
2233 } else {
2234 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2235 }
2236 }
2237
2238 qemu_free(s);
2239}
2240
82c643ff 2241/* open a character device to a unix fd */
52f61fde 2242static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
82c643ff
FB
2243{
2244 CharDriverState *chr;
2245 FDCharDriver *s;
2246
2247 chr = qemu_mallocz(sizeof(CharDriverState));
2248 if (!chr)
2249 return NULL;
2250 s = qemu_mallocz(sizeof(FDCharDriver));
2251 if (!s) {
2252 free(chr);
2253 return NULL;
2254 }
2255 s->fd_in = fd_in;
2256 s->fd_out = fd_out;
2257 chr->opaque = s;
2258 chr->chr_write = fd_chr_write;
e5b0bc44 2259 chr->chr_update_read_handler = fd_chr_update_read_handler;
a11d070e 2260 chr->chr_close = fd_chr_close;
86e94dea
TS
2261
2262 qemu_chr_reset(chr);
2263
82c643ff
FB
2264 return chr;
2265}
2266
52f61fde 2267static CharDriverState *qemu_chr_open_file_out(const char *file_out)
f8d179e3
FB
2268{
2269 int fd_out;
2270
aeb30be6 2271 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
f8d179e3
FB
2272 if (fd_out < 0)
2273 return NULL;
2274 return qemu_chr_open_fd(-1, fd_out);
2275}
2276
52f61fde 2277static CharDriverState *qemu_chr_open_pipe(const char *filename)
f8d179e3 2278{
c26c1c4b
TS
2279 int fd_in, fd_out;
2280 char filename_in[256], filename_out[256];
2281
2282 snprintf(filename_in, 256, "%s.in", filename);
2283 snprintf(filename_out, 256, "%s.out", filename);
aeb30be6
AZ
2284 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2285 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
c26c1c4b
TS
2286 if (fd_in < 0 || fd_out < 0) {
2287 if (fd_in >= 0)
2288 close(fd_in);
2289 if (fd_out >= 0)
2290 close(fd_out);
aeb30be6 2291 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
c26c1c4b
TS
2292 if (fd_in < 0)
2293 return NULL;
2294 }
2295 return qemu_chr_open_fd(fd_in, fd_out);
f8d179e3
FB
2296}
2297
2298
82c643ff
FB
2299/* for STDIO, we handle the case where several clients use it
2300 (nographic mode) */
2301
aa0bc6b6
FB
2302#define TERM_FIFO_MAX_SIZE 1
2303
aa0bc6b6 2304static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1dce7c3c 2305static int term_fifo_size;
330d0414 2306
7c9d8e07 2307static int stdio_read_poll(void *opaque)
82c643ff 2308{
20d8a3ed 2309 CharDriverState *chr = opaque;
aa0bc6b6 2310
20d8a3ed
TS
2311 /* try to flush the queue if needed */
2312 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2313 qemu_chr_read(chr, term_fifo, 1);
2314 term_fifo_size = 0;
aa0bc6b6 2315 }
20d8a3ed
TS
2316 /* see if we can absorb more chars */
2317 if (term_fifo_size == 0)
2318 return 1;
2319 else
2320 return 0;
82c643ff
FB
2321}
2322
7c9d8e07 2323static void stdio_read(void *opaque)
82c643ff 2324{
7c9d8e07
FB
2325 int size;
2326 uint8_t buf[1];
20d8a3ed
TS
2327 CharDriverState *chr = opaque;
2328
7c9d8e07 2329 size = read(0, buf, 1);
519945df
PB
2330 if (size == 0) {
2331 /* stdin has been closed. Remove it from the active list. */
2332 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2333 return;
2334 }
20d8a3ed
TS
2335 if (size > 0) {
2336 if (qemu_chr_can_read(chr) > 0) {
2337 qemu_chr_read(chr, buf, 1);
2338 } else if (term_fifo_size == 0) {
2339 term_fifo[term_fifo_size++] = buf[0];
1dce7c3c 2340 }
1dce7c3c
FB
2341 }
2342}
2343
8d11df9e
FB
2344/* init terminal so that we can grab keys */
2345static struct termios oldtty;
2346static int old_fd0_flags;
a11d070e 2347static int term_atexit_done;
8d11df9e
FB
2348
2349static void term_exit(void)
2350{
2351 tcsetattr (0, TCSANOW, &oldtty);
2352 fcntl(0, F_SETFL, old_fd0_flags);
2353}
2354
2355static void term_init(void)
2356{
2357 struct termios tty;
2358
2359 tcgetattr (0, &tty);
2360 oldtty = tty;
2361 old_fd0_flags = fcntl(0, F_GETFL);
2362
2363 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2364 |INLCR|IGNCR|ICRNL|IXON);
2365 tty.c_oflag |= OPOST;
2366 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2367 /* if graphical mode, we allow Ctrl-C handling */
2368 if (nographic)
2369 tty.c_lflag &= ~ISIG;
2370 tty.c_cflag &= ~(CSIZE|PARENB);
2371 tty.c_cflag |= CS8;
2372 tty.c_cc[VMIN] = 1;
2373 tty.c_cc[VTIME] = 0;
3b46e624 2374
8d11df9e
FB
2375 tcsetattr (0, TCSANOW, &tty);
2376
a11d070e
AZ
2377 if (!term_atexit_done++)
2378 atexit(term_exit);
8d11df9e
FB
2379
2380 fcntl(0, F_SETFL, O_NONBLOCK);
2381}
2382
a11d070e
AZ
2383static void qemu_chr_close_stdio(struct CharDriverState *chr)
2384{
2385 term_exit();
2386 stdio_nb_clients--;
2387 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2388 fd_chr_close(chr);
2389}
2390
52f61fde 2391static CharDriverState *qemu_chr_open_stdio(void)
82c643ff
FB
2392{
2393 CharDriverState *chr;
2394
20d8a3ed
TS
2395 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2396 return NULL;
2397 chr = qemu_chr_open_fd(0, 1);
a11d070e 2398 chr->chr_close = qemu_chr_close_stdio;
20d8a3ed
TS
2399 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2400 stdio_nb_clients++;
2401 term_init();
2402
82c643ff
FB
2403 return chr;
2404}
2405
64b7b733
AJ
2406#ifdef __sun__
2407/* Once Solaris has openpty(), this is going to be removed. */
2408int openpty(int *amaster, int *aslave, char *name,
2409 struct termios *termp, struct winsize *winp)
2410{
2411 const char *slave;
2412 int mfd = -1, sfd = -1;
2413
2414 *amaster = *aslave = -1;
2415
2416 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2417 if (mfd < 0)
2418 goto err;
2419
2420 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2421 goto err;
2422
2423 if ((slave = ptsname(mfd)) == NULL)
2424 goto err;
2425
2426 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2427 goto err;
2428
2429 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2430 (termp != NULL && tcgetattr(sfd, termp) < 0))
2431 goto err;
2432
2433 if (amaster)
2434 *amaster = mfd;
2435 if (aslave)
2436 *aslave = sfd;
2437 if (winp)
2438 ioctl(sfd, TIOCSWINSZ, winp);
2439
2440 return 0;
2441
2442err:
2443 if (sfd != -1)
2444 close(sfd);
2445 close(mfd);
2446 return -1;
2447}
2448
2449void cfmakeraw (struct termios *termios_p)
2450{
2451 termios_p->c_iflag &=
2452 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2453 termios_p->c_oflag &= ~OPOST;
2454 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2455 termios_p->c_cflag &= ~(CSIZE|PARENB);
2456 termios_p->c_cflag |= CS8;
2457
2458 termios_p->c_cc[VMIN] = 0;
2459 termios_p->c_cc[VTIME] = 0;
2460}
2461#endif
2462
9892fbfb
BS
2463#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2464 || defined(__NetBSD__) || defined(__OpenBSD__)
279e694b
AL
2465
2466typedef struct {
2467 int fd;
2468 int connected;
2469 int polling;
2470 int read_bytes;
2471 QEMUTimer *timer;
2472} PtyCharDriver;
2473
2474static void pty_chr_update_read_handler(CharDriverState *chr);
2475static void pty_chr_state(CharDriverState *chr, int connected);
2476
2477static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2478{
2479 PtyCharDriver *s = chr->opaque;
2480
2481 if (!s->connected) {
2482 /* guest sends data, check for (re-)connect */
2483 pty_chr_update_read_handler(chr);
2484 return 0;
2485 }
2486 return unix_write(s->fd, buf, len);
2487}
2488
2489static int pty_chr_read_poll(void *opaque)
2490{
2491 CharDriverState *chr = opaque;
2492 PtyCharDriver *s = chr->opaque;
2493
2494 s->read_bytes = qemu_chr_can_read(chr);
2495 return s->read_bytes;
2496}
2497
2498static void pty_chr_read(void *opaque)
2499{
2500 CharDriverState *chr = opaque;
2501 PtyCharDriver *s = chr->opaque;
2502 int size, len;
2503 uint8_t buf[1024];
2504
2505 len = sizeof(buf);
2506 if (len > s->read_bytes)
2507 len = s->read_bytes;
2508 if (len == 0)
2509 return;
2510 size = read(s->fd, buf, len);
2511 if ((size == -1 && errno == EIO) ||
2512 (size == 0)) {
2513 pty_chr_state(chr, 0);
2514 return;
2515 }
2516 if (size > 0) {
2517 pty_chr_state(chr, 1);
2518 qemu_chr_read(chr, buf, size);
2519 }
2520}
2521
2522static void pty_chr_update_read_handler(CharDriverState *chr)
2523{
2524 PtyCharDriver *s = chr->opaque;
2525
2526 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2527 pty_chr_read, NULL, chr);
2528 s->polling = 1;
2529 /*
2530 * Short timeout here: just need wait long enougth that qemu makes
2531 * it through the poll loop once. When reconnected we want a
2532 * short timeout so we notice it almost instantly. Otherwise
2533 * read() gives us -EIO instantly, making pty_chr_state() reset the
2534 * timeout to the normal (much longer) poll interval before the
2535 * timer triggers.
2536 */
2537 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2538}
2539
2540static void pty_chr_state(CharDriverState *chr, int connected)
2541{
2542 PtyCharDriver *s = chr->opaque;
2543
2544 if (!connected) {
2545 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2546 s->connected = 0;
2547 s->polling = 0;
2548 /* (re-)connect poll interval for idle guests: once per second.
2549 * We check more frequently in case the guests sends data to
2550 * the virtual device linked to our pty. */
2551 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2552 } else {
2553 if (!s->connected)
2554 qemu_chr_reset(chr);
2555 s->connected = 1;
2556 }
2557}
2558
8fcd3692 2559static void pty_chr_timer(void *opaque)
279e694b
AL
2560{
2561 struct CharDriverState *chr = opaque;
2562 PtyCharDriver *s = chr->opaque;
2563
2564 if (s->connected)
2565 return;
2566 if (s->polling) {
2567 /* If we arrive here without polling being cleared due
2568 * read returning -EIO, then we are (re-)connected */
2569 pty_chr_state(chr, 1);
2570 return;
2571 }
2572
2573 /* Next poll ... */
2574 pty_chr_update_read_handler(chr);
2575}
2576
2577static void pty_chr_close(struct CharDriverState *chr)
2578{
2579 PtyCharDriver *s = chr->opaque;
2580
2581 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2582 close(s->fd);
2583 qemu_free(s);
2584}
2585
52f61fde 2586static CharDriverState *qemu_chr_open_pty(void)
82c643ff 2587{
279e694b
AL
2588 CharDriverState *chr;
2589 PtyCharDriver *s;
91fc2119 2590 struct termios tty;
279e694b 2591 int slave_fd;
9892fbfb
BS
2592#if defined(__OpenBSD__)
2593 char pty_name[PATH_MAX];
2594#define q_ptsname(x) pty_name
2595#else
2596 char *pty_name = NULL;
2597#define q_ptsname(x) ptsname(x)
2598#endif
279e694b
AL
2599
2600 chr = qemu_mallocz(sizeof(CharDriverState));
2601 if (!chr)
2602 return NULL;
2603 s = qemu_mallocz(sizeof(PtyCharDriver));
2604 if (!s) {
2605 qemu_free(chr);
2606 return NULL;
2607 }
3b46e624 2608
9892fbfb 2609 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
82c643ff
FB
2610 return NULL;
2611 }
3b46e624 2612
64b7b733
AJ
2613 /* Set raw attributes on the pty. */
2614 cfmakeraw(&tty);
2615 tcsetattr(slave_fd, TCSAFLUSH, &tty);
279e694b
AL
2616 close(slave_fd);
2617
9892fbfb 2618 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
91fc2119 2619
279e694b
AL
2620 chr->opaque = s;
2621 chr->chr_write = pty_chr_write;
2622 chr->chr_update_read_handler = pty_chr_update_read_handler;
2623 chr->chr_close = pty_chr_close;
2624
2625 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2626
2627 return chr;
82c643ff 2628}
f8d179e3 2629
5fafdf24 2630static void tty_serial_init(int fd, int speed,
f8d179e3
FB
2631 int parity, int data_bits, int stop_bits)
2632{
2633 struct termios tty;
2634 speed_t spd;
2635
e57a8c0e 2636#if 0
5fafdf24 2637 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
e57a8c0e
FB
2638 speed, parity, data_bits, stop_bits);
2639#endif
2640 tcgetattr (fd, &tty);
f8d179e3 2641
a7954218
AZ
2642#define MARGIN 1.1
2643 if (speed <= 50 * MARGIN)
f8d179e3 2644 spd = B50;
a7954218 2645 else if (speed <= 75 * MARGIN)
f8d179e3 2646 spd = B75;
a7954218 2647 else if (speed <= 300 * MARGIN)
f8d179e3 2648 spd = B300;
a7954218 2649 else if (speed <= 600 * MARGIN)
f8d179e3 2650 spd = B600;
a7954218 2651 else if (speed <= 1200 * MARGIN)
f8d179e3 2652 spd = B1200;
a7954218 2653 else if (speed <= 2400 * MARGIN)
f8d179e3 2654 spd = B2400;
a7954218 2655 else if (speed <= 4800 * MARGIN)
f8d179e3 2656 spd = B4800;
a7954218 2657 else if (speed <= 9600 * MARGIN)
f8d179e3 2658 spd = B9600;
a7954218 2659 else if (speed <= 19200 * MARGIN)
f8d179e3 2660 spd = B19200;
a7954218 2661 else if (speed <= 38400 * MARGIN)
f8d179e3 2662 spd = B38400;
a7954218 2663 else if (speed <= 57600 * MARGIN)
f8d179e3 2664 spd = B57600;
a7954218
AZ
2665 else if (speed <= 115200 * MARGIN)
2666 spd = B115200;
2667 else
f8d179e3 2668 spd = B115200;
f8d179e3
FB
2669
2670 cfsetispeed(&tty, spd);
2671 cfsetospeed(&tty, spd);
2672
2673 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2674 |INLCR|IGNCR|ICRNL|IXON);
2675 tty.c_oflag |= OPOST;
2676 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
094eed6c 2677 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
f8d179e3
FB
2678 switch(data_bits) {
2679 default:
2680 case 8:
2681 tty.c_cflag |= CS8;
2682 break;
2683 case 7:
2684 tty.c_cflag |= CS7;
2685 break;
2686 case 6:
2687 tty.c_cflag |= CS6;
2688 break;
2689 case 5:
2690 tty.c_cflag |= CS5;
2691 break;
2692 }
2693 switch(parity) {
2694 default:
2695 case 'N':
2696 break;
2697 case 'E':
2698 tty.c_cflag |= PARENB;
2699 break;
2700 case 'O':
2701 tty.c_cflag |= PARENB | PARODD;
2702 break;
2703 }
094eed6c
FB
2704 if (stop_bits == 2)
2705 tty.c_cflag |= CSTOPB;
3b46e624 2706
f8d179e3
FB
2707 tcsetattr (fd, TCSANOW, &tty);
2708}
2709
e57a8c0e 2710static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
f8d179e3
FB
2711{
2712 FDCharDriver *s = chr->opaque;
3b46e624 2713
e57a8c0e
FB
2714 switch(cmd) {
2715 case CHR_IOCTL_SERIAL_SET_PARAMS:
2716 {
2717 QEMUSerialSetParams *ssp = arg;
5fafdf24 2718 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
e57a8c0e
FB
2719 ssp->data_bits, ssp->stop_bits);
2720 }
2721 break;
2722 case CHR_IOCTL_SERIAL_SET_BREAK:
2723 {
2724 int enable = *(int *)arg;
2725 if (enable)
2726 tcsendbreak(s->fd_in, 1);
2727 }
2728 break;
81174dae
AL
2729 case CHR_IOCTL_SERIAL_GET_TIOCM:
2730 {
2731 int sarg = 0;
2732 int *targ = (int *)arg;
2733 ioctl(s->fd_in, TIOCMGET, &sarg);
2734 *targ = 0;
2735 if (sarg | TIOCM_CTS)
2736 *targ |= CHR_TIOCM_CTS;
2737 if (sarg | TIOCM_CAR)
2738 *targ |= CHR_TIOCM_CAR;
2739 if (sarg | TIOCM_DSR)
2740 *targ |= CHR_TIOCM_DSR;
2741 if (sarg | TIOCM_RI)
2742 *targ |= CHR_TIOCM_RI;
2743 if (sarg | TIOCM_DTR)
2744 *targ |= CHR_TIOCM_DTR;
2745 if (sarg | TIOCM_RTS)
2746 *targ |= CHR_TIOCM_RTS;
2747 }
2748 break;
2749 case CHR_IOCTL_SERIAL_SET_TIOCM:
2750 {
2751 int sarg = *(int *)arg;
2752 int targ = 0;
2753 if (sarg | CHR_TIOCM_DTR)
2754 targ |= TIOCM_DTR;
2755 if (sarg | CHR_TIOCM_RTS)
2756 targ |= TIOCM_RTS;
2757 ioctl(s->fd_in, TIOCMSET, &targ);
2758 }
2759 break;
e57a8c0e
FB
2760 default:
2761 return -ENOTSUP;
2762 }
2763 return 0;
f8d179e3
FB
2764}
2765
52f61fde 2766static CharDriverState *qemu_chr_open_tty(const char *filename)
f8d179e3
FB
2767{
2768 CharDriverState *chr;
2769 int fd;
2770
aeb30be6 2771 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
f8d179e3
FB
2772 tty_serial_init(fd, 115200, 'N', 8, 1);
2773 chr = qemu_chr_open_fd(fd, fd);
aeb30be6
AZ
2774 if (!chr) {
2775 close(fd);
f8d179e3 2776 return NULL;
aeb30be6 2777 }
e57a8c0e 2778 chr->chr_ioctl = tty_serial_ioctl;
86e94dea 2779 qemu_chr_reset(chr);
e57a8c0e
FB
2780 return chr;
2781}
aec62507
TS
2782#else /* ! __linux__ && ! __sun__ */
2783static CharDriverState *qemu_chr_open_pty(void)
2784{
2785 return NULL;
2786}
2787#endif /* __linux__ || __sun__ */
e57a8c0e 2788
aec62507 2789#if defined(__linux__)
5867c88a
TS
2790typedef struct {
2791 int fd;
2792 int mode;
2793} ParallelCharDriver;
2794
2795static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2796{
2797 if (s->mode != mode) {
2798 int m = mode;
2799 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2800 return 0;
2801 s->mode = mode;
2802 }
2803 return 1;
2804}
2805
e57a8c0e
FB
2806static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2807{
5867c88a
TS
2808 ParallelCharDriver *drv = chr->opaque;
2809 int fd = drv->fd;
e57a8c0e
FB
2810 uint8_t b;
2811
2812 switch(cmd) {
2813 case CHR_IOCTL_PP_READ_DATA:
2814 if (ioctl(fd, PPRDATA, &b) < 0)
2815 return -ENOTSUP;
2816 *(uint8_t *)arg = b;
2817 break;
2818 case CHR_IOCTL_PP_WRITE_DATA:
2819 b = *(uint8_t *)arg;
2820 if (ioctl(fd, PPWDATA, &b) < 0)
2821 return -ENOTSUP;
2822 break;
2823 case CHR_IOCTL_PP_READ_CONTROL:
2824 if (ioctl(fd, PPRCONTROL, &b) < 0)
2825 return -ENOTSUP;
5867c88a
TS
2826 /* Linux gives only the lowest bits, and no way to know data
2827 direction! For better compatibility set the fixed upper
2828 bits. */
2829 *(uint8_t *)arg = b | 0xc0;
e57a8c0e
FB
2830 break;
2831 case CHR_IOCTL_PP_WRITE_CONTROL:
2832 b = *(uint8_t *)arg;
2833 if (ioctl(fd, PPWCONTROL, &b) < 0)
2834 return -ENOTSUP;
2835 break;
2836 case CHR_IOCTL_PP_READ_STATUS:
2837 if (ioctl(fd, PPRSTATUS, &b) < 0)
2838 return -ENOTSUP;
2839 *(uint8_t *)arg = b;
2840 break;
563e3c6e
AJ
2841 case CHR_IOCTL_PP_DATA_DIR:
2842 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2843 return -ENOTSUP;
2844 break;
5867c88a
TS
2845 case CHR_IOCTL_PP_EPP_READ_ADDR:
2846 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2847 struct ParallelIOArg *parg = arg;
2848 int n = read(fd, parg->buffer, parg->count);
2849 if (n != parg->count) {
2850 return -EIO;
2851 }
2852 }
2853 break;
2854 case CHR_IOCTL_PP_EPP_READ:
2855 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2856 struct ParallelIOArg *parg = arg;
2857 int n = read(fd, parg->buffer, parg->count);
2858 if (n != parg->count) {
2859 return -EIO;
2860 }
2861 }
2862 break;
2863 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2864 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2865 struct ParallelIOArg *parg = arg;
2866 int n = write(fd, parg->buffer, parg->count);
2867 if (n != parg->count) {
2868 return -EIO;
2869 }
2870 }
2871 break;
2872 case CHR_IOCTL_PP_EPP_WRITE:
2873 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2874 struct ParallelIOArg *parg = arg;
2875 int n = write(fd, parg->buffer, parg->count);
2876 if (n != parg->count) {
2877 return -EIO;
2878 }
2879 }
2880 break;
e57a8c0e
FB
2881 default:
2882 return -ENOTSUP;
2883 }
2884 return 0;
2885}
2886
5867c88a
TS
2887static void pp_close(CharDriverState *chr)
2888{
2889 ParallelCharDriver *drv = chr->opaque;
2890 int fd = drv->fd;
2891
2892 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2893 ioctl(fd, PPRELEASE);
2894 close(fd);
2895 qemu_free(drv);
2896}
2897
52f61fde 2898static CharDriverState *qemu_chr_open_pp(const char *filename)
e57a8c0e
FB
2899{
2900 CharDriverState *chr;
5867c88a 2901 ParallelCharDriver *drv;
e57a8c0e
FB
2902 int fd;
2903
aeb30be6 2904 TFR(fd = open(filename, O_RDWR));
e57a8c0e
FB
2905 if (fd < 0)
2906 return NULL;
2907
2908 if (ioctl(fd, PPCLAIM) < 0) {
2909 close(fd);
2910 return NULL;
2911 }
2912
5867c88a
TS
2913 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2914 if (!drv) {
2915 close(fd);
2916 return NULL;
2917 }
2918 drv->fd = fd;
2919 drv->mode = IEEE1284_MODE_COMPAT;
2920
e57a8c0e
FB
2921 chr = qemu_mallocz(sizeof(CharDriverState));
2922 if (!chr) {
5867c88a 2923 qemu_free(drv);
e57a8c0e
FB
2924 close(fd);
2925 return NULL;
2926 }
e57a8c0e 2927 chr->chr_write = null_chr_write;
e57a8c0e 2928 chr->chr_ioctl = pp_ioctl;
5867c88a
TS
2929 chr->chr_close = pp_close;
2930 chr->opaque = drv;
86e94dea
TS
2931
2932 qemu_chr_reset(chr);
2933
f8d179e3
FB
2934 return chr;
2935}
aec62507 2936#endif /* __linux__ */
f8d179e3 2937
aec62507 2938#else /* _WIN32 */
82c643ff 2939
f331110f 2940typedef struct {
f331110f
FB
2941 int max_size;
2942 HANDLE hcom, hrecv, hsend;
2943 OVERLAPPED orecv, osend;
2944 BOOL fpipe;
2945 DWORD len;
2946} WinCharState;
2947
2948#define NSENDBUF 2048
2949#define NRECVBUF 2048
2950#define MAXCONNECT 1
2951#define NTIMEOUT 5000
2952
2953static int win_chr_poll(void *opaque);
2954static int win_chr_pipe_poll(void *opaque);
2955
087f4ae0 2956static void win_chr_close(CharDriverState *chr)
f331110f 2957{
087f4ae0
TS
2958 WinCharState *s = chr->opaque;
2959
f331110f
FB
2960 if (s->hsend) {
2961 CloseHandle(s->hsend);
2962 s->hsend = NULL;
2963 }
2964 if (s->hrecv) {
2965 CloseHandle(s->hrecv);
2966 s->hrecv = NULL;
2967 }
2968 if (s->hcom) {
2969 CloseHandle(s->hcom);
2970 s->hcom = NULL;
2971 }
2972 if (s->fpipe)
087f4ae0 2973 qemu_del_polling_cb(win_chr_pipe_poll, chr);
f331110f 2974 else
087f4ae0 2975 qemu_del_polling_cb(win_chr_poll, chr);
f331110f
FB
2976}
2977
087f4ae0 2978static int win_chr_init(CharDriverState *chr, const char *filename)
f331110f
FB
2979{
2980 WinCharState *s = chr->opaque;
f331110f
FB
2981 COMMCONFIG comcfg;
2982 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2983 COMSTAT comstat;
2984 DWORD size;
2985 DWORD err;
3b46e624 2986
f331110f
FB
2987 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2988 if (!s->hsend) {
2989 fprintf(stderr, "Failed CreateEvent\n");
2990 goto fail;
2991 }
2992 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2993 if (!s->hrecv) {
2994 fprintf(stderr, "Failed CreateEvent\n");
2995 goto fail;
2996 }
2997
2998 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2999 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3000 if (s->hcom == INVALID_HANDLE_VALUE) {
3001 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3002 s->hcom = NULL;
3003 goto fail;
3004 }
3b46e624 3005
f331110f
FB
3006 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3007 fprintf(stderr, "Failed SetupComm\n");
3008 goto fail;
3009 }
3b46e624 3010
f331110f
FB
3011 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3012 size = sizeof(COMMCONFIG);
3013 GetDefaultCommConfig(filename, &comcfg, &size);
3014 comcfg.dcb.DCBlength = sizeof(DCB);
3015 CommConfigDialog(filename, NULL, &comcfg);
3016
3017 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3018 fprintf(stderr, "Failed SetCommState\n");
3019 goto fail;
3020 }
3021
3022 if (!SetCommMask(s->hcom, EV_ERR)) {
3023 fprintf(stderr, "Failed SetCommMask\n");
3024 goto fail;
3025 }
3026
3027 cto.ReadIntervalTimeout = MAXDWORD;
3028 if (!SetCommTimeouts(s->hcom, &cto)) {
3029 fprintf(stderr, "Failed SetCommTimeouts\n");
3030 goto fail;
3031 }
3b46e624 3032
f331110f
FB
3033 if (!ClearCommError(s->hcom, &err, &comstat)) {
3034 fprintf(stderr, "Failed ClearCommError\n");
3035 goto fail;
3036 }
087f4ae0 3037 qemu_add_polling_cb(win_chr_poll, chr);
f331110f
FB
3038 return 0;
3039
3040 fail:
087f4ae0 3041 win_chr_close(chr);
f331110f
FB
3042 return -1;
3043}
3044
3045static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3046{
3047 WinCharState *s = chr->opaque;
3048 DWORD len, ret, size, err;
3049
3050 len = len1;
3051 ZeroMemory(&s->osend, sizeof(s->osend));
3052 s->osend.hEvent = s->hsend;
3053 while (len > 0) {
3054 if (s->hsend)
3055 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3056 else
3057 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3058 if (!ret) {
3059 err = GetLastError();
3060 if (err == ERROR_IO_PENDING) {
3061 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3062 if (ret) {
3063 buf += size;
3064 len -= size;
3065 } else {
3066 break;
3067 }
3068 } else {
3069 break;
3070 }
3071 } else {
3072 buf += size;
3073 len -= size;
3074 }
3075 }
3076 return len1 - len;
3077}
3078
087f4ae0 3079static int win_chr_read_poll(CharDriverState *chr)
f331110f 3080{
087f4ae0
TS
3081 WinCharState *s = chr->opaque;
3082
3083 s->max_size = qemu_chr_can_read(chr);
f331110f
FB
3084 return s->max_size;
3085}
e5b0bc44 3086
087f4ae0 3087static void win_chr_readfile(CharDriverState *chr)
f331110f 3088{
087f4ae0 3089 WinCharState *s = chr->opaque;
f331110f
FB
3090 int ret, err;
3091 uint8_t buf[1024];
3092 DWORD size;
3b46e624 3093
f331110f
FB
3094 ZeroMemory(&s->orecv, sizeof(s->orecv));
3095 s->orecv.hEvent = s->hrecv;
3096 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3097 if (!ret) {
3098 err = GetLastError();
3099 if (err == ERROR_IO_PENDING) {
3100 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3101 }
3102 }
3103
3104 if (size > 0) {
087f4ae0 3105 qemu_chr_read(chr, buf, size);
f331110f
FB
3106 }
3107}
3108
087f4ae0 3109static void win_chr_read(CharDriverState *chr)
f331110f 3110{
087f4ae0
TS
3111 WinCharState *s = chr->opaque;
3112
f331110f
FB
3113 if (s->len > s->max_size)
3114 s->len = s->max_size;
3115 if (s->len == 0)
3116 return;
3b46e624 3117
087f4ae0 3118 win_chr_readfile(chr);
f331110f
FB
3119}
3120
3121static int win_chr_poll(void *opaque)
3122{
087f4ae0
TS
3123 CharDriverState *chr = opaque;
3124 WinCharState *s = chr->opaque;
f331110f
FB
3125 COMSTAT status;
3126 DWORD comerr;
3b46e624 3127
f331110f
FB
3128 ClearCommError(s->hcom, &comerr, &status);
3129 if (status.cbInQue > 0) {
3130 s->len = status.cbInQue;
087f4ae0
TS
3131 win_chr_read_poll(chr);
3132 win_chr_read(chr);
f331110f
FB
3133 return 1;
3134 }
3135 return 0;
3136}
3137
52f61fde 3138static CharDriverState *qemu_chr_open_win(const char *filename)
f331110f
FB
3139{
3140 CharDriverState *chr;
3141 WinCharState *s;
3b46e624 3142
f331110f
FB
3143 chr = qemu_mallocz(sizeof(CharDriverState));
3144 if (!chr)
3145 return NULL;
3146 s = qemu_mallocz(sizeof(WinCharState));
3147 if (!s) {
3148 free(chr);
3149 return NULL;
3150 }
3151 chr->opaque = s;
3152 chr->chr_write = win_chr_write;
f331110f
FB
3153 chr->chr_close = win_chr_close;
3154
087f4ae0 3155 if (win_chr_init(chr, filename) < 0) {
f331110f
FB
3156 free(s);
3157 free(chr);
3158 return NULL;
3159 }
86e94dea 3160 qemu_chr_reset(chr);
f331110f
FB
3161 return chr;
3162}
3163
3164static int win_chr_pipe_poll(void *opaque)
3165{
087f4ae0
TS
3166 CharDriverState *chr = opaque;
3167 WinCharState *s = chr->opaque;
f331110f
FB
3168 DWORD size;
3169
3170 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3171 if (size > 0) {
3172 s->len = size;
087f4ae0
TS
3173 win_chr_read_poll(chr);
3174 win_chr_read(chr);
f331110f
FB
3175 return 1;
3176 }
3177 return 0;
3178}
3179
087f4ae0 3180static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
f331110f 3181{
087f4ae0 3182 WinCharState *s = chr->opaque;
f331110f
FB
3183 OVERLAPPED ov;
3184 int ret;
3185 DWORD size;
3186 char openname[256];
3b46e624 3187
f331110f
FB
3188 s->fpipe = TRUE;
3189
3190 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3191 if (!s->hsend) {
3192 fprintf(stderr, "Failed CreateEvent\n");
3193 goto fail;
3194 }
3195 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3196 if (!s->hrecv) {
3197 fprintf(stderr, "Failed CreateEvent\n");
3198 goto fail;
3199 }
3b46e624 3200
f331110f
FB
3201 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3202 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3203 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3204 PIPE_WAIT,
3205 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3206 if (s->hcom == INVALID_HANDLE_VALUE) {
3207 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3208 s->hcom = NULL;
3209 goto fail;
3210 }
3211
3212 ZeroMemory(&ov, sizeof(ov));
3213 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3214 ret = ConnectNamedPipe(s->hcom, &ov);
3215 if (ret) {
3216 fprintf(stderr, "Failed ConnectNamedPipe\n");
3217 goto fail;
3218 }
3219
3220 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3221 if (!ret) {
3222 fprintf(stderr, "Failed GetOverlappedResult\n");
3223 if (ov.hEvent) {
3224 CloseHandle(ov.hEvent);
3225 ov.hEvent = NULL;
3226 }
3227 goto fail;
3228 }
3229
3230 if (ov.hEvent) {
3231 CloseHandle(ov.hEvent);
3232 ov.hEvent = NULL;
3233 }
087f4ae0 3234 qemu_add_polling_cb(win_chr_pipe_poll, chr);
f331110f
FB
3235 return 0;
3236
3237 fail:
087f4ae0 3238 win_chr_close(chr);
f331110f
FB
3239 return -1;
3240}
3241
3242
52f61fde 3243static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
f331110f
FB
3244{
3245 CharDriverState *chr;
3246 WinCharState *s;
3247
3248 chr = qemu_mallocz(sizeof(CharDriverState));
3249 if (!chr)
3250 return NULL;
3251 s = qemu_mallocz(sizeof(WinCharState));
3252 if (!s) {
3253 free(chr);
3254 return NULL;
3255 }
3256 chr->opaque = s;
3257 chr->chr_write = win_chr_write;
f331110f 3258 chr->chr_close = win_chr_close;
3b46e624 3259
087f4ae0 3260 if (win_chr_pipe_init(chr, filename) < 0) {
f331110f
FB
3261 free(s);
3262 free(chr);
3263 return NULL;
3264 }
86e94dea 3265 qemu_chr_reset(chr);
f331110f
FB
3266 return chr;
3267}
3268
52f61fde 3269static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
f331110f
FB
3270{
3271 CharDriverState *chr;
3272 WinCharState *s;
3273
3274 chr = qemu_mallocz(sizeof(CharDriverState));
3275 if (!chr)
3276 return NULL;
3277 s = qemu_mallocz(sizeof(WinCharState));
3278 if (!s) {
3279 free(chr);
3280 return NULL;
3281 }
3282 s->hcom = fd_out;
3283 chr->opaque = s;
3284 chr->chr_write = win_chr_write;
86e94dea 3285 qemu_chr_reset(chr);
f331110f
FB
3286 return chr;
3287}
72d46479
TS
3288
3289static CharDriverState *qemu_chr_open_win_con(const char *filename)
3290{
3291 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3292}
3293
52f61fde 3294static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
f331110f
FB
3295{
3296 HANDLE fd_out;
3b46e624 3297
f331110f
FB
3298 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3299 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3300 if (fd_out == INVALID_HANDLE_VALUE)
3301 return NULL;
3302
3303 return qemu_chr_open_win_file(fd_out);
3304}
aec62507 3305#endif /* !_WIN32 */
f331110f 3306
0bab00f3
FB
3307/***********************************************************/
3308/* UDP Net console */
3309
3310typedef struct {
0bab00f3
FB
3311 int fd;
3312 struct sockaddr_in daddr;
60fe76f3 3313 uint8_t buf[1024];
0bab00f3
FB
3314 int bufcnt;
3315 int bufptr;
3316 int max_size;
3317} NetCharDriver;
3318
3319static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3320{
3321 NetCharDriver *s = chr->opaque;
3322
3323 return sendto(s->fd, buf, len, 0,
3324 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3325}
3326
3327static int udp_chr_read_poll(void *opaque)
3328{
3329 CharDriverState *chr = opaque;
3330 NetCharDriver *s = chr->opaque;
3331
e5b0bc44 3332 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
3333
3334 /* If there were any stray characters in the queue process them
3335 * first
3336 */
3337 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
e5b0bc44 3338 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
0bab00f3 3339 s->bufptr++;
e5b0bc44 3340 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
3341 }
3342 return s->max_size;
3343}
3344
3345static void udp_chr_read(void *opaque)
3346{
3347 CharDriverState *chr = opaque;
3348 NetCharDriver *s = chr->opaque;
3349
3350 if (s->max_size == 0)
3351 return;
3352 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3353 s->bufptr = s->bufcnt;
3354 if (s->bufcnt <= 0)
3355 return;
3356
3357 s->bufptr = 0;
3358 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
e5b0bc44 3359 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
0bab00f3 3360 s->bufptr++;
e5b0bc44 3361 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
3362 }
3363}
3364
e5b0bc44 3365static void udp_chr_update_read_handler(CharDriverState *chr)
0bab00f3
FB
3366{
3367 NetCharDriver *s = chr->opaque;
3368
3369 if (s->fd >= 0) {
0bab00f3
FB
3370 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3371 udp_chr_read, NULL, chr);
3372 }
3373}
3374
3375int parse_host_port(struct sockaddr_in *saddr, const char *str);
52f61fde
TS
3376#ifndef _WIN32
3377static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3378#endif
951f1351
FB
3379int parse_host_src_port(struct sockaddr_in *haddr,
3380 struct sockaddr_in *saddr,
3381 const char *str);
0bab00f3 3382
52f61fde 3383static CharDriverState *qemu_chr_open_udp(const char *def)
0bab00f3
FB
3384{
3385 CharDriverState *chr = NULL;
3386 NetCharDriver *s = NULL;
3387 int fd = -1;
951f1351 3388 struct sockaddr_in saddr;
0bab00f3
FB
3389
3390 chr = qemu_mallocz(sizeof(CharDriverState));
3391 if (!chr)
3392 goto return_err;
3393 s = qemu_mallocz(sizeof(NetCharDriver));
3394 if (!s)
3395 goto return_err;
3396
3397 fd = socket(PF_INET, SOCK_DGRAM, 0);
3398 if (fd < 0) {
3399 perror("socket(PF_INET, SOCK_DGRAM)");
3400 goto return_err;
3401 }
3402
951f1351
FB
3403 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3404 printf("Could not parse: %s\n", def);
3405 goto return_err;
0bab00f3
FB
3406 }
3407
951f1351 3408 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
0bab00f3
FB
3409 {
3410 perror("bind");
3411 goto return_err;
3412 }
3413
3414 s->fd = fd;
3415 s->bufcnt = 0;
3416 s->bufptr = 0;
3417 chr->opaque = s;
3418 chr->chr_write = udp_chr_write;
e5b0bc44 3419 chr->chr_update_read_handler = udp_chr_update_read_handler;
0bab00f3
FB
3420 return chr;
3421
3422return_err:
3423 if (chr)
3424 free(chr);
3425 if (s)
3426 free(s);
3427 if (fd >= 0)
3428 closesocket(fd);
3429 return NULL;
3430}
3431
3432/***********************************************************/
3433/* TCP Net console */
3434
3435typedef struct {
0bab00f3
FB
3436 int fd, listen_fd;
3437 int connected;
3438 int max_size;
951f1351 3439 int do_telnetopt;
e5b0bc44 3440 int do_nodelay;
ffd843bc 3441 int is_unix;
0bab00f3
FB
3442} TCPCharDriver;
3443
3444static void tcp_chr_accept(void *opaque);
3445
3446static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3447{
3448 TCPCharDriver *s = chr->opaque;
3449 if (s->connected) {
3450 return send_all(s->fd, buf, len);
3451 } else {
3452 /* XXX: indicate an error ? */
3453 return len;
3454 }
3455}
3456
3457static int tcp_chr_read_poll(void *opaque)
3458{
3459 CharDriverState *chr = opaque;
3460 TCPCharDriver *s = chr->opaque;
3461 if (!s->connected)
3462 return 0;
e5b0bc44 3463 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
3464 return s->max_size;
3465}
3466
951f1351
FB
3467#define IAC 255
3468#define IAC_BREAK 243
3469static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3470 TCPCharDriver *s,
60fe76f3 3471 uint8_t *buf, int *size)
951f1351
FB
3472{
3473 /* Handle any telnet client's basic IAC options to satisfy char by
3474 * char mode with no echo. All IAC options will be removed from
3475 * the buf and the do_telnetopt variable will be used to track the
3476 * state of the width of the IAC information.
3477 *
3478 * IAC commands come in sets of 3 bytes with the exception of the
3479 * "IAC BREAK" command and the double IAC.
3480 */
3481
3482 int i;
3483 int j = 0;
3484
3485 for (i = 0; i < *size; i++) {
3486 if (s->do_telnetopt > 1) {
3487 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3488 /* Double IAC means send an IAC */
3489 if (j != i)
3490 buf[j] = buf[i];
3491 j++;
3492 s->do_telnetopt = 1;
3493 } else {
3494 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3495 /* Handle IAC break commands by sending a serial break */
e5b0bc44 3496 qemu_chr_event(chr, CHR_EVENT_BREAK);
951f1351
FB
3497 s->do_telnetopt++;
3498 }
3499 s->do_telnetopt++;
3500 }
3501 if (s->do_telnetopt >= 4) {
3502 s->do_telnetopt = 1;
3503 }
3504 } else {
3505 if ((unsigned char)buf[i] == IAC) {
3506 s->do_telnetopt = 2;
3507 } else {
3508 if (j != i)
3509 buf[j] = buf[i];
3510 j++;
3511 }
3512 }
3513 }
3514 *size = j;
3515}
3516
0bab00f3
FB
3517static void tcp_chr_read(void *opaque)
3518{
3519 CharDriverState *chr = opaque;
3520 TCPCharDriver *s = chr->opaque;
3521 uint8_t buf[1024];
3522 int len, size;
3523
3524 if (!s->connected || s->max_size <= 0)
3525 return;
3526 len = sizeof(buf);
3527 if (len > s->max_size)
3528 len = s->max_size;
3529 size = recv(s->fd, buf, len, 0);
3530 if (size == 0) {
3531 /* connection closed */
3532 s->connected = 0;
3533 if (s->listen_fd >= 0) {
3534 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3535 }
3536 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3537 closesocket(s->fd);
3538 s->fd = -1;
3539 } else if (size > 0) {
951f1351
FB
3540 if (s->do_telnetopt)
3541 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3542 if (size > 0)
e5b0bc44 3543 qemu_chr_read(chr, buf, size);
0bab00f3
FB
3544 }
3545}
3546
0bab00f3
FB
3547static void tcp_chr_connect(void *opaque)
3548{
3549 CharDriverState *chr = opaque;
3550 TCPCharDriver *s = chr->opaque;
3551
3552 s->connected = 1;
3553 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3554 tcp_chr_read, NULL, chr);
86e94dea 3555 qemu_chr_reset(chr);
0bab00f3
FB
3556}
3557
951f1351
FB
3558#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3559static void tcp_chr_telnet_init(int fd)
3560{
3561 char buf[3];
3562 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3563 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3564 send(fd, (char *)buf, 3, 0);
3565 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3566 send(fd, (char *)buf, 3, 0);
3567 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3568 send(fd, (char *)buf, 3, 0);
3569 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3570 send(fd, (char *)buf, 3, 0);
3571}
3572
f7499989
PB
3573static void socket_set_nodelay(int fd)
3574{
3575 int val = 1;
3576 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3577}
3578
0bab00f3
FB
3579static void tcp_chr_accept(void *opaque)
3580{
3581 CharDriverState *chr = opaque;
3582 TCPCharDriver *s = chr->opaque;
3583 struct sockaddr_in saddr;
ffd843bc
TS
3584#ifndef _WIN32
3585 struct sockaddr_un uaddr;
3586#endif
3587 struct sockaddr *addr;
0bab00f3
FB
3588 socklen_t len;
3589 int fd;
3590
3591 for(;;) {
ffd843bc
TS
3592#ifndef _WIN32
3593 if (s->is_unix) {
3594 len = sizeof(uaddr);
3595 addr = (struct sockaddr *)&uaddr;
3596 } else
3597#endif
3598 {
3599 len = sizeof(saddr);
3600 addr = (struct sockaddr *)&saddr;
3601 }
3602 fd = accept(s->listen_fd, addr, &len);
0bab00f3
FB
3603 if (fd < 0 && errno != EINTR) {
3604 return;
3605 } else if (fd >= 0) {
951f1351
FB
3606 if (s->do_telnetopt)
3607 tcp_chr_telnet_init(fd);
0bab00f3
FB
3608 break;
3609 }
3610 }
3611 socket_set_nonblock(fd);
f7499989
PB
3612 if (s->do_nodelay)
3613 socket_set_nodelay(fd);
0bab00f3
FB
3614 s->fd = fd;
3615 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3616 tcp_chr_connect(chr);
3617}
3618
3619static void tcp_chr_close(CharDriverState *chr)
3620{
3621 TCPCharDriver *s = chr->opaque;
3622 if (s->fd >= 0)
3623 closesocket(s->fd);
3624 if (s->listen_fd >= 0)
3625 closesocket(s->listen_fd);
3626 qemu_free(s);
3627}
3628
5fafdf24 3629static CharDriverState *qemu_chr_open_tcp(const char *host_str,
ffd843bc
TS
3630 int is_telnet,
3631 int is_unix)
0bab00f3
FB
3632{
3633 CharDriverState *chr = NULL;
3634 TCPCharDriver *s = NULL;
3635 int fd = -1, ret, err, val;
951f1351
FB
3636 int is_listen = 0;
3637 int is_waitconnect = 1;
f7499989 3638 int do_nodelay = 0;
951f1351 3639 const char *ptr;
0bab00f3 3640 struct sockaddr_in saddr;
ffd843bc
TS
3641#ifndef _WIN32
3642 struct sockaddr_un uaddr;
3643#endif
3644 struct sockaddr *addr;
3645 socklen_t addrlen;
0bab00f3 3646
ffd843bc
TS
3647#ifndef _WIN32
3648 if (is_unix) {
3649 addr = (struct sockaddr *)&uaddr;
3650 addrlen = sizeof(uaddr);
3651 if (parse_unix_path(&uaddr, host_str) < 0)
3652 goto fail;
3653 } else
3654#endif
3655 {
3656 addr = (struct sockaddr *)&saddr;
3657 addrlen = sizeof(saddr);
3658 if (parse_host_port(&saddr, host_str) < 0)
3659 goto fail;
3660 }
0bab00f3 3661
951f1351
FB
3662 ptr = host_str;
3663 while((ptr = strchr(ptr,','))) {
3664 ptr++;
3665 if (!strncmp(ptr,"server",6)) {
3666 is_listen = 1;
3667 } else if (!strncmp(ptr,"nowait",6)) {
3668 is_waitconnect = 0;
f7499989
PB
3669 } else if (!strncmp(ptr,"nodelay",6)) {
3670 do_nodelay = 1;
951f1351
FB
3671 } else {
3672 printf("Unknown option: %s\n", ptr);
3673 goto fail;
3674 }
3675 }
3676 if (!is_listen)
3677 is_waitconnect = 0;
3678
0bab00f3
FB
3679 chr = qemu_mallocz(sizeof(CharDriverState));
3680 if (!chr)
3681 goto fail;
3682 s = qemu_mallocz(sizeof(TCPCharDriver));
3683 if (!s)
3684 goto fail;
ffd843bc
TS
3685
3686#ifndef _WIN32
3687 if (is_unix)
3688 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3689 else
3690#endif
3691 fd = socket(PF_INET, SOCK_STREAM, 0);
5fafdf24
TS
3692
3693 if (fd < 0)
0bab00f3 3694 goto fail;
951f1351
FB
3695
3696 if (!is_waitconnect)
3697 socket_set_nonblock(fd);
0bab00f3
FB
3698
3699 s->connected = 0;
3700 s->fd = -1;
3701 s->listen_fd = -1;
ffd843bc 3702 s->is_unix = is_unix;
f7499989 3703 s->do_nodelay = do_nodelay && !is_unix;
ffd843bc
TS
3704
3705 chr->opaque = s;
3706 chr->chr_write = tcp_chr_write;
ffd843bc
TS
3707 chr->chr_close = tcp_chr_close;
3708
0bab00f3
FB
3709 if (is_listen) {
3710 /* allow fast reuse */
ffd843bc
TS
3711#ifndef _WIN32
3712 if (is_unix) {
3713 char path[109];
ae45d369 3714 pstrcpy(path, sizeof(path), uaddr.sun_path);
ffd843bc
TS
3715 unlink(path);
3716 } else
3717#endif
3718 {
3719 val = 1;
3720 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3721 }
3b46e624 3722
ffd843bc
TS
3723 ret = bind(fd, addr, addrlen);
3724 if (ret < 0)
0bab00f3 3725 goto fail;
ffd843bc 3726
0bab00f3
FB
3727 ret = listen(fd, 0);
3728 if (ret < 0)
3729 goto fail;
ffd843bc 3730
0bab00f3
FB
3731 s->listen_fd = fd;
3732 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
951f1351
FB
3733 if (is_telnet)
3734 s->do_telnetopt = 1;
0bab00f3
FB
3735 } else {
3736 for(;;) {
ffd843bc 3737 ret = connect(fd, addr, addrlen);
0bab00f3
FB
3738 if (ret < 0) {
3739 err = socket_error();
3740 if (err == EINTR || err == EWOULDBLOCK) {
3741 } else if (err == EINPROGRESS) {
3742 break;
f5b12268
TS
3743#ifdef _WIN32
3744 } else if (err == WSAEALREADY) {
3745 break;
3746#endif
0bab00f3
FB
3747 } else {
3748 goto fail;
3749 }
3750 } else {
3751 s->connected = 1;
3752 break;
3753 }
3754 }
3755 s->fd = fd;
f7499989 3756 socket_set_nodelay(fd);
0bab00f3
FB
3757 if (s->connected)
3758 tcp_chr_connect(chr);
3759 else
3760 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3761 }
3b46e624 3762
951f1351
FB
3763 if (is_listen && is_waitconnect) {
3764 printf("QEMU waiting for connection on: %s\n", host_str);
3765 tcp_chr_accept(chr);
3766 socket_set_nonblock(s->listen_fd);
3767 }
3768
0bab00f3
FB
3769 return chr;
3770 fail:
3771 if (fd >= 0)
3772 closesocket(fd);
3773 qemu_free(s);
3774 qemu_free(chr);
3775 return NULL;
3776}
3777
82c643ff
FB
3778CharDriverState *qemu_chr_open(const char *filename)
3779{
f8d179e3 3780 const char *p;
fd1dff4b 3781
82c643ff 3782 if (!strcmp(filename, "vc")) {
af3a9031
TS
3783 return text_console_init(&display_state, 0);
3784 } else if (strstart(filename, "vc:", &p)) {
3785 return text_console_init(&display_state, p);
82c643ff
FB
3786 } else if (!strcmp(filename, "null")) {
3787 return qemu_chr_open_null();
5fafdf24 3788 } else
0bab00f3 3789 if (strstart(filename, "tcp:", &p)) {
ffd843bc 3790 return qemu_chr_open_tcp(p, 0, 0);
0bab00f3 3791 } else
951f1351 3792 if (strstart(filename, "telnet:", &p)) {
ffd843bc 3793 return qemu_chr_open_tcp(p, 1, 0);
0bab00f3
FB
3794 } else
3795 if (strstart(filename, "udp:", &p)) {
3796 return qemu_chr_open_udp(p);
3797 } else
20d8a3ed
TS
3798 if (strstart(filename, "mon:", &p)) {
3799 CharDriverState *drv = qemu_chr_open(p);
3800 if (drv) {
3801 drv = qemu_chr_open_mux(drv);
3802 monitor_init(drv, !nographic);
3803 return drv;
3804 }
3805 printf("Unable to open driver: %s\n", p);
3806 return 0;
3807 } else
7664728b 3808#ifndef _WIN32
ffd843bc
TS
3809 if (strstart(filename, "unix:", &p)) {
3810 return qemu_chr_open_tcp(p, 0, 1);
3811 } else if (strstart(filename, "file:", &p)) {
f8d179e3
FB
3812 return qemu_chr_open_file_out(p);
3813 } else if (strstart(filename, "pipe:", &p)) {
3814 return qemu_chr_open_pipe(p);
7664728b 3815 } else if (!strcmp(filename, "pty")) {
82c643ff
FB
3816 return qemu_chr_open_pty();
3817 } else if (!strcmp(filename, "stdio")) {
3818 return qemu_chr_open_stdio();
5fafdf24 3819 } else
f8d179e3 3820#if defined(__linux__)
e57a8c0e
FB
3821 if (strstart(filename, "/dev/parport", NULL)) {
3822 return qemu_chr_open_pp(filename);
5fafdf24 3823 } else
aec62507 3824#endif
9892fbfb
BS
3825#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3826 || defined(__NetBSD__) || defined(__OpenBSD__)
f8d179e3
FB
3827 if (strstart(filename, "/dev/", NULL)) {
3828 return qemu_chr_open_tty(filename);
3fda388a
TS
3829 } else
3830#endif
aec62507 3831#else /* !_WIN32 */
f331110f
FB
3832 if (strstart(filename, "COM", NULL)) {
3833 return qemu_chr_open_win(filename);
3834 } else
3835 if (strstart(filename, "pipe:", &p)) {
3836 return qemu_chr_open_win_pipe(p);
3837 } else
72d46479
TS
3838 if (strstart(filename, "con:", NULL)) {
3839 return qemu_chr_open_win_con(filename);
3840 } else
f331110f
FB
3841 if (strstart(filename, "file:", &p)) {
3842 return qemu_chr_open_win_file_out(p);
2e4d9fb1
AJ
3843 } else
3844#endif
3845#ifdef CONFIG_BRLAPI
3846 if (!strcmp(filename, "braille")) {
3847 return chr_baum_init();
3848 } else
82c643ff
FB
3849#endif
3850 {
3851 return NULL;
3852 }
3853}
3854
f331110f
FB
3855void qemu_chr_close(CharDriverState *chr)
3856{
3857 if (chr->chr_close)
3858 chr->chr_close(chr);
a11d070e 3859 qemu_free(chr);
f331110f
FB
3860}
3861
80cabfad 3862/***********************************************************/
7c9d8e07 3863/* network device redirectors */
330d0414 3864
9dc63a1e 3865#if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
9596ebb7 3866static void hex_dump(FILE *f, const uint8_t *buf, int size)
c20709aa
FB
3867{
3868 int len, i, j, c;
3869
3870 for(i=0;i<size;i+=16) {
3871 len = size - i;
3872 if (len > 16)
3873 len = 16;
3874 fprintf(f, "%08x ", i);
3875 for(j=0;j<16;j++) {
3876 if (j < len)
3877 fprintf(f, " %02x", buf[i+j]);
3878 else
3879 fprintf(f, " ");
3880 }
3881 fprintf(f, " ");
3882 for(j=0;j<len;j++) {
3883 c = buf[i+j];
3884 if (c < ' ' || c > '~')
3885 c = '.';
3886 fprintf(f, "%c", c);
3887 }
3888 fprintf(f, "\n");
3889 }
3890}
9dc63a1e 3891#endif
c20709aa 3892
7c9d8e07 3893static int parse_macaddr(uint8_t *macaddr, const char *p)
c20709aa 3894{
7c9d8e07 3895 int i;
76ea08f9
AZ
3896 char *last_char;
3897 long int offset;
3898
3899 errno = 0;
3900 offset = strtol(p, &last_char, 0);
3901 if (0 == errno && '\0' == *last_char &&
3902 offset >= 0 && offset <= 0xFFFFFF) {
3903 macaddr[3] = (offset & 0xFF0000) >> 16;
3904 macaddr[4] = (offset & 0xFF00) >> 8;
3905 macaddr[5] = offset & 0xFF;
3906 return 0;
3907 } else {
3908 for(i = 0; i < 6; i++) {
3909 macaddr[i] = strtol(p, (char **)&p, 16);
3910 if (i == 5) {
3911 if (*p != '\0')
3912 return -1;
3913 } else {
3914 if (*p != ':' && *p != '-')
3915 return -1;
3916 p++;
3917 }
7c9d8e07 3918 }
76ea08f9 3919 return 0;
7c9d8e07 3920 }
76ea08f9
AZ
3921
3922 return -1;
c20709aa 3923}
67b915a5 3924
7c9d8e07 3925static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
67b915a5 3926{
7c9d8e07
FB
3927 const char *p, *p1;
3928 int len;
3929 p = *pp;
3930 p1 = strchr(p, sep);
3931 if (!p1)
3932 return -1;
3933 len = p1 - p;
3934 p1++;
3935 if (buf_size > 0) {
3936 if (len > buf_size - 1)
3937 len = buf_size - 1;
3938 memcpy(buf, p, len);
3939 buf[len] = '\0';
3940 }
3941 *pp = p1;
3942 return 0;
c20709aa
FB
3943}
3944
951f1351
FB
3945int parse_host_src_port(struct sockaddr_in *haddr,
3946 struct sockaddr_in *saddr,
3947 const char *input_str)
3948{
3949 char *str = strdup(input_str);
3950 char *host_str = str;
3951 char *src_str;
7ccfb2eb 3952 const char *src_str2;
951f1351
FB
3953 char *ptr;
3954
3955 /*
3956 * Chop off any extra arguments at the end of the string which
3957 * would start with a comma, then fill in the src port information
3958 * if it was provided else use the "any address" and "any port".
3959 */
3960 if ((ptr = strchr(str,',')))
3961 *ptr = '\0';
3962
3963 if ((src_str = strchr(input_str,'@'))) {
3964 *src_str = '\0';
3965 src_str++;
3966 }
3967
3968 if (parse_host_port(haddr, host_str) < 0)
3969 goto fail;
3970
7ccfb2eb 3971 src_str2 = src_str;
951f1351 3972 if (!src_str || *src_str == '\0')
7ccfb2eb 3973 src_str2 = ":0";
951f1351 3974
7ccfb2eb 3975 if (parse_host_port(saddr, src_str2) < 0)
951f1351
FB
3976 goto fail;
3977
3978 free(str);
3979 return(0);
3980
3981fail:
3982 free(str);
3983 return -1;
3984}
3985
7c9d8e07
FB
3986int parse_host_port(struct sockaddr_in *saddr, const char *str)
3987{
3988 char buf[512];
3989 struct hostent *he;
3990 const char *p, *r;
3991 int port;
3992
3993 p = str;
3994 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3995 return -1;
3996 saddr->sin_family = AF_INET;
3997 if (buf[0] == '\0') {
3998 saddr->sin_addr.s_addr = 0;
3999 } else {
4000 if (isdigit(buf[0])) {
4001 if (!inet_aton(buf, &saddr->sin_addr))
4002 return -1;
4003 } else {
7c9d8e07
FB
4004 if ((he = gethostbyname(buf)) == NULL)
4005 return - 1;
4006 saddr->sin_addr = *(struct in_addr *)he->h_addr;
7c9d8e07
FB
4007 }
4008 }
4009 port = strtol(p, (char **)&r, 0);
4010 if (r == p)
4011 return -1;
4012 saddr->sin_port = htons(port);
4013 return 0;
4014}
c20709aa 4015
52f61fde
TS
4016#ifndef _WIN32
4017static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
ffd843bc
TS
4018{
4019 const char *p;
4020 int len;
4021
4022 len = MIN(108, strlen(str));
4023 p = strchr(str, ',');
4024 if (p)
4025 len = MIN(len, p - str);
4026
4027 memset(uaddr, 0, sizeof(*uaddr));
4028
4029 uaddr->sun_family = AF_UNIX;
4030 memcpy(uaddr->sun_path, str, len);
4031
4032 return 0;
4033}
52f61fde 4034#endif
ffd843bc 4035
7c9d8e07
FB
4036/* find or alloc a new VLAN */
4037VLANState *qemu_find_vlan(int id)
c20709aa 4038{
7c9d8e07
FB
4039 VLANState **pvlan, *vlan;
4040 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4041 if (vlan->id == id)
4042 return vlan;
4043 }
4044 vlan = qemu_mallocz(sizeof(VLANState));
4045 if (!vlan)
4046 return NULL;
4047 vlan->id = id;
4048 vlan->next = NULL;
4049 pvlan = &first_vlan;
4050 while (*pvlan != NULL)
4051 pvlan = &(*pvlan)->next;
4052 *pvlan = vlan;
4053 return vlan;
c20709aa
FB
4054}
4055
7c9d8e07 4056VLANClientState *qemu_new_vlan_client(VLANState *vlan,
d861b05e
PB
4057 IOReadHandler *fd_read,
4058 IOCanRWHandler *fd_can_read,
4059 void *opaque)
c20709aa 4060{
7c9d8e07
FB
4061 VLANClientState *vc, **pvc;
4062 vc = qemu_mallocz(sizeof(VLANClientState));
4063 if (!vc)
4064 return NULL;
4065 vc->fd_read = fd_read;
d861b05e 4066 vc->fd_can_read = fd_can_read;
7c9d8e07
FB
4067 vc->opaque = opaque;
4068 vc->vlan = vlan;
4069
4070 vc->next = NULL;
4071 pvc = &vlan->first_client;
4072 while (*pvc != NULL)
4073 pvc = &(*pvc)->next;
4074 *pvc = vc;
4075 return vc;
c20709aa
FB
4076}
4077
dcf414d6
AZ
4078void qemu_del_vlan_client(VLANClientState *vc)
4079{
4080 VLANClientState **pvc = &vc->vlan->first_client;
4081
4082 while (*pvc != NULL)
4083 if (*pvc == vc) {
4084 *pvc = vc->next;
4085 free(vc);
4086 break;
4087 } else
4088 pvc = &(*pvc)->next;
4089}
4090
d861b05e
PB
4091int qemu_can_send_packet(VLANClientState *vc1)
4092{
4093 VLANState *vlan = vc1->vlan;
4094 VLANClientState *vc;
4095
4096 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4097 if (vc != vc1) {
fbd1711d
AZ
4098 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4099 return 1;
d861b05e
PB
4100 }
4101 }
fbd1711d 4102 return 0;
d861b05e
PB
4103}
4104
7c9d8e07 4105void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
c20709aa 4106{
7c9d8e07
FB
4107 VLANState *vlan = vc1->vlan;
4108 VLANClientState *vc;
4109
9dc63a1e 4110#ifdef DEBUG_NET
7c9d8e07
FB
4111 printf("vlan %d send:\n", vlan->id);
4112 hex_dump(stdout, buf, size);
4113#endif
4114 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4115 if (vc != vc1) {
4116 vc->fd_read(vc->opaque, buf, size);
4117 }
4118 }
67b915a5
FB
4119}
4120
c20709aa
FB
4121#if defined(CONFIG_SLIRP)
4122
4123/* slirp network adapter */
4124
c20709aa 4125static int slirp_inited;
7c9d8e07 4126static VLANClientState *slirp_vc;
c20709aa
FB
4127
4128int slirp_can_output(void)
4129{
3b7f5d47 4130 return !slirp_vc || qemu_can_send_packet(slirp_vc);
c20709aa
FB
4131}
4132
4133void slirp_output(const uint8_t *pkt, int pkt_len)
67b915a5 4134{
9dc63a1e 4135#ifdef DEBUG_SLIRP
7c9d8e07 4136 printf("slirp output:\n");
c20709aa
FB
4137 hex_dump(stdout, pkt, pkt_len);
4138#endif
3b7f5d47
PB
4139 if (!slirp_vc)
4140 return;
7c9d8e07 4141 qemu_send_packet(slirp_vc, pkt, pkt_len);
67b915a5
FB
4142}
4143
7c9d8e07 4144static void slirp_receive(void *opaque, const uint8_t *buf, int size)
c20709aa 4145{
9dc63a1e 4146#ifdef DEBUG_SLIRP
7c9d8e07 4147 printf("slirp input:\n");
c20709aa
FB
4148 hex_dump(stdout, buf, size);
4149#endif
4150 slirp_input(buf, size);
4151}
4152
7c9d8e07 4153static int net_slirp_init(VLANState *vlan)
c20709aa
FB
4154{
4155 if (!slirp_inited) {
4156 slirp_inited = 1;
4157 slirp_init();
4158 }
5fafdf24 4159 slirp_vc = qemu_new_vlan_client(vlan,
d861b05e 4160 slirp_receive, NULL, NULL);
7c9d8e07 4161 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
9bf05444
FB
4162 return 0;
4163}
4164
4165static void net_slirp_redir(const char *redir_str)
4166{
4167 int is_udp;
4168 char buf[256], *r;
4169 const char *p;
4170 struct in_addr guest_addr;
4171 int host_port, guest_port;
3b46e624 4172
9bf05444
FB
4173 if (!slirp_inited) {
4174 slirp_inited = 1;
4175 slirp_init();
4176 }
4177
4178 p = redir_str;
4179 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4180 goto fail;
4181 if (!strcmp(buf, "tcp")) {
4182 is_udp = 0;
4183 } else if (!strcmp(buf, "udp")) {
4184 is_udp = 1;
4185 } else {
4186 goto fail;
4187 }
4188
4189 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4190 goto fail;
4191 host_port = strtol(buf, &r, 0);
4192 if (r == buf)
4193 goto fail;
4194
4195 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4196 goto fail;
4197 if (buf[0] == '\0') {
4198 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4199 }
4200 if (!inet_aton(buf, &guest_addr))
4201 goto fail;
3b46e624 4202
9bf05444
FB
4203 guest_port = strtol(p, &r, 0);
4204 if (r == p)
4205 goto fail;
3b46e624 4206
9bf05444
FB
4207 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4208 fprintf(stderr, "qemu: could not set up redirection\n");
4209 exit(1);
4210 }
4211 return;
4212 fail:
4213 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4214 exit(1);
4215}
3b46e624 4216
c94c8d64
FB
4217#ifndef _WIN32
4218
dbed7e40 4219static char smb_dir[1024];
9d728e8c 4220
044fae83 4221static void erase_dir(char *dir_name)
9d728e8c
FB
4222{
4223 DIR *d;
4224 struct dirent *de;
4225 char filename[1024];
4226
4227 /* erase all the files in the directory */
044fae83
AZ
4228 if ((d = opendir(dir_name)) != 0) {
4229 for(;;) {
4230 de = readdir(d);
4231 if (!de)
4232 break;
4233 if (strcmp(de->d_name, ".") != 0 &&
4234 strcmp(de->d_name, "..") != 0) {
4235 snprintf(filename, sizeof(filename), "%s/%s",
4236 smb_dir, de->d_name);
4237 if (unlink(filename) != 0) /* is it a directory? */
4238 erase_dir(filename);
4239 }
9d728e8c 4240 }
044fae83
AZ
4241 closedir(d);
4242 rmdir(dir_name);
9d728e8c 4243 }
044fae83
AZ
4244}
4245
4246/* automatic user mode samba server configuration */
4247static void smb_exit(void)
4248{
4249 erase_dir(smb_dir);
9d728e8c
FB
4250}
4251
4252/* automatic user mode samba server configuration */
9596ebb7 4253static void net_slirp_smb(const char *exported_dir)
9d728e8c
FB
4254{
4255 char smb_conf[1024];
4256 char smb_cmdline[1024];
4257 FILE *f;
4258
4259 if (!slirp_inited) {
4260 slirp_inited = 1;
4261 slirp_init();
4262 }
4263
4264 /* XXX: better tmp dir construction */
4265 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4266 if (mkdir(smb_dir, 0700) < 0) {
4267 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4268 exit(1);
4269 }
4270 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3b46e624 4271
9d728e8c
FB
4272 f = fopen(smb_conf, "w");
4273 if (!f) {
4274 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4275 exit(1);
4276 }
5fafdf24 4277 fprintf(f,
9d728e8c 4278 "[global]\n"
157777ef
FB
4279 "private dir=%s\n"
4280 "smb ports=0\n"
4281 "socket address=127.0.0.1\n"
9d728e8c
FB
4282 "pid directory=%s\n"
4283 "lock directory=%s\n"
4284 "log file=%s/log.smbd\n"
4285 "smb passwd file=%s/smbpasswd\n"
03ffbb69 4286 "security = share\n"
9d728e8c
FB
4287 "[qemu]\n"
4288 "path=%s\n"
4289 "read only=no\n"
4290 "guest ok=yes\n",
4291 smb_dir,
157777ef 4292 smb_dir,
9d728e8c
FB
4293 smb_dir,
4294 smb_dir,
4295 smb_dir,
4296 exported_dir
4297 );
4298 fclose(f);
4299 atexit(smb_exit);
4300
a14d6c8c
PB
4301 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4302 SMBD_COMMAND, smb_conf);
3b46e624 4303
9d728e8c
FB
4304 slirp_add_exec(0, smb_cmdline, 4, 139);
4305}
9bf05444 4306
c94c8d64 4307#endif /* !defined(_WIN32) */
31a60e22
BS
4308void do_info_slirp(void)
4309{
4310 slirp_stats();
4311}
c94c8d64 4312
c20709aa
FB
4313#endif /* CONFIG_SLIRP */
4314
4315#if !defined(_WIN32)
7c9d8e07
FB
4316
4317typedef struct TAPState {
4318 VLANClientState *vc;
4319 int fd;
b46a8906 4320 char down_script[1024];
7c9d8e07
FB
4321} TAPState;
4322
4323static void tap_receive(void *opaque, const uint8_t *buf, int size)
4324{
4325 TAPState *s = opaque;
4326 int ret;
4327 for(;;) {
4328 ret = write(s->fd, buf, size);
4329 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4330 } else {
4331 break;
4332 }
4333 }
4334}
4335
4336static void tap_send(void *opaque)
4337{
4338 TAPState *s = opaque;
4339 uint8_t buf[4096];
4340 int size;
4341
d5d10bc3
TS
4342#ifdef __sun__
4343 struct strbuf sbuf;
4344 int f = 0;
4345 sbuf.maxlen = sizeof(buf);
4346 sbuf.buf = buf;
4347 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4348#else
7c9d8e07 4349 size = read(s->fd, buf, sizeof(buf));
d5d10bc3 4350#endif
7c9d8e07
FB
4351 if (size > 0) {
4352 qemu_send_packet(s->vc, buf, size);
4353 }
4354}
4355
4356/* fd support */
4357
4358static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4359{
4360 TAPState *s;
4361
4362 s = qemu_mallocz(sizeof(TAPState));
4363 if (!s)
4364 return NULL;
4365 s->fd = fd;
d861b05e 4366 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
7c9d8e07
FB
4367 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4368 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4369 return s;
4370}
4371
5c40d2bd 4372#if defined (_BSD) || defined (__FreeBSD_kernel__)
7c9d8e07 4373static int tap_open(char *ifname, int ifname_size)
7d3505c5
FB
4374{
4375 int fd;
4376 char *dev;
4377 struct stat s;
67b915a5 4378
aeb30be6 4379 TFR(fd = open("/dev/tap", O_RDWR));
7d3505c5
FB
4380 if (fd < 0) {
4381 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4382 return -1;
4383 }
4384
4385 fstat(fd, &s);
4386 dev = devname(s.st_rdev, S_IFCHR);
4387 pstrcpy(ifname, ifname_size, dev);
4388
4389 fcntl(fd, F_SETFL, O_NONBLOCK);
4390 return fd;
4391}
ec530c81 4392#elif defined(__sun__)
d5d10bc3 4393#define TUNNEWPPA (('T'<<16) | 0x0001)
5fafdf24
TS
4394/*
4395 * Allocate TAP device, returns opened fd.
d5d10bc3 4396 * Stores dev name in the first arg(must be large enough).
3b46e624 4397 */
363a37d5 4398int tap_alloc(char *dev, size_t dev_size)
d5d10bc3
TS
4399{
4400 int tap_fd, if_fd, ppa = -1;
4401 static int ip_fd = 0;
4402 char *ptr;
4403
4404 static int arp_fd = 0;
4405 int ip_muxid, arp_muxid;
4406 struct strioctl strioc_if, strioc_ppa;
4407 int link_type = I_PLINK;;
4408 struct lifreq ifr;
4409 char actual_name[32] = "";
4410
4411 memset(&ifr, 0x0, sizeof(ifr));
4412
4413 if( *dev ){
5fafdf24
TS
4414 ptr = dev;
4415 while( *ptr && !isdigit((int)*ptr) ) ptr++;
d5d10bc3
TS
4416 ppa = atoi(ptr);
4417 }
4418
4419 /* Check if IP device was opened */
4420 if( ip_fd )
4421 close(ip_fd);
4422
aeb30be6
AZ
4423 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4424 if (ip_fd < 0) {
d5d10bc3
TS
4425 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4426 return -1;
4427 }
4428
aeb30be6
AZ
4429 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4430 if (tap_fd < 0) {
d5d10bc3
TS
4431 syslog(LOG_ERR, "Can't open /dev/tap");
4432 return -1;
4433 }
4434
4435 /* Assign a new PPA and get its unit number. */
4436 strioc_ppa.ic_cmd = TUNNEWPPA;
4437 strioc_ppa.ic_timout = 0;
4438 strioc_ppa.ic_len = sizeof(ppa);
4439 strioc_ppa.ic_dp = (char *)&ppa;
4440 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4441 syslog (LOG_ERR, "Can't assign new interface");
4442
aeb30be6
AZ
4443 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4444 if (if_fd < 0) {
d5d10bc3
TS
4445 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4446 return -1;
4447 }
4448 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4449 syslog(LOG_ERR, "Can't push IP module");
4450 return -1;
4451 }
4452
4453 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4454 syslog(LOG_ERR, "Can't get flags\n");
4455
4456 snprintf (actual_name, 32, "tap%d", ppa);
4457 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4458
4459 ifr.lifr_ppa = ppa;
4460 /* Assign ppa according to the unit number returned by tun device */
4461
4462 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4463 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4464 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4465 syslog (LOG_ERR, "Can't get flags\n");
4466 /* Push arp module to if_fd */
4467 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4468 syslog (LOG_ERR, "Can't push ARP module (2)");
4469
4470 /* Push arp module to ip_fd */
4471 if (ioctl (ip_fd, I_POP, NULL) < 0)
4472 syslog (LOG_ERR, "I_POP failed\n");
4473 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4474 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4475 /* Open arp_fd */
aeb30be6
AZ
4476 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4477 if (arp_fd < 0)
d5d10bc3
TS
4478 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4479
4480 /* Set ifname to arp */
4481 strioc_if.ic_cmd = SIOCSLIFNAME;
4482 strioc_if.ic_timout = 0;
4483 strioc_if.ic_len = sizeof(ifr);
4484 strioc_if.ic_dp = (char *)&ifr;
4485 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4486 syslog (LOG_ERR, "Can't set ifname to arp\n");
4487 }
4488
4489 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4490 syslog(LOG_ERR, "Can't link TAP device to IP");
4491 return -1;
4492 }
4493
4494 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4495 syslog (LOG_ERR, "Can't link TAP device to ARP");
4496
4497 close (if_fd);
4498
4499 memset(&ifr, 0x0, sizeof(ifr));
4500 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4501 ifr.lifr_ip_muxid = ip_muxid;
4502 ifr.lifr_arp_muxid = arp_muxid;
4503
4504 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4505 {
4506 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4507 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4508 syslog (LOG_ERR, "Can't set multiplexor id");
4509 }
4510
363a37d5 4511 snprintf(dev, dev_size, "tap%d", ppa);
d5d10bc3
TS
4512 return tap_fd;
4513}
4514
ec530c81
FB
4515static int tap_open(char *ifname, int ifname_size)
4516{
d5d10bc3
TS
4517 char dev[10]="";
4518 int fd;
363a37d5 4519 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
d5d10bc3
TS
4520 fprintf(stderr, "Cannot allocate TAP device\n");
4521 return -1;
4522 }
4523 pstrcpy(ifname, ifname_size, dev);
4524 fcntl(fd, F_SETFL, O_NONBLOCK);
4525 return fd;
ec530c81 4526}
7d3505c5 4527#else
7c9d8e07 4528static int tap_open(char *ifname, int ifname_size)
330d0414 4529{
80cabfad 4530 struct ifreq ifr;
c4b1fcc0 4531 int fd, ret;
3b46e624 4532
aeb30be6 4533 TFR(fd = open("/dev/net/tun", O_RDWR));
80cabfad
FB
4534 if (fd < 0) {
4535 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4536 return -1;
330d0414 4537 }
80cabfad
FB
4538 memset(&ifr, 0, sizeof(ifr));
4539 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
7c9d8e07
FB
4540 if (ifname[0] != '\0')
4541 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4542 else
4543 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
80cabfad
FB
4544 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4545 if (ret != 0) {
4546 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4547 close(fd);
4548 return -1;
4549 }
c4b1fcc0 4550 pstrcpy(ifname, ifname_size, ifr.ifr_name);
80cabfad 4551 fcntl(fd, F_SETFL, O_NONBLOCK);
c4b1fcc0
FB
4552 return fd;
4553}
7d3505c5 4554#endif
330d0414 4555
b46a8906 4556static int launch_script(const char *setup_script, const char *ifname, int fd)
7c9d8e07 4557{
b46a8906 4558 int pid, status;
7c9d8e07
FB
4559 char *args[3];
4560 char **parg;
7c9d8e07 4561
b46a8906 4562 /* try to launch network script */
7c9d8e07
FB
4563 pid = fork();
4564 if (pid >= 0) {
4565 if (pid == 0) {
50d3eeae
TS
4566 int open_max = sysconf (_SC_OPEN_MAX), i;
4567 for (i = 0; i < open_max; i++)
4568 if (i != STDIN_FILENO &&
4569 i != STDOUT_FILENO &&
4570 i != STDERR_FILENO &&
4571 i != fd)
4572 close(i);
4573
7c9d8e07
FB
4574 parg = args;
4575 *parg++ = (char *)setup_script;
b46a8906 4576 *parg++ = (char *)ifname;
7c9d8e07
FB
4577 *parg++ = NULL;
4578 execv(setup_script, args);
4a38940d 4579 _exit(1);
7c9d8e07
FB
4580 }
4581 while (waitpid(pid, &status, 0) != pid);
4582 if (!WIFEXITED(status) ||
4583 WEXITSTATUS(status) != 0) {
4584 fprintf(stderr, "%s: could not launch network script\n",
4585 setup_script);
4586 return -1;
4587 }
4588 }
b46a8906
TS
4589 return 0;
4590}
4591
4592static int net_tap_init(VLANState *vlan, const char *ifname1,
4593 const char *setup_script, const char *down_script)
4594{
4595 TAPState *s;
4596 int fd;
4597 char ifname[128];
4598
4599 if (ifname1 != NULL)
4600 pstrcpy(ifname, sizeof(ifname), ifname1);
4601 else
4602 ifname[0] = '\0';
4603 TFR(fd = tap_open(ifname, sizeof(ifname)));
4604 if (fd < 0)
4605 return -1;
4606
4607 if (!setup_script || !strcmp(setup_script, "no"))
4608 setup_script = "";
4609 if (setup_script[0] != '\0') {
4610 if (launch_script(setup_script, ifname, fd))
4611 return -1;
7c9d8e07
FB
4612 }
4613 s = net_tap_fd_init(vlan, fd);
4614 if (!s)
4615 return -1;
5fafdf24 4616 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
7c9d8e07 4617 "tap: ifname=%s setup_script=%s", ifname, setup_script);
b46a8906
TS
4618 if (down_script && strcmp(down_script, "no"))
4619 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
7c9d8e07
FB
4620 return 0;
4621}
4622
fd1dff4b
FB
4623#endif /* !_WIN32 */
4624
8a16d273
TS
4625#if defined(CONFIG_VDE)
4626typedef struct VDEState {
4627 VLANClientState *vc;
4628 VDECONN *vde;
4629} VDEState;
4630
4631static void vde_to_qemu(void *opaque)
4632{
4633 VDEState *s = opaque;
4634 uint8_t buf[4096];
4635 int size;
4636
4637 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4638 if (size > 0) {
4639 qemu_send_packet(s->vc, buf, size);
4640 }
4641}
4642
4643static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4644{
4645 VDEState *s = opaque;
4646 int ret;
4647 for(;;) {
4648 ret = vde_send(s->vde, buf, size, 0);
4649 if (ret < 0 && errno == EINTR) {
4650 } else {
4651 break;
4652 }
4653 }
4654}
4655
4656static int net_vde_init(VLANState *vlan, const char *sock, int port,
4657 const char *group, int mode)
4658{
4659 VDEState *s;
4660 char *init_group = strlen(group) ? (char *)group : NULL;
4661 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4662
4663 struct vde_open_args args = {
4664 .port = port,
4665 .group = init_group,
4666 .mode = mode,
4667 };
4668
4669 s = qemu_mallocz(sizeof(VDEState));
4670 if (!s)
4671 return -1;
4672 s->vde = vde_open(init_sock, "QEMU", &args);
4673 if (!s->vde){
4674 free(s);
4675 return -1;
4676 }
4677 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4678 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4679 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4680 sock, vde_datafd(s->vde));
4681 return 0;
4682}
4683#endif
4684
7c9d8e07
FB
4685/* network connection */
4686typedef struct NetSocketState {
4687 VLANClientState *vc;
4688 int fd;
4689 int state; /* 0 = getting length, 1 = getting data */
4690 int index;
4691 int packet_len;
4692 uint8_t buf[4096];
3d830459 4693 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
7c9d8e07
FB
4694} NetSocketState;
4695
4696typedef struct NetSocketListenState {
4697 VLANState *vlan;
4698 int fd;
4699} NetSocketListenState;
4700
4701/* XXX: we consider we can send the whole packet without blocking */
4702static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
c20709aa 4703{
7c9d8e07
FB
4704 NetSocketState *s = opaque;
4705 uint32_t len;
4706 len = htonl(size);
4707
fd1dff4b
FB
4708 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4709 send_all(s->fd, buf, size);
c20709aa
FB
4710}
4711
3d830459
FB
4712static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4713{
4714 NetSocketState *s = opaque;
5fafdf24 4715 sendto(s->fd, buf, size, 0,
3d830459
FB
4716 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4717}
4718
7c9d8e07 4719static void net_socket_send(void *opaque)
c4b1fcc0 4720{
7c9d8e07 4721 NetSocketState *s = opaque;
fd1dff4b 4722 int l, size, err;
7c9d8e07
FB
4723 uint8_t buf1[4096];
4724 const uint8_t *buf;
4725
fd1dff4b
FB
4726 size = recv(s->fd, buf1, sizeof(buf1), 0);
4727 if (size < 0) {
4728 err = socket_error();
5fafdf24 4729 if (err != EWOULDBLOCK)
fd1dff4b
FB
4730 goto eoc;
4731 } else if (size == 0) {
7c9d8e07 4732 /* end of connection */
fd1dff4b 4733 eoc:
7c9d8e07 4734 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
fd1dff4b 4735 closesocket(s->fd);
7c9d8e07
FB
4736 return;
4737 }
4738 buf = buf1;
4739 while (size > 0) {
4740 /* reassemble a packet from the network */
4741 switch(s->state) {
4742 case 0:
4743 l = 4 - s->index;
4744 if (l > size)
4745 l = size;
4746 memcpy(s->buf + s->index, buf, l);
4747 buf += l;
4748 size -= l;
4749 s->index += l;
4750 if (s->index == 4) {
4751 /* got length */
4752 s->packet_len = ntohl(*(uint32_t *)s->buf);
4753 s->index = 0;
4754 s->state = 1;
4755 }
4756 break;
4757 case 1:
4758 l = s->packet_len - s->index;
4759 if (l > size)
4760 l = size;
4761 memcpy(s->buf + s->index, buf, l);
4762 s->index += l;
4763 buf += l;
4764 size -= l;
4765 if (s->index >= s->packet_len) {
4766 qemu_send_packet(s->vc, s->buf, s->packet_len);
4767 s->index = 0;
4768 s->state = 0;
4769 }
4770 break;
4771 }
4772 }
c20709aa
FB
4773}
4774
3d830459
FB
4775static void net_socket_send_dgram(void *opaque)
4776{
4777 NetSocketState *s = opaque;
4778 int size;
4779
4780 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
5fafdf24 4781 if (size < 0)
3d830459
FB
4782 return;
4783 if (size == 0) {
4784 /* end of connection */
4785 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4786 return;
4787 }
4788 qemu_send_packet(s->vc, s->buf, size);
4789}
4790
4791static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4792{
4793 struct ip_mreq imr;
4794 int fd;
4795 int val, ret;
4796 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4797 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5fafdf24 4798 inet_ntoa(mcastaddr->sin_addr),
fd1dff4b 4799 (int)ntohl(mcastaddr->sin_addr.s_addr));
3d830459
FB
4800 return -1;
4801
4802 }
4803 fd = socket(PF_INET, SOCK_DGRAM, 0);
4804 if (fd < 0) {
4805 perror("socket(PF_INET, SOCK_DGRAM)");
4806 return -1;
4807 }
4808
fd1dff4b 4809 val = 1;
5fafdf24 4810 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
fd1dff4b
FB
4811 (const char *)&val, sizeof(val));
4812 if (ret < 0) {
4813 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4814 goto fail;
4815 }
4816
4817 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4818 if (ret < 0) {
4819 perror("bind");
4820 goto fail;
4821 }
3b46e624 4822
3d830459
FB
4823 /* Add host to multicast group */
4824 imr.imr_multiaddr = mcastaddr->sin_addr;
4825 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4826
5fafdf24 4827 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
fd1dff4b 4828 (const char *)&imr, sizeof(struct ip_mreq));
3d830459
FB
4829 if (ret < 0) {
4830 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4831 goto fail;
4832 }
4833
4834 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4835 val = 1;
5fafdf24 4836 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
fd1dff4b 4837 (const char *)&val, sizeof(val));
3d830459
FB
4838 if (ret < 0) {
4839 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4840 goto fail;
4841 }
4842
fd1dff4b 4843 socket_set_nonblock(fd);
3d830459
FB
4844 return fd;
4845fail:
5fafdf24 4846 if (fd >= 0)
0bab00f3 4847 closesocket(fd);
3d830459
FB
4848 return -1;
4849}
4850
5fafdf24 4851static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3d830459
FB
4852 int is_connected)
4853{
4854 struct sockaddr_in saddr;
4855 int newfd;
4856 socklen_t saddr_len;
4857 NetSocketState *s;
4858
4859 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5fafdf24 4860 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3d830459
FB
4861 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4862 */
4863
4864 if (is_connected) {
4865 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4866 /* must be bound */
4867 if (saddr.sin_addr.s_addr==0) {
4868 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4869 fd);
4870 return NULL;
4871 }
4872 /* clone dgram socket */
4873 newfd = net_socket_mcast_create(&saddr);
4874 if (newfd < 0) {
4875 /* error already reported by net_socket_mcast_create() */
4876 close(fd);
4877 return NULL;
4878 }
4879 /* clone newfd to fd, close newfd */
4880 dup2(newfd, fd);
4881 close(newfd);
5fafdf24 4882
3d830459
FB
4883 } else {
4884 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4885 fd, strerror(errno));
4886 return NULL;
4887 }
4888 }
4889
4890 s = qemu_mallocz(sizeof(NetSocketState));
4891 if (!s)
4892 return NULL;
4893 s->fd = fd;
4894
d861b05e 4895 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3d830459
FB
4896 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4897
4898 /* mcast: save bound address as dst */
4899 if (is_connected) s->dgram_dst=saddr;
4900
4901 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5fafdf24 4902 "socket: fd=%d (%s mcast=%s:%d)",
3d830459
FB
4903 fd, is_connected? "cloned" : "",
4904 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4905 return s;
4906}
4907
7c9d8e07 4908static void net_socket_connect(void *opaque)
c20709aa 4909{
7c9d8e07
FB
4910 NetSocketState *s = opaque;
4911 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4912}
c4b1fcc0 4913
5fafdf24 4914static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
7c9d8e07
FB
4915 int is_connected)
4916{
4917 NetSocketState *s;
4918 s = qemu_mallocz(sizeof(NetSocketState));
4919 if (!s)
4920 return NULL;
4921 s->fd = fd;
5fafdf24 4922 s->vc = qemu_new_vlan_client(vlan,
d861b05e 4923 net_socket_receive, NULL, s);
7c9d8e07
FB
4924 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4925 "socket: fd=%d", fd);
4926 if (is_connected) {
4927 net_socket_connect(s);
4928 } else {
4929 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4930 }
4931 return s;
4932}
c4b1fcc0 4933
5fafdf24 4934static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3d830459
FB
4935 int is_connected)
4936{
4937 int so_type=-1, optlen=sizeof(so_type);
4938
69b34976
TS
4939 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4940 (socklen_t *)&optlen)< 0) {
931f03ee 4941 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3d830459
FB
4942 return NULL;
4943 }
4944 switch(so_type) {
4945 case SOCK_DGRAM:
4946 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4947 case SOCK_STREAM:
4948 return net_socket_fd_init_stream(vlan, fd, is_connected);
4949 default:
4950 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4951 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4952 return net_socket_fd_init_stream(vlan, fd, is_connected);
4953 }
4954 return NULL;
4955}
4956
7c9d8e07
FB
4957static void net_socket_accept(void *opaque)
4958{
3b46e624 4959 NetSocketListenState *s = opaque;
7c9d8e07
FB
4960 NetSocketState *s1;
4961 struct sockaddr_in saddr;
4962 socklen_t len;
4963 int fd;
4964
4965 for(;;) {
4966 len = sizeof(saddr);
4967 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4968 if (fd < 0 && errno != EINTR) {
4969 return;
4970 } else if (fd >= 0) {
4971 break;
80cabfad 4972 }
330d0414 4973 }
5fafdf24 4974 s1 = net_socket_fd_init(s->vlan, fd, 1);
7c9d8e07 4975 if (!s1) {
0bab00f3 4976 closesocket(fd);
7c9d8e07
FB
4977 } else {
4978 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5fafdf24 4979 "socket: connection from %s:%d",
7c9d8e07
FB
4980 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4981 }
4982}
4983
4984static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4985{
4986 NetSocketListenState *s;
4987 int fd, val, ret;
4988 struct sockaddr_in saddr;
4989
4990 if (parse_host_port(&saddr, host_str) < 0)
4991 return -1;
3b46e624 4992
7c9d8e07
FB
4993 s = qemu_mallocz(sizeof(NetSocketListenState));
4994 if (!s)
4995 return -1;
4996
4997 fd = socket(PF_INET, SOCK_STREAM, 0);
4998 if (fd < 0) {
4999 perror("socket");
5000 return -1;
5001 }
fd1dff4b 5002 socket_set_nonblock(fd);
7c9d8e07
FB
5003
5004 /* allow fast reuse */
5005 val = 1;
fd1dff4b 5006 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3b46e624 5007
7c9d8e07
FB
5008 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5009 if (ret < 0) {
5010 perror("bind");
5011 return -1;
5012 }
5013 ret = listen(fd, 0);
5014 if (ret < 0) {
5015 perror("listen");
5016 return -1;
5017 }
5018 s->vlan = vlan;
5019 s->fd = fd;
5020 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
80cabfad 5021 return 0;
330d0414
FB
5022}
5023
7c9d8e07 5024static int net_socket_connect_init(VLANState *vlan, const char *host_str)
330d0414 5025{
7c9d8e07 5026 NetSocketState *s;
fd1dff4b 5027 int fd, connected, ret, err;
7c9d8e07
FB
5028 struct sockaddr_in saddr;
5029
5030 if (parse_host_port(&saddr, host_str) < 0)
5031 return -1;
5032
5033 fd = socket(PF_INET, SOCK_STREAM, 0);
5034 if (fd < 0) {
5035 perror("socket");
5036 return -1;
5037 }
fd1dff4b 5038 socket_set_nonblock(fd);
7c9d8e07
FB
5039
5040 connected = 0;
5041 for(;;) {
5042 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5043 if (ret < 0) {
fd1dff4b
FB
5044 err = socket_error();
5045 if (err == EINTR || err == EWOULDBLOCK) {
5046 } else if (err == EINPROGRESS) {
7c9d8e07 5047 break;
f5b12268
TS
5048#ifdef _WIN32
5049 } else if (err == WSAEALREADY) {
5050 break;
5051#endif
7c9d8e07
FB
5052 } else {
5053 perror("connect");
fd1dff4b 5054 closesocket(fd);
7c9d8e07
FB
5055 return -1;
5056 }
5057 } else {
5058 connected = 1;
5059 break;
5060 }
5061 }
5062 s = net_socket_fd_init(vlan, fd, connected);
5063 if (!s)
5064 return -1;
5065 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5fafdf24 5066 "socket: connect to %s:%d",
7c9d8e07 5067 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
c20709aa 5068 return 0;
80cabfad 5069}
330d0414 5070
3d830459
FB
5071static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5072{
5073 NetSocketState *s;
5074 int fd;
5075 struct sockaddr_in saddr;
5076
5077 if (parse_host_port(&saddr, host_str) < 0)
5078 return -1;
5079
5080
5081 fd = net_socket_mcast_create(&saddr);
5082 if (fd < 0)
5083 return -1;
5084
5085 s = net_socket_fd_init(vlan, fd, 0);
5086 if (!s)
5087 return -1;
5088
5089 s->dgram_dst = saddr;
3b46e624 5090
3d830459 5091 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5fafdf24 5092 "socket: mcast=%s:%d",
3d830459
FB
5093 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5094 return 0;
5095
5096}
5097
609497ab
AZ
5098static const char *get_opt_name(char *buf, int buf_size, const char *p)
5099{
5100 char *q;
5101
5102 q = buf;
5103 while (*p != '\0' && *p != '=') {
5104 if (q && (q - buf) < buf_size - 1)
5105 *q++ = *p;
5106 p++;
5107 }
5108 if (q)
5109 *q = '\0';
5110
5111 return p;
5112}
5113
5114static const char *get_opt_value(char *buf, int buf_size, const char *p)
e4bcb14c
TS
5115{
5116 char *q;
e4bcb14c 5117
e4bcb14c
TS
5118 q = buf;
5119 while (*p != '\0') {
609497ab
AZ
5120 if (*p == ',') {
5121 if (*(p + 1) != ',')
e4bcb14c 5122 break;
e4bcb14c 5123 p++;
609497ab 5124 }
e4bcb14c
TS
5125 if (q && (q - buf) < buf_size - 1)
5126 *q++ = *p;
5127 p++;
5128 }
5129 if (q)
5130 *q = '\0';
5131
5132 return p;
5133}
5134
7c9d8e07
FB
5135static int get_param_value(char *buf, int buf_size,
5136 const char *tag, const char *str)
5137{
5138 const char *p;
7c9d8e07
FB
5139 char option[128];
5140
5141 p = str;
5142 for(;;) {
609497ab 5143 p = get_opt_name(option, sizeof(option), p);
7c9d8e07
FB
5144 if (*p != '=')
5145 break;
5146 p++;
5147 if (!strcmp(tag, option)) {
609497ab 5148 (void)get_opt_value(buf, buf_size, p);
e4bcb14c 5149 return strlen(buf);
7c9d8e07 5150 } else {
609497ab 5151 p = get_opt_value(NULL, 0, p);
7c9d8e07
FB
5152 }
5153 if (*p != ',')
5154 break;
5155 p++;
5156 }
5157 return 0;
5158}
5159
e4bcb14c 5160static int check_params(char *buf, int buf_size,
7ccfb2eb 5161 const char * const *params, const char *str)
e4bcb14c
TS
5162{
5163 const char *p;
5164 int i;
5165
5166 p = str;
5167 for(;;) {
609497ab 5168 p = get_opt_name(buf, buf_size, p);
e4bcb14c
TS
5169 if (*p != '=')
5170 return -1;
5171 p++;
5172 for(i = 0; params[i] != NULL; i++)
5173 if (!strcmp(params[i], buf))
5174 break;
5175 if (params[i] == NULL)
5176 return -1;
609497ab 5177 p = get_opt_value(NULL, 0, p);
e4bcb14c
TS
5178 if (*p != ',')
5179 break;
5180 p++;
5181 }
5182 return 0;
5183}
5184
9ad97e65 5185static int net_client_init(const char *device, const char *p)
7c9d8e07 5186{
7c9d8e07
FB
5187 char buf[1024];
5188 int vlan_id, ret;
5189 VLANState *vlan;
5190
7c9d8e07
FB
5191 vlan_id = 0;
5192 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5193 vlan_id = strtol(buf, NULL, 0);
5194 }
5195 vlan = qemu_find_vlan(vlan_id);
5196 if (!vlan) {
5197 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5198 return -1;
5199 }
5200 if (!strcmp(device, "nic")) {
5201 NICInfo *nd;
5202 uint8_t *macaddr;
5203
5204 if (nb_nics >= MAX_NICS) {
5205 fprintf(stderr, "Too Many NICs\n");
5206 return -1;
5207 }
5208 nd = &nd_table[nb_nics];
5209 macaddr = nd->macaddr;
5210 macaddr[0] = 0x52;
5211 macaddr[1] = 0x54;
5212 macaddr[2] = 0x00;
5213 macaddr[3] = 0x12;
5214 macaddr[4] = 0x34;
5215 macaddr[5] = 0x56 + nb_nics;
5216
5217 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5218 if (parse_macaddr(macaddr, buf) < 0) {
5219 fprintf(stderr, "invalid syntax for ethernet address\n");
5220 return -1;
5221 }
5222 }
a41b2ff2
PB
5223 if (get_param_value(buf, sizeof(buf), "model", p)) {
5224 nd->model = strdup(buf);
5225 }
7c9d8e07
FB
5226 nd->vlan = vlan;
5227 nb_nics++;
833c7174 5228 vlan->nb_guest_devs++;
7c9d8e07
FB
5229 ret = 0;
5230 } else
5231 if (!strcmp(device, "none")) {
5232 /* does nothing. It is needed to signal that no network cards
5233 are wanted */
5234 ret = 0;
5235 } else
5236#ifdef CONFIG_SLIRP
5237 if (!strcmp(device, "user")) {
115defd1 5238 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3f423c9c 5239 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
115defd1 5240 }
833c7174 5241 vlan->nb_host_devs++;
7c9d8e07
FB
5242 ret = net_slirp_init(vlan);
5243 } else
5244#endif
7fb843f8
FB
5245#ifdef _WIN32
5246 if (!strcmp(device, "tap")) {
5247 char ifname[64];
5248 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5249 fprintf(stderr, "tap: no interface name\n");
5250 return -1;
5251 }
833c7174 5252 vlan->nb_host_devs++;
7fb843f8
FB
5253 ret = tap_win32_init(vlan, ifname);
5254 } else
5255#else
7c9d8e07
FB
5256 if (!strcmp(device, "tap")) {
5257 char ifname[64];
b46a8906 5258 char setup_script[1024], down_script[1024];
7c9d8e07 5259 int fd;
4f01035f 5260 vlan->nb_host_devs++;
7c9d8e07
FB
5261 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5262 fd = strtol(buf, NULL, 0);
64538cdf 5263 fcntl(fd, F_SETFL, O_NONBLOCK);
7c9d8e07
FB
5264 ret = -1;
5265 if (net_tap_fd_init(vlan, fd))
5266 ret = 0;
5267 } else {
bf8c5342
FB
5268 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5269 ifname[0] = '\0';
5270 }
7c9d8e07
FB
5271 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5272 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5273 }
b46a8906
TS
5274 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5275 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5276 }
5277 ret = net_tap_init(vlan, ifname, setup_script, down_script);
7c9d8e07
FB
5278 }
5279 } else
fd1dff4b 5280#endif
7c9d8e07
FB
5281 if (!strcmp(device, "socket")) {
5282 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5283 int fd;
5284 fd = strtol(buf, NULL, 0);
5285 ret = -1;
5286 if (net_socket_fd_init(vlan, fd, 1))
5287 ret = 0;
5288 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5289 ret = net_socket_listen_init(vlan, buf);
5290 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5291 ret = net_socket_connect_init(vlan, buf);
3d830459
FB
5292 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5293 ret = net_socket_mcast_init(vlan, buf);
7c9d8e07
FB
5294 } else {
5295 fprintf(stderr, "Unknown socket options: %s\n", p);
5296 return -1;
5297 }
833c7174 5298 vlan->nb_host_devs++;
7c9d8e07 5299 } else
8a16d273
TS
5300#ifdef CONFIG_VDE
5301 if (!strcmp(device, "vde")) {
5302 char vde_sock[1024], vde_group[512];
5303 int vde_port, vde_mode;
5304 vlan->nb_host_devs++;
5305 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5306 vde_sock[0] = '\0';
5307 }
5308 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5309 vde_port = strtol(buf, NULL, 10);
5310 } else {
5311 vde_port = 0;
5312 }
5313 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5314 vde_group[0] = '\0';
5315 }
5316 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5317 vde_mode = strtol(buf, NULL, 8);
5318 } else {
5319 vde_mode = 0700;
5320 }
5321 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5322 } else
5323#endif
7c9d8e07
FB
5324 {
5325 fprintf(stderr, "Unknown network device: %s\n", device);
5326 return -1;
5327 }
5328 if (ret < 0) {
5329 fprintf(stderr, "Could not initialize device '%s'\n", device);
5330 }
3b46e624 5331
7c9d8e07
FB
5332 return ret;
5333}
5334
9ad97e65
AZ
5335static int net_client_parse(const char *str)
5336{
5337 const char *p;
5338 char *q;
5339 char device[64];
5340
5341 p = str;
5342 q = device;
5343 while (*p != '\0' && *p != ',') {
5344 if ((q - device) < sizeof(device) - 1)
5345 *q++ = *p;
5346 p++;
5347 }
5348 *q = '\0';
5349 if (*p == ',')
5350 p++;
5351
5352 return net_client_init(device, p);
5353}
5354
7c9d8e07
FB
5355void do_info_network(void)
5356{
5357 VLANState *vlan;
5358 VLANClientState *vc;
5359
5360 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5361 term_printf("VLAN %d devices:\n", vlan->id);
5362 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5363 term_printf(" %s\n", vc->info_str);
5364 }
5365}
42550fde 5366
1ae26a18
AZ
5367/***********************************************************/
5368/* Bluetooth support */
5369static int nb_hcis;
5370static int cur_hci;
5371static struct HCIInfo *hci_table[MAX_NICS];
5372static struct bt_vlan_s {
5373 struct bt_scatternet_s net;
5374 int id;
5375 struct bt_vlan_s *next;
5376} *first_bt_vlan;
5377
5378/* find or alloc a new bluetooth "VLAN" */
674bb261 5379static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1ae26a18
AZ
5380{
5381 struct bt_vlan_s **pvlan, *vlan;
5382 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
5383 if (vlan->id == id)
5384 return &vlan->net;
5385 }
5386 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
5387 vlan->id = id;
5388 pvlan = &first_bt_vlan;
5389 while (*pvlan != NULL)
5390 pvlan = &(*pvlan)->next;
5391 *pvlan = vlan;
5392 return &vlan->net;
5393}
5394
5395static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
5396{
5397}
5398
5399static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
5400{
5401 return -ENOTSUP;
5402}
5403
5404static struct HCIInfo null_hci = {
5405 .cmd_send = null_hci_send,
5406 .sco_send = null_hci_send,
5407 .acl_send = null_hci_send,
5408 .bdaddr_set = null_hci_addr_set,
5409};
5410
5411struct HCIInfo *qemu_next_hci(void)
5412{
5413 if (cur_hci == nb_hcis)
5414 return &null_hci;
5415
5416 return hci_table[cur_hci++];
5417}
5418
5419/***********************************************************/
5420/* QEMU Block devices */
5421
609497ab 5422#define HD_ALIAS "index=%d,media=disk"
e4bcb14c
TS
5423#ifdef TARGET_PPC
5424#define CDROM_ALIAS "index=1,media=cdrom"
5425#else
5426#define CDROM_ALIAS "index=2,media=cdrom"
5427#endif
5428#define FD_ALIAS "index=%d,if=floppy"
609497ab
AZ
5429#define PFLASH_ALIAS "if=pflash"
5430#define MTD_ALIAS "if=mtd"
9d413d1d 5431#define SD_ALIAS "index=0,if=sd"
e4bcb14c 5432
609497ab 5433static int drive_add(const char *file, const char *fmt, ...)
e4bcb14c
TS
5434{
5435 va_list ap;
5436
5437 if (nb_drives_opt >= MAX_DRIVES) {
5438 fprintf(stderr, "qemu: too many drives\n");
5439 exit(1);
5440 }
5441
609497ab 5442 drives_opt[nb_drives_opt].file = file;
e4bcb14c 5443 va_start(ap, fmt);
609497ab
AZ
5444 vsnprintf(drives_opt[nb_drives_opt].opt,
5445 sizeof(drives_opt[0].opt), fmt, ap);
e4bcb14c
TS
5446 va_end(ap);
5447
5448 return nb_drives_opt++;
5449}
5450
f60d39bc 5451int drive_get_index(BlockInterfaceType type, int bus, int unit)
e4bcb14c
TS
5452{
5453 int index;
5454
5455 /* seek interface, bus and unit */
5456
5457 for (index = 0; index < nb_drives; index++)
f60d39bc 5458 if (drives_table[index].type == type &&
e4bcb14c
TS
5459 drives_table[index].bus == bus &&
5460 drives_table[index].unit == unit)
5461 return index;
5462
5463 return -1;
5464}
5465
f60d39bc 5466int drive_get_max_bus(BlockInterfaceType type)
e4bcb14c
TS
5467{
5468 int max_bus;
5469 int index;
5470
5471 max_bus = -1;
5472 for (index = 0; index < nb_drives; index++) {
f60d39bc 5473 if(drives_table[index].type == type &&
e4bcb14c
TS
5474 drives_table[index].bus > max_bus)
5475 max_bus = drives_table[index].bus;
5476 }
5477 return max_bus;
5478}
5479
a1620fac
AJ
5480static void bdrv_format_print(void *opaque, const char *name)
5481{
5482 fprintf(stderr, " %s", name);
5483}
5484
609497ab
AZ
5485static int drive_init(struct drive_opt *arg, int snapshot,
5486 QEMUMachine *machine)
e4bcb14c
TS
5487{
5488 char buf[128];
5489 char file[1024];
c8522bdf
AZ
5490 char devname[128];
5491 const char *mediastr = "";
f60d39bc 5492 BlockInterfaceType type;
e4bcb14c
TS
5493 enum { MEDIA_DISK, MEDIA_CDROM } media;
5494 int bus_id, unit_id;
5495 int cyls, heads, secs, translation;
5496 BlockDriverState *bdrv;
1e72d3b7 5497 BlockDriver *drv = NULL;
e4bcb14c
TS
5498 int max_devs;
5499 int index;
33f00271
AZ
5500 int cache;
5501 int bdrv_flags;
609497ab 5502 char *str = arg->opt;
7ccfb2eb
BS
5503 static const char * const params[] = { "bus", "unit", "if", "index",
5504 "cyls", "heads", "secs", "trans",
5505 "media", "snapshot", "file",
5506 "cache", "format", NULL };
e4bcb14c
TS
5507
5508 if (check_params(buf, sizeof(buf), params, str) < 0) {
ff993638 5509 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
e4bcb14c
TS
5510 buf, str);
5511 return -1;
5512 }
5513
5514 file[0] = 0;
5515 cyls = heads = secs = 0;
5516 bus_id = 0;
5517 unit_id = -1;
5518 translation = BIOS_ATA_TRANSLATION_AUTO;
5519 index = -1;
33f00271 5520 cache = 1;
e4bcb14c 5521
c9b1ae2c 5522 if (machine->use_scsi) {
f60d39bc 5523 type = IF_SCSI;
e4bcb14c 5524 max_devs = MAX_SCSI_DEVS;
363a37d5 5525 pstrcpy(devname, sizeof(devname), "scsi");
e4bcb14c 5526 } else {
f60d39bc 5527 type = IF_IDE;
e4bcb14c 5528 max_devs = MAX_IDE_DEVS;
363a37d5 5529 pstrcpy(devname, sizeof(devname), "ide");
e4bcb14c
TS
5530 }
5531 media = MEDIA_DISK;
5532
5533 /* extract parameters */
5534
5535 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5536 bus_id = strtol(buf, NULL, 0);
5537 if (bus_id < 0) {
5538 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5539 return -1;
5540 }
5541 }
5542
5543 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5544 unit_id = strtol(buf, NULL, 0);
5545 if (unit_id < 0) {
5546 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5547 return -1;
5548 }
5549 }
5550
5551 if (get_param_value(buf, sizeof(buf), "if", str)) {
ae45d369 5552 pstrcpy(devname, sizeof(devname), buf);
e4bcb14c 5553 if (!strcmp(buf, "ide")) {
f60d39bc 5554 type = IF_IDE;
e4bcb14c
TS
5555 max_devs = MAX_IDE_DEVS;
5556 } else if (!strcmp(buf, "scsi")) {
f60d39bc 5557 type = IF_SCSI;
e4bcb14c
TS
5558 max_devs = MAX_SCSI_DEVS;
5559 } else if (!strcmp(buf, "floppy")) {
f60d39bc 5560 type = IF_FLOPPY;
e4bcb14c
TS
5561 max_devs = 0;
5562 } else if (!strcmp(buf, "pflash")) {
f60d39bc 5563 type = IF_PFLASH;
e4bcb14c
TS
5564 max_devs = 0;
5565 } else if (!strcmp(buf, "mtd")) {
f60d39bc 5566 type = IF_MTD;
e4bcb14c
TS
5567 max_devs = 0;
5568 } else if (!strcmp(buf, "sd")) {
f60d39bc 5569 type = IF_SD;
e4bcb14c
TS
5570 max_devs = 0;
5571 } else {
5572 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5573 return -1;
5574 }
5575 }
5576
5577 if (get_param_value(buf, sizeof(buf), "index", str)) {
5578 index = strtol(buf, NULL, 0);
5579 if (index < 0) {
5580 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5581 return -1;
5582 }
5583 }
5584
5585 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5586 cyls = strtol(buf, NULL, 0);
5587 }
5588
5589 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5590 heads = strtol(buf, NULL, 0);
5591 }
5592
5593 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5594 secs = strtol(buf, NULL, 0);
5595 }
5596
5597 if (cyls || heads || secs) {
5598 if (cyls < 1 || cyls > 16383) {
5599 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5600 return -1;
5601 }
5602 if (heads < 1 || heads > 16) {
5603 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5604 return -1;
5605 }
5606 if (secs < 1 || secs > 63) {
5607 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5608 return -1;
5609 }
5610 }
5611
5612 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5613 if (!cyls) {
5614 fprintf(stderr,
5615 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5616 str);
5617 return -1;
5618 }
5619 if (!strcmp(buf, "none"))
5620 translation = BIOS_ATA_TRANSLATION_NONE;
5621 else if (!strcmp(buf, "lba"))
5622 translation = BIOS_ATA_TRANSLATION_LBA;
5623 else if (!strcmp(buf, "auto"))
5624 translation = BIOS_ATA_TRANSLATION_AUTO;
5625 else {
5626 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5627 return -1;
5628 }
5629 }
5630
5631 if (get_param_value(buf, sizeof(buf), "media", str)) {
5632 if (!strcmp(buf, "disk")) {
5633 media = MEDIA_DISK;
5634 } else if (!strcmp(buf, "cdrom")) {
5635 if (cyls || secs || heads) {
5636 fprintf(stderr,
5637 "qemu: '%s' invalid physical CHS format\n", str);
5638 return -1;
5639 }
5640 media = MEDIA_CDROM;
5641 } else {
5642 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5643 return -1;
5644 }
5645 }
5646
5647 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5648 if (!strcmp(buf, "on"))
5649 snapshot = 1;
5650 else if (!strcmp(buf, "off"))
5651 snapshot = 0;
5652 else {
5653 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5654 return -1;
5655 }
5656 }
5657
33f00271
AZ
5658 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5659 if (!strcmp(buf, "off"))
5660 cache = 0;
5661 else if (!strcmp(buf, "on"))
5662 cache = 1;
5663 else {
5664 fprintf(stderr, "qemu: invalid cache option\n");
5665 return -1;
5666 }
5667 }
5668
1e72d3b7 5669 if (get_param_value(buf, sizeof(buf), "format", str)) {
a1620fac
AJ
5670 if (strcmp(buf, "?") == 0) {
5671 fprintf(stderr, "qemu: Supported formats:");
5672 bdrv_iterate_format(bdrv_format_print, NULL);
5673 fprintf(stderr, "\n");
5674 return -1;
5675 }
1e72d3b7
AJ
5676 drv = bdrv_find_format(buf);
5677 if (!drv) {
5678 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5679 return -1;
5680 }
5681 }
5682
609497ab
AZ
5683 if (arg->file == NULL)
5684 get_param_value(file, sizeof(file), "file", str);
5685 else
5686 pstrcpy(file, sizeof(file), arg->file);
e4bcb14c
TS
5687
5688 /* compute bus and unit according index */
5689
5690 if (index != -1) {
5691 if (bus_id != 0 || unit_id != -1) {
5692 fprintf(stderr,
5693 "qemu: '%s' index cannot be used with bus and unit\n", str);
5694 return -1;
5695 }
5696 if (max_devs == 0)
5697 {
5698 unit_id = index;
5699 bus_id = 0;
5700 } else {
5701 unit_id = index % max_devs;
5702 bus_id = index / max_devs;
5703 }
5704 }
5705
5706 /* if user doesn't specify a unit_id,
5707 * try to find the first free
5708 */
5709
5710 if (unit_id == -1) {
5711 unit_id = 0;
f60d39bc 5712 while (drive_get_index(type, bus_id, unit_id) != -1) {
e4bcb14c
TS
5713 unit_id++;
5714 if (max_devs && unit_id >= max_devs) {
5715 unit_id -= max_devs;
5716 bus_id++;
5717 }
5718 }
5719 }
5720
5721 /* check unit id */
5722
5723 if (max_devs && unit_id >= max_devs) {
5724 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5725 str, unit_id, max_devs - 1);
5726 return -1;
5727 }
5728
5729 /*
5730 * ignore multiple definitions
5731 */
5732
f60d39bc 5733 if (drive_get_index(type, bus_id, unit_id) != -1)
e4bcb14c
TS
5734 return 0;
5735
5736 /* init */
5737
f60d39bc 5738 if (type == IF_IDE || type == IF_SCSI)
c8522bdf 5739 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
e6198a70
AZ
5740 if (max_devs)
5741 snprintf(buf, sizeof(buf), "%s%i%s%i",
5742 devname, bus_id, mediastr, unit_id);
5743 else
5744 snprintf(buf, sizeof(buf), "%s%s%i",
5745 devname, mediastr, unit_id);
e4bcb14c
TS
5746 bdrv = bdrv_new(buf);
5747 drives_table[nb_drives].bdrv = bdrv;
f60d39bc 5748 drives_table[nb_drives].type = type;
e4bcb14c
TS
5749 drives_table[nb_drives].bus = bus_id;
5750 drives_table[nb_drives].unit = unit_id;
5751 nb_drives++;
5752
f60d39bc 5753 switch(type) {
e4bcb14c
TS
5754 case IF_IDE:
5755 case IF_SCSI:
5756 switch(media) {
5757 case MEDIA_DISK:
5758 if (cyls != 0) {
5759 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5760 bdrv_set_translation_hint(bdrv, translation);
5761 }
5762 break;
5763 case MEDIA_CDROM:
5764 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5765 break;
5766 }
5767 break;
5768 case IF_SD:
5769 /* FIXME: This isn't really a floppy, but it's a reasonable
5770 approximation. */
5771 case IF_FLOPPY:
5772 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5773 break;
5774 case IF_PFLASH:
5775 case IF_MTD:
5776 break;
5777 }
5778 if (!file[0])
5779 return 0;
33f00271
AZ
5780 bdrv_flags = 0;
5781 if (snapshot)
5782 bdrv_flags |= BDRV_O_SNAPSHOT;
5783 if (!cache)
5784 bdrv_flags |= BDRV_O_DIRECT;
83ab7950 5785 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
e4bcb14c
TS
5786 fprintf(stderr, "qemu: could not open disk image %s\n",
5787 file);
5788 return -1;
5789 }
5790 return 0;
5791}
5792
a594cfbf
FB
5793/***********************************************************/
5794/* USB devices */
5795
0d92ed30
PB
5796static USBPort *used_usb_ports;
5797static USBPort *free_usb_ports;
5798
5799/* ??? Maybe change this to register a hub to keep track of the topology. */
5800void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5801 usb_attachfn attach)
5802{
5803 port->opaque = opaque;
5804 port->index = index;
5805 port->attach = attach;
5806 port->next = free_usb_ports;
5807 free_usb_ports = port;
5808}
5809
4b096fc9
AL
5810int usb_device_add_dev(USBDevice *dev)
5811{
5812 USBPort *port;
5813
5814 /* Find a USB port to add the device to. */
5815 port = free_usb_ports;
5816 if (!port->next) {
5817 USBDevice *hub;
5818
5819 /* Create a new hub and chain it on. */
5820 free_usb_ports = NULL;
5821 port->next = used_usb_ports;
5822 used_usb_ports = port;
5823
5824 hub = usb_hub_init(VM_USB_HUB_SIZE);
5825 usb_attach(port, hub);
5826 port = free_usb_ports;
5827 }
5828
5829 free_usb_ports = port->next;
5830 port->next = used_usb_ports;
5831 used_usb_ports = port;
5832 usb_attach(port, dev);
5833 return 0;
5834}
5835
a594cfbf
FB
5836static int usb_device_add(const char *devname)
5837{
5838 const char *p;
5839 USBDevice *dev;
a594cfbf 5840
0d92ed30 5841 if (!free_usb_ports)
a594cfbf
FB
5842 return -1;
5843
5844 if (strstart(devname, "host:", &p)) {
5845 dev = usb_host_device_open(p);
a594cfbf
FB
5846 } else if (!strcmp(devname, "mouse")) {
5847 dev = usb_mouse_init();
09b26c5e 5848 } else if (!strcmp(devname, "tablet")) {
47b2d338
AZ
5849 dev = usb_tablet_init();
5850 } else if (!strcmp(devname, "keyboard")) {
5851 dev = usb_keyboard_init();
2e5d83bb
PB
5852 } else if (strstart(devname, "disk:", &p)) {
5853 dev = usb_msd_init(p);
f6d2a316
AZ
5854 } else if (!strcmp(devname, "wacom-tablet")) {
5855 dev = usb_wacom_init();
a7954218
AZ
5856 } else if (strstart(devname, "serial:", &p)) {
5857 dev = usb_serial_init(p);
2e4d9fb1
AJ
5858#ifdef CONFIG_BRLAPI
5859 } else if (!strcmp(devname, "braille")) {
5860 dev = usb_baum_init();
5861#endif
6c9f886c 5862 } else if (strstart(devname, "net:", &p)) {
9ad97e65 5863 int nic = nb_nics;
6c9f886c 5864
9ad97e65 5865 if (net_client_init("nic", p) < 0)
6c9f886c 5866 return -1;
9ad97e65
AZ
5867 nd_table[nic].model = "usb";
5868 dev = usb_net_init(&nd_table[nic]);
a594cfbf
FB
5869 } else {
5870 return -1;
5871 }
0d92ed30
PB
5872 if (!dev)
5873 return -1;
5874
4b096fc9 5875 return usb_device_add_dev(dev);
a594cfbf
FB
5876}
5877
1f3870ab 5878int usb_device_del_addr(int bus_num, int addr)
a594cfbf 5879{
0d92ed30
PB
5880 USBPort *port;
5881 USBPort **lastp;
059809e4 5882 USBDevice *dev;
a594cfbf 5883
0d92ed30 5884 if (!used_usb_ports)
a594cfbf
FB
5885 return -1;
5886
a594cfbf
FB
5887 if (bus_num != 0)
5888 return -1;
0d92ed30
PB
5889
5890 lastp = &used_usb_ports;
5891 port = used_usb_ports;
5892 while (port && port->dev->addr != addr) {
5893 lastp = &port->next;
5894 port = port->next;
a594cfbf 5895 }
0d92ed30
PB
5896
5897 if (!port)
a594cfbf 5898 return -1;
0d92ed30 5899
059809e4 5900 dev = port->dev;
0d92ed30
PB
5901 *lastp = port->next;
5902 usb_attach(port, NULL);
059809e4 5903 dev->handle_destroy(dev);
0d92ed30
PB
5904 port->next = free_usb_ports;
5905 free_usb_ports = port;
a594cfbf
FB
5906 return 0;
5907}
5908
1f3870ab
AL
5909static int usb_device_del(const char *devname)
5910{
5911 int bus_num, addr;
5912 const char *p;
5913
5d0c5750
AL
5914 if (strstart(devname, "host:", &p))
5915 return usb_host_device_close(p);
5916
1f3870ab
AL
5917 if (!used_usb_ports)
5918 return -1;
5919
5920 p = strchr(devname, '.');
5921 if (!p)
5922 return -1;
5923 bus_num = strtoul(devname, NULL, 0);
5924 addr = strtoul(p + 1, NULL, 0);
5925
5926 return usb_device_del_addr(bus_num, addr);
5927}
5928
a594cfbf
FB
5929void do_usb_add(const char *devname)
5930{
4b096fc9 5931 usb_device_add(devname);
a594cfbf
FB
5932}
5933
5934void do_usb_del(const char *devname)
5935{
4b096fc9 5936 usb_device_del(devname);
a594cfbf
FB
5937}
5938
5939void usb_info(void)
5940{
5941 USBDevice *dev;
0d92ed30 5942 USBPort *port;
a594cfbf
FB
5943 const char *speed_str;
5944
0d92ed30 5945 if (!usb_enabled) {
a594cfbf
FB
5946 term_printf("USB support not enabled\n");
5947 return;
5948 }
5949
0d92ed30
PB
5950 for (port = used_usb_ports; port; port = port->next) {
5951 dev = port->dev;
5952 if (!dev)
5953 continue;
5954 switch(dev->speed) {
5fafdf24
TS
5955 case USB_SPEED_LOW:
5956 speed_str = "1.5";
0d92ed30 5957 break;
5fafdf24
TS
5958 case USB_SPEED_FULL:
5959 speed_str = "12";
0d92ed30 5960 break;
5fafdf24
TS
5961 case USB_SPEED_HIGH:
5962 speed_str = "480";
0d92ed30
PB
5963 break;
5964 default:
5fafdf24 5965 speed_str = "?";
0d92ed30 5966 break;
a594cfbf 5967 }
5fafdf24 5968 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
1f6e24e7 5969 0, dev->addr, speed_str, dev->devname);
a594cfbf
FB
5970 }
5971}
5972
201a51fc
AZ
5973/***********************************************************/
5974/* PCMCIA/Cardbus */
5975
5976static struct pcmcia_socket_entry_s {
5977 struct pcmcia_socket_s *socket;
5978 struct pcmcia_socket_entry_s *next;
5979} *pcmcia_sockets = 0;
5980
5981void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5982{
5983 struct pcmcia_socket_entry_s *entry;
5984
5985 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5986 entry->socket = socket;
5987 entry->next = pcmcia_sockets;
5988 pcmcia_sockets = entry;
5989}
5990
5991void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5992{
5993 struct pcmcia_socket_entry_s *entry, **ptr;
5994
5995 ptr = &pcmcia_sockets;
5996 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5997 if (entry->socket == socket) {
5998 *ptr = entry->next;
5999 qemu_free(entry);
6000 }
6001}
6002
6003void pcmcia_info(void)
6004{
6005 struct pcmcia_socket_entry_s *iter;
6006 if (!pcmcia_sockets)
6007 term_printf("No PCMCIA sockets\n");
6008
6009 for (iter = pcmcia_sockets; iter; iter = iter->next)
6010 term_printf("%s: %s\n", iter->socket->slot_string,
6011 iter->socket->attached ? iter->socket->card_string :
6012 "Empty");
6013}
6014
2ff89790
TS
6015/***********************************************************/
6016/* dumb display */
6017
6018static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6019{
6020}
6021
6022static void dumb_resize(DisplayState *ds, int w, int h)
6023{
6024}
6025
6026static void dumb_refresh(DisplayState *ds)
6027{
6028#if defined(CONFIG_SDL)
6029 vga_hw_update();
6030#endif
6031}
6032
6033static void dumb_display_init(DisplayState *ds)
6034{
6035 ds->data = NULL;
6036 ds->linesize = 0;
6037 ds->depth = 0;
6038 ds->dpy_update = dumb_update;
6039 ds->dpy_resize = dumb_resize;
6040 ds->dpy_refresh = dumb_refresh;
bcfad70f
AL
6041 ds->gui_timer_interval = 500;
6042 ds->idle = 1;
2ff89790
TS
6043}
6044
8a7ddc38
FB
6045/***********************************************************/
6046/* I/O handling */
0824d6fc 6047
c4b1fcc0
FB
6048#define MAX_IO_HANDLERS 64
6049
6050typedef struct IOHandlerRecord {
6051 int fd;
7c9d8e07
FB
6052 IOCanRWHandler *fd_read_poll;
6053 IOHandler *fd_read;
6054 IOHandler *fd_write;
cafffd40 6055 int deleted;
c4b1fcc0
FB
6056 void *opaque;
6057 /* temporary data */
6058 struct pollfd *ufd;
8a7ddc38 6059 struct IOHandlerRecord *next;
c4b1fcc0
FB
6060} IOHandlerRecord;
6061
8a7ddc38 6062static IOHandlerRecord *first_io_handler;
c4b1fcc0 6063
7c9d8e07
FB
6064/* XXX: fd_read_poll should be suppressed, but an API change is
6065 necessary in the character devices to suppress fd_can_read(). */
5fafdf24
TS
6066int qemu_set_fd_handler2(int fd,
6067 IOCanRWHandler *fd_read_poll,
6068 IOHandler *fd_read,
6069 IOHandler *fd_write,
7c9d8e07 6070 void *opaque)
c4b1fcc0 6071{
7c9d8e07 6072 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 6073
7c9d8e07
FB
6074 if (!fd_read && !fd_write) {
6075 pioh = &first_io_handler;
6076 for(;;) {
6077 ioh = *pioh;
6078 if (ioh == NULL)
6079 break;
6080 if (ioh->fd == fd) {
cafffd40 6081 ioh->deleted = 1;
7c9d8e07
FB
6082 break;
6083 }
6084 pioh = &ioh->next;
6085 }
6086 } else {
6087 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6088 if (ioh->fd == fd)
6089 goto found;
6090 }
6091 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6092 if (!ioh)
6093 return -1;
6094 ioh->next = first_io_handler;
6095 first_io_handler = ioh;
6096 found:
6097 ioh->fd = fd;
6098 ioh->fd_read_poll = fd_read_poll;
6099 ioh->fd_read = fd_read;
6100 ioh->fd_write = fd_write;
6101 ioh->opaque = opaque;
cafffd40 6102 ioh->deleted = 0;
7c9d8e07 6103 }
c4b1fcc0
FB
6104 return 0;
6105}
6106
5fafdf24
TS
6107int qemu_set_fd_handler(int fd,
6108 IOHandler *fd_read,
6109 IOHandler *fd_write,
7c9d8e07 6110 void *opaque)
8a7ddc38 6111{
7c9d8e07 6112 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
6113}
6114
f331110f
FB
6115/***********************************************************/
6116/* Polling handling */
6117
6118typedef struct PollingEntry {
6119 PollingFunc *func;
6120 void *opaque;
6121 struct PollingEntry *next;
6122} PollingEntry;
6123
6124static PollingEntry *first_polling_entry;
6125
6126int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6127{
6128 PollingEntry **ppe, *pe;
6129 pe = qemu_mallocz(sizeof(PollingEntry));
6130 if (!pe)
6131 return -1;
6132 pe->func = func;
6133 pe->opaque = opaque;
6134 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6135 *ppe = pe;
6136 return 0;
6137}
6138
6139void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6140{
6141 PollingEntry **ppe, *pe;
6142 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6143 pe = *ppe;
6144 if (pe->func == func && pe->opaque == opaque) {
6145 *ppe = pe->next;
6146 qemu_free(pe);
6147 break;
6148 }
6149 }
6150}
6151
a18e524a
FB
6152#ifdef _WIN32
6153/***********************************************************/
6154/* Wait objects support */
6155typedef struct WaitObjects {
6156 int num;
6157 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6158 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6159 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6160} WaitObjects;
6161
6162static WaitObjects wait_objects = {0};
3b46e624 6163
a18e524a
FB
6164int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6165{
6166 WaitObjects *w = &wait_objects;
6167
6168 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6169 return -1;
6170 w->events[w->num] = handle;
6171 w->func[w->num] = func;
6172 w->opaque[w->num] = opaque;
6173 w->num++;
6174 return 0;
6175}
6176
6177void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6178{
6179 int i, found;
6180 WaitObjects *w = &wait_objects;
6181
6182 found = 0;
6183 for (i = 0; i < w->num; i++) {
6184 if (w->events[i] == handle)
6185 found = 1;
6186 if (found) {
6187 w->events[i] = w->events[i + 1];
6188 w->func[i] = w->func[i + 1];
6189 w->opaque[i] = w->opaque[i + 1];
3b46e624 6190 }
a18e524a
FB
6191 }
6192 if (found)
6193 w->num--;
6194}
6195#endif
6196
8a7ddc38
FB
6197/***********************************************************/
6198/* savevm/loadvm support */
6199
faea38e7
FB
6200#define IO_BUF_SIZE 32768
6201
6202struct QEMUFile {
5dafc53f
AL
6203 QEMUFilePutBufferFunc *put_buffer;
6204 QEMUFileGetBufferFunc *get_buffer;
6205 QEMUFileCloseFunc *close;
6206 QEMUFileRateLimit *rate_limit;
6207 void *opaque;
6208
faea38e7
FB
6209 int64_t buf_offset; /* start of buffer when writing, end of buffer
6210 when reading */
6211 int buf_index;
6212 int buf_size; /* 0 when writing */
6213 uint8_t buf[IO_BUF_SIZE];
6214};
6215
5dafc53f
AL
6216typedef struct QEMUFileFD
6217{
6218 int fd;
6219 QEMUFile *file;
6220} QEMUFileFD;
6221
6222static void fd_put_notify(void *opaque)
6223{
6224 QEMUFileFD *s = opaque;
6225
6226 /* Remove writable callback and do a put notify */
6227 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
6228 qemu_file_put_notify(s->file);
6229}
6230
342b51d7
BS
6231static void fd_put_buffer(void *opaque, const uint8_t *buf,
6232 int64_t pos, int size)
5dafc53f
AL
6233{
6234 QEMUFileFD *s = opaque;
6235 ssize_t len;
6236
6237 do {
6238 len = write(s->fd, buf, size);
6239 } while (len == -1 && errno == EINTR);
6240
6241 if (len == -1)
6242 len = -errno;
6243
6244 /* When the fd becomes writable again, register a callback to do
6245 * a put notify */
6246 if (len == -EAGAIN)
6247 qemu_set_fd_handler2(s->fd, NULL, NULL, fd_put_notify, s);
5dafc53f
AL
6248}
6249
6250static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6251{
6252 QEMUFileFD *s = opaque;
6253 ssize_t len;
6254
6255 do {
6256 len = read(s->fd, buf, size);
6257 } while (len == -1 && errno == EINTR);
6258
6259 if (len == -1)
6260 len = -errno;
6261
6262 return len;
6263}
6264
6265static int fd_close(void *opaque)
6266{
6267 QEMUFileFD *s = opaque;
6268 qemu_free(s);
6269 return 0;
6270}
6271
6272QEMUFile *qemu_fopen_fd(int fd)
6273{
6274 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6275
6276 if (s == NULL)
6277 return NULL;
6278
6279 s->fd = fd;
6280 s->file = qemu_fopen_ops(s, fd_put_buffer, fd_get_buffer, fd_close, NULL);
6281 return s->file;
6282}
6283
6284typedef struct QEMUFileStdio
6285{
6286 FILE *outfile;
6287} QEMUFileStdio;
6288
6289static void file_put_buffer(void *opaque, const uint8_t *buf,
6290 int64_t pos, int size)
6291{
6292 QEMUFileStdio *s = opaque;
6293 fseek(s->outfile, pos, SEEK_SET);
6294 fwrite(buf, 1, size, s->outfile);
6295}
6296
6297static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6298{
6299 QEMUFileStdio *s = opaque;
6300 fseek(s->outfile, pos, SEEK_SET);
6301 return fread(buf, 1, size, s->outfile);
6302}
6303
6304static int file_close(void *opaque)
6305{
6306 QEMUFileStdio *s = opaque;
6307 fclose(s->outfile);
6308 qemu_free(s);
6309 return 0;
6310}
6311
faea38e7
FB
6312QEMUFile *qemu_fopen(const char *filename, const char *mode)
6313{
5dafc53f 6314 QEMUFileStdio *s;
faea38e7 6315
5dafc53f
AL
6316 s = qemu_mallocz(sizeof(QEMUFileStdio));
6317 if (!s)
faea38e7 6318 return NULL;
5dafc53f
AL
6319
6320 s->outfile = fopen(filename, mode);
6321 if (!s->outfile)
faea38e7 6322 goto fail;
5dafc53f
AL
6323
6324 if (!strcmp(mode, "wb"))
6325 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
6326 else if (!strcmp(mode, "rb"))
6327 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
6328
6329fail:
6330 if (s->outfile)
6331 fclose(s->outfile);
6332 qemu_free(s);
faea38e7
FB
6333 return NULL;
6334}
6335
5dafc53f
AL
6336typedef struct QEMUFileBdrv
6337{
6338 BlockDriverState *bs;
6339 int64_t base_offset;
6340} QEMUFileBdrv;
6341
6342static void bdrv_put_buffer(void *opaque, const uint8_t *buf,
6343 int64_t pos, int size)
6344{
6345 QEMUFileBdrv *s = opaque;
6346 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6347}
6348
6349static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6350{
6351 QEMUFileBdrv *s = opaque;
6352 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6353}
6354
6355static int bdrv_fclose(void *opaque)
6356{
6357 QEMUFileBdrv *s = opaque;
6358 qemu_free(s);
6359 return 0;
6360}
6361
674bb261 6362static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5dafc53f
AL
6363{
6364 QEMUFileBdrv *s;
6365
6366 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6367 if (!s)
6368 return NULL;
6369
6370 s->bs = bs;
6371 s->base_offset = offset;
6372
6373 if (is_writable)
6374 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
6375
6376 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
6377}
6378
6379QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6380 QEMUFileGetBufferFunc *get_buffer,
6381 QEMUFileCloseFunc *close,
6382 QEMUFileRateLimit *rate_limit)
faea38e7
FB
6383{
6384 QEMUFile *f;
6385
6386 f = qemu_mallocz(sizeof(QEMUFile));
6387 if (!f)
6388 return NULL;
5dafc53f
AL
6389
6390 f->opaque = opaque;
6391 f->put_buffer = put_buffer;
6392 f->get_buffer = get_buffer;
6393 f->close = close;
6394 f->rate_limit = rate_limit;
6395
faea38e7
FB
6396 return f;
6397}
6398
6399void qemu_fflush(QEMUFile *f)
6400{
5dafc53f 6401 if (!f->put_buffer)
faea38e7 6402 return;
5dafc53f 6403
faea38e7 6404 if (f->buf_index > 0) {
5dafc53f 6405 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
faea38e7
FB
6406 f->buf_offset += f->buf_index;
6407 f->buf_index = 0;
6408 }
6409}
6410
6411static void qemu_fill_buffer(QEMUFile *f)
6412{
6413 int len;
6414
5dafc53f 6415 if (!f->get_buffer)
faea38e7 6416 return;
5dafc53f
AL
6417
6418 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6419 if (len < 0)
6420 len = 0;
6421
faea38e7
FB
6422 f->buf_index = 0;
6423 f->buf_size = len;
6424 f->buf_offset += len;
6425}
6426
5dafc53f 6427int qemu_fclose(QEMUFile *f)
faea38e7 6428{
5dafc53f
AL
6429 int ret = 0;
6430 qemu_fflush(f);
6431 if (f->close)
6432 ret = f->close(f->opaque);
faea38e7 6433 qemu_free(f);
5dafc53f
AL
6434 return ret;
6435}
6436
6437void qemu_file_put_notify(QEMUFile *f)
6438{
6439 f->put_buffer(f->opaque, NULL, 0, 0);
faea38e7
FB
6440}
6441
2ca83a8d 6442void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
b4608c04 6443{
2ca83a8d 6444 int l;
faea38e7
FB
6445 while (size > 0) {
6446 l = IO_BUF_SIZE - f->buf_index;
6447 if (l > size)
6448 l = size;
6449 memcpy(f->buf + f->buf_index, buf, l);
6450 f->buf_index += l;
6451 buf += l;
6452 size -= l;
6453 if (f->buf_index >= IO_BUF_SIZE)
6454 qemu_fflush(f);
6455 }
b4608c04
FB
6456}
6457
2ca83a8d 6458void qemu_put_byte(QEMUFile *f, int v)
b4608c04 6459{
faea38e7
FB
6460 f->buf[f->buf_index++] = v;
6461 if (f->buf_index >= IO_BUF_SIZE)
6462 qemu_fflush(f);
6463}
6464
2ca83a8d 6465int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
faea38e7 6466{
2ca83a8d 6467 int size, l;
faea38e7
FB
6468
6469 size = size1;
6470 while (size > 0) {
6471 l = f->buf_size - f->buf_index;
6472 if (l == 0) {
6473 qemu_fill_buffer(f);
6474 l = f->buf_size - f->buf_index;
6475 if (l == 0)
6476 break;
6477 }
6478 if (l > size)
6479 l = size;
6480 memcpy(buf, f->buf + f->buf_index, l);
6481 f->buf_index += l;
6482 buf += l;
6483 size -= l;
6484 }
6485 return size1 - size;
6486}
6487
2ca83a8d 6488int qemu_get_byte(QEMUFile *f)
faea38e7
FB
6489{
6490 if (f->buf_index >= f->buf_size) {
6491 qemu_fill_buffer(f);
6492 if (f->buf_index >= f->buf_size)
6493 return 0;
6494 }
6495 return f->buf[f->buf_index++];
6496}
6497
6498int64_t qemu_ftell(QEMUFile *f)
6499{
6500 return f->buf_offset - f->buf_size + f->buf_index;
6501}
6502
6503int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6504{
6505 if (whence == SEEK_SET) {
6506 /* nothing to do */
6507 } else if (whence == SEEK_CUR) {
6508 pos += qemu_ftell(f);
6509 } else {
6510 /* SEEK_END not supported */
6511 return -1;
6512 }
5dafc53f 6513 if (f->put_buffer) {
faea38e7
FB
6514 qemu_fflush(f);
6515 f->buf_offset = pos;
6516 } else {
6517 f->buf_offset = pos;
6518 f->buf_index = 0;
6519 f->buf_size = 0;
6520 }
6521 return pos;
8a7ddc38
FB
6522}
6523
5dafc53f
AL
6524int qemu_file_rate_limit(QEMUFile *f)
6525{
6526 if (f->rate_limit)
6527 return f->rate_limit(f->opaque);
6528
6529 return 0;
6530}
6531
2ca83a8d 6532void qemu_put_be16(QEMUFile *f, unsigned int v)
8a7ddc38
FB
6533{
6534 qemu_put_byte(f, v >> 8);
6535 qemu_put_byte(f, v);
6536}
6537
2ca83a8d 6538void qemu_put_be32(QEMUFile *f, unsigned int v)
8a7ddc38
FB
6539{
6540 qemu_put_byte(f, v >> 24);
6541 qemu_put_byte(f, v >> 16);
6542 qemu_put_byte(f, v >> 8);
6543 qemu_put_byte(f, v);
6544}
6545
6546void qemu_put_be64(QEMUFile *f, uint64_t v)
6547{
6548 qemu_put_be32(f, v >> 32);
6549 qemu_put_be32(f, v);
6550}
6551
2ca83a8d 6552unsigned int qemu_get_be16(QEMUFile *f)
8a7ddc38 6553{
2ca83a8d 6554 unsigned int v;
8a7ddc38
FB
6555 v = qemu_get_byte(f) << 8;
6556 v |= qemu_get_byte(f);
6557 return v;
6558}
6559
2ca83a8d 6560unsigned int qemu_get_be32(QEMUFile *f)
8a7ddc38 6561{
2ca83a8d 6562 unsigned int v;
8a7ddc38
FB
6563 v = qemu_get_byte(f) << 24;
6564 v |= qemu_get_byte(f) << 16;
6565 v |= qemu_get_byte(f) << 8;
6566 v |= qemu_get_byte(f);
6567 return v;
6568}
6569
6570uint64_t qemu_get_be64(QEMUFile *f)
6571{
6572 uint64_t v;
6573 v = (uint64_t)qemu_get_be32(f) << 32;
6574 v |= qemu_get_be32(f);
6575 return v;
6576}
6577
8a7ddc38
FB
6578typedef struct SaveStateEntry {
6579 char idstr[256];
6580 int instance_id;
6581 int version_id;
9366f418
AL
6582 int section_id;
6583 SaveLiveStateHandler *save_live_state;
8a7ddc38
FB
6584 SaveStateHandler *save_state;
6585 LoadStateHandler *load_state;
6586 void *opaque;
6587 struct SaveStateEntry *next;
6588} SaveStateEntry;
b4608c04 6589
8a7ddc38
FB
6590static SaveStateEntry *first_se;
6591
18be5187 6592/* TODO: Individual devices generally have very little idea about the rest
18fdb1c5
TS
6593 of the system, so instance_id should be removed/replaced.
6594 Meanwhile pass -1 as instance_id if you do not already have a clearly
6595 distinguishing id for all instances of your device class. */
9366f418
AL
6596int register_savevm_live(const char *idstr,
6597 int instance_id,
6598 int version_id,
6599 SaveLiveStateHandler *save_live_state,
6600 SaveStateHandler *save_state,
6601 LoadStateHandler *load_state,
6602 void *opaque)
8a7ddc38
FB
6603{
6604 SaveStateEntry *se, **pse;
9366f418 6605 static int global_section_id;
8a7ddc38
FB
6606
6607 se = qemu_malloc(sizeof(SaveStateEntry));
6608 if (!se)
6609 return -1;
6610 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
18be5187 6611 se->instance_id = (instance_id == -1) ? 0 : instance_id;
8a7ddc38 6612 se->version_id = version_id;
9366f418
AL
6613 se->section_id = global_section_id++;
6614 se->save_live_state = save_live_state;
8a7ddc38
FB
6615 se->save_state = save_state;
6616 se->load_state = load_state;
6617 se->opaque = opaque;
6618 se->next = NULL;
6619
6620 /* add at the end of list */
6621 pse = &first_se;
18be5187
PB
6622 while (*pse != NULL) {
6623 if (instance_id == -1
6624 && strcmp(se->idstr, (*pse)->idstr) == 0
6625 && se->instance_id <= (*pse)->instance_id)
6626 se->instance_id = (*pse)->instance_id + 1;
8a7ddc38 6627 pse = &(*pse)->next;
18be5187 6628 }
8a7ddc38
FB
6629 *pse = se;
6630 return 0;
6631}
6632
9366f418
AL
6633int register_savevm(const char *idstr,
6634 int instance_id,
6635 int version_id,
6636 SaveStateHandler *save_state,
6637 LoadStateHandler *load_state,
6638 void *opaque)
6639{
6640 return register_savevm_live(idstr, instance_id, version_id,
6641 NULL, save_state, load_state, opaque);
6642}
6643
6644#define QEMU_VM_FILE_MAGIC 0x5145564d
6645#define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
6646#define QEMU_VM_FILE_VERSION 0x00000003
6647
6648#define QEMU_VM_EOF 0x00
6649#define QEMU_VM_SECTION_START 0x01
6650#define QEMU_VM_SECTION_PART 0x02
6651#define QEMU_VM_SECTION_END 0x03
6652#define QEMU_VM_SECTION_FULL 0x04
8a7ddc38 6653
9366f418 6654int qemu_savevm_state_begin(QEMUFile *f)
8a7ddc38
FB
6655{
6656 SaveStateEntry *se;
313aa567 6657
8a7ddc38
FB
6658 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6659 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
9366f418
AL
6660
6661 for (se = first_se; se != NULL; se = se->next) {
6662 int len;
6663
6664 if (se->save_live_state == NULL)
6665 continue;
6666
6667 /* Section type */
6668 qemu_put_byte(f, QEMU_VM_SECTION_START);
6669 qemu_put_be32(f, se->section_id);
6670
6671 /* ID string */
6672 len = strlen(se->idstr);
6673 qemu_put_byte(f, len);
6674 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6675
6676 qemu_put_be32(f, se->instance_id);
6677 qemu_put_be32(f, se->version_id);
6678
6679 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
6680 }
6681
6682 return 0;
6683}
6684
6685int qemu_savevm_state_iterate(QEMUFile *f)
6686{
6687 SaveStateEntry *se;
475e4277 6688 int ret = 1;
9366f418
AL
6689
6690 for (se = first_se; se != NULL; se = se->next) {
6691 if (se->save_live_state == NULL)
6692 continue;
6693
6694 /* Section type */
6695 qemu_put_byte(f, QEMU_VM_SECTION_PART);
6696 qemu_put_be32(f, se->section_id);
6697
475e4277 6698 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
9366f418
AL
6699 }
6700
6701 if (ret)
6702 return 1;
6703
6704 return 0;
6705}
6706
6707int qemu_savevm_state_complete(QEMUFile *f)
6708{
6709 SaveStateEntry *se;
6710
6711 for (se = first_se; se != NULL; se = se->next) {
6712 if (se->save_live_state == NULL)
6713 continue;
6714
6715 /* Section type */
6716 qemu_put_byte(f, QEMU_VM_SECTION_END);
6717 qemu_put_be32(f, se->section_id);
6718
6719 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
6720 }
8a7ddc38
FB
6721
6722 for(se = first_se; se != NULL; se = se->next) {
9366f418
AL
6723 int len;
6724
d978c02c 6725 if (se->save_state == NULL)
d978c02c
AJ
6726 continue;
6727
9366f418
AL
6728 /* Section type */
6729 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
6730 qemu_put_be32(f, se->section_id);
6731
8a7ddc38
FB
6732 /* ID string */
6733 len = strlen(se->idstr);
6734 qemu_put_byte(f, len);
ffe8ab83 6735 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
8a7ddc38
FB
6736
6737 qemu_put_be32(f, se->instance_id);
6738 qemu_put_be32(f, se->version_id);
6739
8a7ddc38 6740 se->save_state(f, se->opaque);
8a7ddc38
FB
6741 }
6742
9366f418
AL
6743 qemu_put_byte(f, QEMU_VM_EOF);
6744
6745 return 0;
6746}
6747
6748int qemu_savevm_state(QEMUFile *f)
6749{
6750 int saved_vm_running;
6751 int ret;
6752
6753 saved_vm_running = vm_running;
6754 vm_stop(0);
6755
6756 ret = qemu_savevm_state_begin(f);
6757 if (ret < 0)
6758 goto out;
6759
6760 do {
6761 ret = qemu_savevm_state_iterate(f);
6762 if (ret < 0)
6763 goto out;
475e4277 6764 } while (ret == 0);
9366f418
AL
6765
6766 ret = qemu_savevm_state_complete(f);
6767
6768out:
6769 if (saved_vm_running)
6770 vm_start();
8a7ddc38
FB
6771 return ret;
6772}
6773
6774static SaveStateEntry *find_se(const char *idstr, int instance_id)
6775{
6776 SaveStateEntry *se;
6777
6778 for(se = first_se; se != NULL; se = se->next) {
5fafdf24 6779 if (!strcmp(se->idstr, idstr) &&
8a7ddc38
FB
6780 instance_id == se->instance_id)
6781 return se;
6782 }
6783 return NULL;
6784}
6785
9366f418
AL
6786typedef struct LoadStateEntry {
6787 SaveStateEntry *se;
6788 int section_id;
6789 int version_id;
6790 struct LoadStateEntry *next;
6791} LoadStateEntry;
6792
6793static int qemu_loadvm_state_v2(QEMUFile *f)
8a7ddc38
FB
6794{
6795 SaveStateEntry *se;
faea38e7
FB
6796 int len, ret, instance_id, record_len, version_id;
6797 int64_t total_len, end_pos, cur_pos;
8a7ddc38 6798 char idstr[256];
3b46e624 6799
faea38e7
FB
6800 total_len = qemu_get_be64(f);
6801 end_pos = total_len + qemu_ftell(f);
b4608c04 6802 for(;;) {
faea38e7 6803 if (qemu_ftell(f) >= end_pos)
cd4c3e88 6804 break;
faea38e7 6805 len = qemu_get_byte(f);
ffe8ab83 6806 qemu_get_buffer(f, (uint8_t *)idstr, len);
8a7ddc38
FB
6807 idstr[len] = '\0';
6808 instance_id = qemu_get_be32(f);
6809 version_id = qemu_get_be32(f);
6810 record_len = qemu_get_be32(f);
faea38e7 6811 cur_pos = qemu_ftell(f);
8a7ddc38
FB
6812 se = find_se(idstr, instance_id);
6813 if (!se) {
5fafdf24 6814 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
8a7ddc38
FB
6815 instance_id, idstr);
6816 } else {
6817 ret = se->load_state(f, se->opaque, version_id);
6818 if (ret < 0) {
5fafdf24 6819 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
8a7ddc38
FB
6820 instance_id, idstr);
6821 }
34865134 6822 }
8a7ddc38
FB
6823 /* always seek to exact end of record */
6824 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6825 }
9366f418
AL
6826 return 0;
6827}
6828
6829int qemu_loadvm_state(QEMUFile *f)
6830{
6831 LoadStateEntry *first_le = NULL;
6832 uint8_t section_type;
6833 unsigned int v;
6834 int ret;
6835
6836 v = qemu_get_be32(f);
6837 if (v != QEMU_VM_FILE_MAGIC)
6838 return -EINVAL;
6839
6840 v = qemu_get_be32(f);
6841 if (v == QEMU_VM_FILE_VERSION_COMPAT)
6842 return qemu_loadvm_state_v2(f);
6843 if (v != QEMU_VM_FILE_VERSION)
6844 return -ENOTSUP;
6845
6846 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
6847 uint32_t instance_id, version_id, section_id;
6848 LoadStateEntry *le;
6849 SaveStateEntry *se;
6850 char idstr[257];
6851 int len;
6852
6853 switch (section_type) {
6854 case QEMU_VM_SECTION_START:
6855 case QEMU_VM_SECTION_FULL:
6856 /* Read section start */
6857 section_id = qemu_get_be32(f);
6858 len = qemu_get_byte(f);
6859 qemu_get_buffer(f, (uint8_t *)idstr, len);
6860 idstr[len] = 0;
6861 instance_id = qemu_get_be32(f);
6862 version_id = qemu_get_be32(f);
6863
6864 /* Find savevm section */
6865 se = find_se(idstr, instance_id);
6866 if (se == NULL) {
6867 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
6868 ret = -EINVAL;
6869 goto out;
6870 }
6871
6872 /* Validate version */
6873 if (version_id > se->version_id) {
6874 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
6875 version_id, idstr, se->version_id);
6876 ret = -EINVAL;
6877 goto out;
6878 }
6879
6880 /* Add entry */
6881 le = qemu_mallocz(sizeof(*le));
6882 if (le == NULL) {
6883 ret = -ENOMEM;
6884 goto out;
6885 }
6886
6887 le->se = se;
6888 le->section_id = section_id;
6889 le->version_id = version_id;
6890 le->next = first_le;
6891 first_le = le;
6892
6893 le->se->load_state(f, le->se->opaque, le->version_id);
6894 break;
6895 case QEMU_VM_SECTION_PART:
6896 case QEMU_VM_SECTION_END:
6897 section_id = qemu_get_be32(f);
6898
6899 for (le = first_le; le && le->section_id != section_id; le = le->next);
6900 if (le == NULL) {
6901 fprintf(stderr, "Unknown savevm section %d\n", section_id);
6902 ret = -EINVAL;
6903 goto out;
6904 }
6905
6906 le->se->load_state(f, le->se->opaque, le->version_id);
6907 break;
6908 default:
6909 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
6910 ret = -EINVAL;
6911 goto out;
6912 }
6913 }
6914
8a7ddc38 6915 ret = 0;
9366f418
AL
6916
6917out:
6918 while (first_le) {
6919 LoadStateEntry *le = first_le;
6920 first_le = first_le->next;
6921 qemu_free(le);
6922 }
6923
faea38e7
FB
6924 return ret;
6925}
6926
6927/* device can contain snapshots */
6928static int bdrv_can_snapshot(BlockDriverState *bs)
6929{
6930 return (bs &&
6931 !bdrv_is_removable(bs) &&
6932 !bdrv_is_read_only(bs));
6933}
6934
6935/* device must be snapshots in order to have a reliable snapshot */
6936static int bdrv_has_snapshot(BlockDriverState *bs)
6937{
6938 return (bs &&
6939 !bdrv_is_removable(bs) &&
6940 !bdrv_is_read_only(bs));
6941}
6942
6943static BlockDriverState *get_bs_snapshots(void)
6944{
6945 BlockDriverState *bs;
6946 int i;
6947
6948 if (bs_snapshots)
6949 return bs_snapshots;
e4bcb14c
TS
6950 for(i = 0; i <= nb_drives; i++) {
6951 bs = drives_table[i].bdrv;
faea38e7
FB
6952 if (bdrv_can_snapshot(bs))
6953 goto ok;
6954 }
6955 return NULL;
6956 ok:
6957 bs_snapshots = bs;
6958 return bs;
6959}
6960
6961static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6962 const char *name)
6963{
6964 QEMUSnapshotInfo *sn_tab, *sn;
6965 int nb_sns, i, ret;
3b46e624 6966
faea38e7
FB
6967 ret = -ENOENT;
6968 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6969 if (nb_sns < 0)
6970 return ret;
6971 for(i = 0; i < nb_sns; i++) {
6972 sn = &sn_tab[i];
6973 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6974 *sn_info = *sn;
6975 ret = 0;
6976 break;
6977 }
6978 }
6979 qemu_free(sn_tab);
6980 return ret;
6981}
6982
6983void do_savevm(const char *name)
6984{
6985 BlockDriverState *bs, *bs1;
6986 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6987 int must_delete, ret, i;
6988 BlockDriverInfo bdi1, *bdi = &bdi1;
6989 QEMUFile *f;
6990 int saved_vm_running;
4c279bdf
FB
6991#ifdef _WIN32
6992 struct _timeb tb;
6993#else
faea38e7 6994 struct timeval tv;
4c279bdf 6995#endif
faea38e7
FB
6996
6997 bs = get_bs_snapshots();
6998 if (!bs) {
6999 term_printf("No block device can accept snapshots\n");
7000 return;
7001 }
7002
6192bc37
PB
7003 /* ??? Should this occur after vm_stop? */
7004 qemu_aio_flush();
7005
faea38e7
FB
7006 saved_vm_running = vm_running;
7007 vm_stop(0);
3b46e624 7008
faea38e7
FB
7009 must_delete = 0;
7010 if (name) {
7011 ret = bdrv_snapshot_find(bs, old_sn, name);
7012 if (ret >= 0) {
7013 must_delete = 1;
7014 }
7015 }
7016 memset(sn, 0, sizeof(*sn));
7017 if (must_delete) {
7018 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7019 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7020 } else {
7021 if (name)
7022 pstrcpy(sn->name, sizeof(sn->name), name);
7023 }
7024
7025 /* fill auxiliary fields */
4c279bdf
FB
7026#ifdef _WIN32
7027 _ftime(&tb);
7028 sn->date_sec = tb.time;
7029 sn->date_nsec = tb.millitm * 1000000;
7030#else
faea38e7
FB
7031 gettimeofday(&tv, NULL);
7032 sn->date_sec = tv.tv_sec;
7033 sn->date_nsec = tv.tv_usec * 1000;
4c279bdf 7034#endif
faea38e7 7035 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3b46e624 7036
faea38e7
FB
7037 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7038 term_printf("Device %s does not support VM state snapshots\n",
7039 bdrv_get_device_name(bs));
7040 goto the_end;
7041 }
3b46e624 7042
faea38e7
FB
7043 /* save the VM state */
7044 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7045 if (!f) {
7046 term_printf("Could not open VM state file\n");
7047 goto the_end;
7048 }
7049 ret = qemu_savevm_state(f);
7050 sn->vm_state_size = qemu_ftell(f);
7051 qemu_fclose(f);
7052 if (ret < 0) {
7053 term_printf("Error %d while writing VM\n", ret);
7054 goto the_end;
7055 }
3b46e624 7056
faea38e7
FB
7057 /* create the snapshots */
7058
e4bcb14c
TS
7059 for(i = 0; i < nb_drives; i++) {
7060 bs1 = drives_table[i].bdrv;
faea38e7
FB
7061 if (bdrv_has_snapshot(bs1)) {
7062 if (must_delete) {
7063 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7064 if (ret < 0) {
7065 term_printf("Error while deleting snapshot on '%s'\n",
7066 bdrv_get_device_name(bs1));
7067 }
7068 }
7069 ret = bdrv_snapshot_create(bs1, sn);
7070 if (ret < 0) {
7071 term_printf("Error while creating snapshot on '%s'\n",
7072 bdrv_get_device_name(bs1));
7073 }
7074 }
7075 }
7076
8a7ddc38
FB
7077 the_end:
7078 if (saved_vm_running)
7079 vm_start();
faea38e7
FB
7080}
7081
7082void do_loadvm(const char *name)
7083{
7084 BlockDriverState *bs, *bs1;
7085 BlockDriverInfo bdi1, *bdi = &bdi1;
7086 QEMUFile *f;
7087 int i, ret;
7088 int saved_vm_running;
7089
7090 bs = get_bs_snapshots();
7091 if (!bs) {
7092 term_printf("No block device supports snapshots\n");
7093 return;
7094 }
3b46e624 7095
6192bc37
PB
7096 /* Flush all IO requests so they don't interfere with the new state. */
7097 qemu_aio_flush();
7098
faea38e7
FB
7099 saved_vm_running = vm_running;
7100 vm_stop(0);
7101
e4bcb14c
TS
7102 for(i = 0; i <= nb_drives; i++) {
7103 bs1 = drives_table[i].bdrv;
faea38e7
FB
7104 if (bdrv_has_snapshot(bs1)) {
7105 ret = bdrv_snapshot_goto(bs1, name);
7106 if (ret < 0) {
7107 if (bs != bs1)
7108 term_printf("Warning: ");
7109 switch(ret) {
7110 case -ENOTSUP:
7111 term_printf("Snapshots not supported on device '%s'\n",
7112 bdrv_get_device_name(bs1));
7113 break;
7114 case -ENOENT:
7115 term_printf("Could not find snapshot '%s' on device '%s'\n",
7116 name, bdrv_get_device_name(bs1));
7117 break;
7118 default:
7119 term_printf("Error %d while activating snapshot on '%s'\n",
7120 ret, bdrv_get_device_name(bs1));
7121 break;
7122 }
7123 /* fatal on snapshot block device */
7124 if (bs == bs1)
7125 goto the_end;
7126 }
7127 }
7128 }
7129
7130 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7131 term_printf("Device %s does not support VM state snapshots\n",
7132 bdrv_get_device_name(bs));
7133 return;
7134 }
3b46e624 7135
faea38e7
FB
7136 /* restore the VM state */
7137 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7138 if (!f) {
7139 term_printf("Could not open VM state file\n");
7140 goto the_end;
7141 }
7142 ret = qemu_loadvm_state(f);
7143 qemu_fclose(f);
7144 if (ret < 0) {
7145 term_printf("Error %d while loading VM state\n", ret);
7146 }
7147 the_end:
7148 if (saved_vm_running)
7149 vm_start();
7150}
7151
7152void do_delvm(const char *name)
7153{
7154 BlockDriverState *bs, *bs1;
7155 int i, ret;
7156
7157 bs = get_bs_snapshots();
7158 if (!bs) {
7159 term_printf("No block device supports snapshots\n");
7160 return;
7161 }
3b46e624 7162
e4bcb14c
TS
7163 for(i = 0; i <= nb_drives; i++) {
7164 bs1 = drives_table[i].bdrv;
faea38e7
FB
7165 if (bdrv_has_snapshot(bs1)) {
7166 ret = bdrv_snapshot_delete(bs1, name);
7167 if (ret < 0) {
7168 if (ret == -ENOTSUP)
7169 term_printf("Snapshots not supported on device '%s'\n",
7170 bdrv_get_device_name(bs1));
7171 else
7172 term_printf("Error %d while deleting snapshot on '%s'\n",
7173 ret, bdrv_get_device_name(bs1));
7174 }
7175 }
7176 }
7177}
7178
7179void do_info_snapshots(void)
7180{
7181 BlockDriverState *bs, *bs1;
7182 QEMUSnapshotInfo *sn_tab, *sn;
7183 int nb_sns, i;
7184 char buf[256];
7185
7186 bs = get_bs_snapshots();
7187 if (!bs) {
7188 term_printf("No available block device supports snapshots\n");
7189 return;
7190 }
7191 term_printf("Snapshot devices:");
e4bcb14c
TS
7192 for(i = 0; i <= nb_drives; i++) {
7193 bs1 = drives_table[i].bdrv;
faea38e7
FB
7194 if (bdrv_has_snapshot(bs1)) {
7195 if (bs == bs1)
7196 term_printf(" %s", bdrv_get_device_name(bs1));
7197 }
7198 }
7199 term_printf("\n");
7200
7201 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7202 if (nb_sns < 0) {
7203 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7204 return;
7205 }
7206 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7207 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7208 for(i = 0; i < nb_sns; i++) {
7209 sn = &sn_tab[i];
7210 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7211 }
7212 qemu_free(sn_tab);
8a7ddc38
FB
7213}
7214
8a7ddc38
FB
7215/***********************************************************/
7216/* ram save/restore */
7217
8a7ddc38
FB
7218static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7219{
7220 int v;
7221
7222 v = qemu_get_byte(f);
7223 switch(v) {
7224 case 0:
7225 if (qemu_get_buffer(f, buf, len) != len)
7226 return -EIO;
7227 break;
7228 case 1:
7229 v = qemu_get_byte(f);
7230 memset(buf, v, len);
7231 break;
7232 default:
7233 return -EINVAL;
7234 }
7235 return 0;
7236}
7237
c88676f8
FB
7238static int ram_load_v1(QEMUFile *f, void *opaque)
7239{
00f82b8a
AJ
7240 int ret;
7241 ram_addr_t i;
c88676f8
FB
7242
7243 if (qemu_get_be32(f) != phys_ram_size)
7244 return -EINVAL;
7245 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7246 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7247 if (ret)
7248 return ret;
7249 }
7250 return 0;
7251}
7252
7253#define BDRV_HASH_BLOCK_SIZE 1024
7254#define IOBUF_SIZE 4096
7255#define RAM_CBLOCK_MAGIC 0xfabe
7256
c88676f8
FB
7257typedef struct RamDecompressState {
7258 z_stream zstream;
7259 QEMUFile *f;
7260 uint8_t buf[IOBUF_SIZE];
7261} RamDecompressState;
7262
7263static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7264{
7265 int ret;
7266 memset(s, 0, sizeof(*s));
7267 s->f = f;
7268 ret = inflateInit(&s->zstream);
7269 if (ret != Z_OK)
7270 return -1;
7271 return 0;
7272}
7273
7274static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7275{
7276 int ret, clen;
7277
7278 s->zstream.avail_out = len;
7279 s->zstream.next_out = buf;
7280 while (s->zstream.avail_out > 0) {
7281 if (s->zstream.avail_in == 0) {
7282 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7283 return -1;
7284 clen = qemu_get_be16(s->f);
7285 if (clen > IOBUF_SIZE)
7286 return -1;
7287 qemu_get_buffer(s->f, s->buf, clen);
7288 s->zstream.avail_in = clen;
7289 s->zstream.next_in = s->buf;
7290 }
7291 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7292 if (ret != Z_OK && ret != Z_STREAM_END) {
7293 return -1;
7294 }
7295 }
7296 return 0;
7297}
7298
7299static void ram_decompress_close(RamDecompressState *s)
7300{
7301 inflateEnd(&s->zstream);
7302}
7303
475e4277
AL
7304#define RAM_SAVE_FLAG_FULL 0x01
7305#define RAM_SAVE_FLAG_COMPRESS 0x02
7306#define RAM_SAVE_FLAG_MEM_SIZE 0x04
7307#define RAM_SAVE_FLAG_PAGE 0x08
7308#define RAM_SAVE_FLAG_EOS 0x10
7309
7310static int is_dup_page(uint8_t *page, uint8_t ch)
8a7ddc38 7311{
475e4277
AL
7312 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
7313 uint32_t *array = (uint32_t *)page;
7314 int i;
3b46e624 7315
475e4277
AL
7316 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
7317 if (array[i] != val)
7318 return 0;
7319 }
7320
7321 return 1;
7322}
7323
7324static int ram_save_block(QEMUFile *f)
7325{
7326 static ram_addr_t current_addr = 0;
7327 ram_addr_t saved_addr = current_addr;
7328 ram_addr_t addr = 0;
7329 int found = 0;
7330
7331 while (addr < phys_ram_size) {
7332 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
7333 uint8_t ch;
7334
7335 cpu_physical_memory_reset_dirty(current_addr,
7336 current_addr + TARGET_PAGE_SIZE,
7337 MIGRATION_DIRTY_FLAG);
7338
7339 ch = *(phys_ram_base + current_addr);
7340
7341 if (is_dup_page(phys_ram_base + current_addr, ch)) {
7342 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
7343 qemu_put_byte(f, ch);
7344 } else {
7345 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
7346 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
c88676f8 7347 }
475e4277
AL
7348
7349 found = 1;
7350 break;
c88676f8 7351 }
475e4277
AL
7352 addr += TARGET_PAGE_SIZE;
7353 current_addr = (saved_addr + addr) % phys_ram_size;
8a7ddc38 7354 }
475e4277
AL
7355
7356 return found;
8a7ddc38
FB
7357}
7358
475e4277
AL
7359static ram_addr_t ram_save_threshold = 10;
7360
7361static ram_addr_t ram_save_remaining(void)
7362{
7363 ram_addr_t addr;
7364 ram_addr_t count = 0;
7365
7366 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7367 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7368 count++;
7369 }
7370
7371 return count;
7372}
7373
7374static int ram_save_live(QEMUFile *f, int stage, void *opaque)
7375{
7376 ram_addr_t addr;
7377
7378 if (stage == 1) {
7379 /* Make sure all dirty bits are set */
7380 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7381 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7382 cpu_physical_memory_set_dirty(addr);
7383 }
7384
7385 /* Enable dirty memory tracking */
7386 cpu_physical_memory_set_dirty_tracking(1);
7387
7388 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
7389 }
7390
7391 while (!qemu_file_rate_limit(f)) {
7392 int ret;
7393
7394 ret = ram_save_block(f);
7395 if (ret == 0) /* no more blocks */
7396 break;
7397 }
7398
7399 /* try transferring iterative blocks of memory */
7400
7401 if (stage == 3) {
7402 cpu_physical_memory_set_dirty_tracking(0);
7403
7404 /* flush all remaining blocks regardless of rate limiting */
7405 while (ram_save_block(f) != 0);
7406 }
7407
7408 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
7409
7410 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
7411}
7412
7413static int ram_load_dead(QEMUFile *f, void *opaque)
8a7ddc38 7414{
c88676f8
FB
7415 RamDecompressState s1, *s = &s1;
7416 uint8_t buf[10];
00f82b8a 7417 ram_addr_t i;
8a7ddc38 7418
c88676f8
FB
7419 if (ram_decompress_open(s, f) < 0)
7420 return -EINVAL;
7421 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7422 if (ram_decompress_buf(s, buf, 1) < 0) {
7423 fprintf(stderr, "Error while reading ram block header\n");
7424 goto error;
7425 }
7426 if (buf[0] == 0) {
7427 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
00f82b8a 7428 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
c88676f8
FB
7429 goto error;
7430 }
475e4277 7431 } else {
c88676f8
FB
7432 error:
7433 printf("Error block header\n");
7434 return -EINVAL;
7435 }
8a7ddc38 7436 }
c88676f8 7437 ram_decompress_close(s);
475e4277
AL
7438
7439 return 0;
7440}
7441
7442static int ram_load(QEMUFile *f, void *opaque, int version_id)
7443{
7444 ram_addr_t addr;
7445 int flags;
7446
7447 if (version_id == 1)
7448 return ram_load_v1(f, opaque);
7449
7450 if (version_id == 2) {
7451 if (qemu_get_be32(f) != phys_ram_size)
7452 return -EINVAL;
7453 return ram_load_dead(f, opaque);
7454 }
7455
7456 if (version_id != 3)
7457 return -EINVAL;
7458
7459 do {
7460 addr = qemu_get_be64(f);
7461
7462 flags = addr & ~TARGET_PAGE_MASK;
7463 addr &= TARGET_PAGE_MASK;
7464
7465 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
7466 if (addr != phys_ram_size)
7467 return -EINVAL;
7468 }
7469
7470 if (flags & RAM_SAVE_FLAG_FULL) {
7471 if (ram_load_dead(f, opaque) < 0)
7472 return -EINVAL;
7473 }
7474
7475 if (flags & RAM_SAVE_FLAG_COMPRESS) {
7476 uint8_t ch = qemu_get_byte(f);
7477 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
7478 } else if (flags & RAM_SAVE_FLAG_PAGE)
7479 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7480 } while (!(flags & RAM_SAVE_FLAG_EOS));
7481
8a7ddc38
FB
7482 return 0;
7483}
7484
83f64091
FB
7485/***********************************************************/
7486/* bottom halves (can be seen as timers which expire ASAP) */
7487
7488struct QEMUBH {
7489 QEMUBHFunc *cb;
7490 void *opaque;
7491 int scheduled;
7492 QEMUBH *next;
7493};
7494
7495static QEMUBH *first_bh = NULL;
7496
7497QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7498{
7499 QEMUBH *bh;
7500 bh = qemu_mallocz(sizeof(QEMUBH));
7501 if (!bh)
7502 return NULL;
7503 bh->cb = cb;
7504 bh->opaque = opaque;
7505 return bh;
7506}
7507
6eb5733a 7508int qemu_bh_poll(void)
83f64091
FB
7509{
7510 QEMUBH *bh, **pbh;
6eb5733a 7511 int ret;
83f64091 7512
6eb5733a 7513 ret = 0;
83f64091
FB
7514 for(;;) {
7515 pbh = &first_bh;
7516 bh = *pbh;
7517 if (!bh)
7518 break;
6eb5733a 7519 ret = 1;
83f64091
FB
7520 *pbh = bh->next;
7521 bh->scheduled = 0;
7522 bh->cb(bh->opaque);
7523 }
6eb5733a 7524 return ret;
83f64091
FB
7525}
7526
7527void qemu_bh_schedule(QEMUBH *bh)
7528{
7529 CPUState *env = cpu_single_env;
7530 if (bh->scheduled)
7531 return;
7532 bh->scheduled = 1;
7533 bh->next = first_bh;
7534 first_bh = bh;
7535
7536 /* stop the currently executing CPU to execute the BH ASAP */
7537 if (env) {
7538 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7539 }
7540}
7541
7542void qemu_bh_cancel(QEMUBH *bh)
7543{
7544 QEMUBH **pbh;
7545 if (bh->scheduled) {
7546 pbh = &first_bh;
7547 while (*pbh != bh)
7548 pbh = &(*pbh)->next;
7549 *pbh = bh->next;
7550 bh->scheduled = 0;
7551 }
7552}
7553
7554void qemu_bh_delete(QEMUBH *bh)
7555{
7556 qemu_bh_cancel(bh);
7557 qemu_free(bh);
7558}
7559
cc1daa40
FB
7560/***********************************************************/
7561/* machine registration */
7562
bdaf78e0 7563static QEMUMachine *first_machine = NULL;
cc1daa40
FB
7564
7565int qemu_register_machine(QEMUMachine *m)
7566{
7567 QEMUMachine **pm;
7568 pm = &first_machine;
7569 while (*pm != NULL)
7570 pm = &(*pm)->next;
7571 m->next = NULL;
7572 *pm = m;
7573 return 0;
7574}
7575
9596ebb7 7576static QEMUMachine *find_machine(const char *name)
cc1daa40
FB
7577{
7578 QEMUMachine *m;
7579
7580 for(m = first_machine; m != NULL; m = m->next) {
7581 if (!strcmp(m->name, name))
7582 return m;
7583 }
7584 return NULL;
7585}
7586
8a7ddc38
FB
7587/***********************************************************/
7588/* main execution loop */
7589
9596ebb7 7590static void gui_update(void *opaque)
8a7ddc38 7591{
740733bb
TS
7592 DisplayState *ds = opaque;
7593 ds->dpy_refresh(ds);
f442e08b
AJ
7594 qemu_mod_timer(ds->gui_timer,
7595 (ds->gui_timer_interval ?
7596 ds->gui_timer_interval :
7597 GUI_REFRESH_INTERVAL)
7598 + qemu_get_clock(rt_clock));
8a7ddc38
FB
7599}
7600
0bd48850
FB
7601struct vm_change_state_entry {
7602 VMChangeStateHandler *cb;
7603 void *opaque;
7604 LIST_ENTRY (vm_change_state_entry) entries;
7605};
7606
7607static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7608
7609VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7610 void *opaque)
7611{
7612 VMChangeStateEntry *e;
7613
7614 e = qemu_mallocz(sizeof (*e));
7615 if (!e)
7616 return NULL;
7617
7618 e->cb = cb;
7619 e->opaque = opaque;
7620 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7621 return e;
7622}
7623
7624void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7625{
7626 LIST_REMOVE (e, entries);
7627 qemu_free (e);
7628}
7629
7630static void vm_state_notify(int running)
7631{
7632 VMChangeStateEntry *e;
7633
7634 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7635 e->cb(e->opaque, running);
7636 }
7637}
7638
8a7ddc38 7639/* XXX: support several handlers */
0bd48850
FB
7640static VMStopHandler *vm_stop_cb;
7641static void *vm_stop_opaque;
8a7ddc38
FB
7642
7643int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7644{
7645 vm_stop_cb = cb;
7646 vm_stop_opaque = opaque;
7647 return 0;
7648}
7649
7650void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7651{
7652 vm_stop_cb = NULL;
7653}
7654
7655void vm_start(void)
7656{
7657 if (!vm_running) {
7658 cpu_enable_ticks();
7659 vm_running = 1;
0bd48850 7660 vm_state_notify(1);
efe75411 7661 qemu_rearm_alarm_timer(alarm_timer);
8a7ddc38
FB
7662 }
7663}
7664
5fafdf24 7665void vm_stop(int reason)
8a7ddc38
FB
7666{
7667 if (vm_running) {
7668 cpu_disable_ticks();
7669 vm_running = 0;
7670 if (reason != 0) {
7671 if (vm_stop_cb) {
7672 vm_stop_cb(vm_stop_opaque, reason);
7673 }
34865134 7674 }
0bd48850 7675 vm_state_notify(0);
8a7ddc38
FB
7676 }
7677}
7678
bb0c6722
FB
7679/* reset/shutdown handler */
7680
7681typedef struct QEMUResetEntry {
7682 QEMUResetHandler *func;
7683 void *opaque;
7684 struct QEMUResetEntry *next;
7685} QEMUResetEntry;
7686
7687static QEMUResetEntry *first_reset_entry;
7688static int reset_requested;
7689static int shutdown_requested;
3475187d 7690static int powerdown_requested;
bb0c6722 7691
cf7a2fe2
AJ
7692int qemu_shutdown_requested(void)
7693{
7694 int r = shutdown_requested;
7695 shutdown_requested = 0;
7696 return r;
7697}
7698
7699int qemu_reset_requested(void)
7700{
7701 int r = reset_requested;
7702 reset_requested = 0;
7703 return r;
7704}
7705
7706int qemu_powerdown_requested(void)
7707{
7708 int r = powerdown_requested;
7709 powerdown_requested = 0;
7710 return r;
7711}
7712
bb0c6722
FB
7713void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7714{
7715 QEMUResetEntry **pre, *re;
7716
7717 pre = &first_reset_entry;
7718 while (*pre != NULL)
7719 pre = &(*pre)->next;
7720 re = qemu_mallocz(sizeof(QEMUResetEntry));
7721 re->func = func;
7722 re->opaque = opaque;
7723 re->next = NULL;
7724 *pre = re;
7725}
7726
cf7a2fe2 7727void qemu_system_reset(void)
bb0c6722
FB
7728{
7729 QEMUResetEntry *re;
7730
7731 /* reset all devices */
7732 for(re = first_reset_entry; re != NULL; re = re->next) {
7733 re->func(re->opaque);
7734 }
7735}
7736
7737void qemu_system_reset_request(void)
7738{
d1beab82
FB
7739 if (no_reboot) {
7740 shutdown_requested = 1;
7741 } else {
7742 reset_requested = 1;
7743 }
6a00d601
FB
7744 if (cpu_single_env)
7745 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
7746}
7747
7748void qemu_system_shutdown_request(void)
7749{
7750 shutdown_requested = 1;
6a00d601
FB
7751 if (cpu_single_env)
7752 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
7753}
7754
3475187d
FB
7755void qemu_system_powerdown_request(void)
7756{
7757 powerdown_requested = 1;
6a00d601
FB
7758 if (cpu_single_env)
7759 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
7760}
7761
5905b2e5 7762void main_loop_wait(int timeout)
8a7ddc38 7763{
cafffd40 7764 IOHandlerRecord *ioh;
e035649e 7765 fd_set rfds, wfds, xfds;
877cf882
TS
7766 int ret, nfds;
7767#ifdef _WIN32
7768 int ret2, i;
7769#endif
fd1dff4b 7770 struct timeval tv;
f331110f
FB
7771 PollingEntry *pe;
7772
c4b1fcc0 7773
f331110f
FB
7774 /* XXX: need to suppress polling by better using win32 events */
7775 ret = 0;
7776 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7777 ret |= pe->func(pe->opaque);
7778 }
38e205a2 7779#ifdef _WIN32
e6b1e558 7780 if (ret == 0) {
a18e524a
FB
7781 int err;
7782 WaitObjects *w = &wait_objects;
3b46e624 7783
a18e524a
FB
7784 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7785 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7786 if (w->func[ret - WAIT_OBJECT_0])
7787 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3b46e624 7788
5fafdf24 7789 /* Check for additional signaled events */
e6b1e558 7790 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3b46e624 7791
e6b1e558
TS
7792 /* Check if event is signaled */
7793 ret2 = WaitForSingleObject(w->events[i], 0);
7794 if(ret2 == WAIT_OBJECT_0) {
7795 if (w->func[i])
7796 w->func[i](w->opaque[i]);
7797 } else if (ret2 == WAIT_TIMEOUT) {
7798 } else {
7799 err = GetLastError();
7800 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3b46e624
TS
7801 }
7802 }
a18e524a
FB
7803 } else if (ret == WAIT_TIMEOUT) {
7804 } else {
7805 err = GetLastError();
e6b1e558 7806 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 7807 }
f331110f 7808 }
fd1dff4b
FB
7809#endif
7810 /* poll any events */
7811 /* XXX: separate device handlers from system ones */
7812 nfds = -1;
7813 FD_ZERO(&rfds);
7814 FD_ZERO(&wfds);
e035649e 7815 FD_ZERO(&xfds);
fd1dff4b 7816 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
7817 if (ioh->deleted)
7818 continue;
fd1dff4b
FB
7819 if (ioh->fd_read &&
7820 (!ioh->fd_read_poll ||
7821 ioh->fd_read_poll(ioh->opaque) != 0)) {
7822 FD_SET(ioh->fd, &rfds);
7823 if (ioh->fd > nfds)
7824 nfds = ioh->fd;
7825 }
7826 if (ioh->fd_write) {
7827 FD_SET(ioh->fd, &wfds);
7828 if (ioh->fd > nfds)
7829 nfds = ioh->fd;
7830 }
7831 }
3b46e624 7832
fd1dff4b
FB
7833 tv.tv_sec = 0;
7834#ifdef _WIN32
7835 tv.tv_usec = 0;
38e205a2 7836#else
fd1dff4b
FB
7837 tv.tv_usec = timeout * 1000;
7838#endif
e035649e
FB
7839#if defined(CONFIG_SLIRP)
7840 if (slirp_inited) {
7841 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7842 }
7843#endif
7844 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
fd1dff4b 7845 if (ret > 0) {
cafffd40
TS
7846 IOHandlerRecord **pioh;
7847
7848 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6ab43fdc 7849 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
fd1dff4b 7850 ioh->fd_read(ioh->opaque);
7c9d8e07 7851 }
6ab43fdc 7852 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
fd1dff4b 7853 ioh->fd_write(ioh->opaque);
c4b1fcc0 7854 }
b4608c04 7855 }
cafffd40
TS
7856
7857 /* remove deleted IO handlers */
7858 pioh = &first_io_handler;
7859 while (*pioh) {
7860 ioh = *pioh;
7861 if (ioh->deleted) {
7862 *pioh = ioh->next;
7863 qemu_free(ioh);
5fafdf24 7864 } else
cafffd40
TS
7865 pioh = &ioh->next;
7866 }
fd1dff4b 7867 }
c20709aa 7868#if defined(CONFIG_SLIRP)
fd1dff4b 7869 if (slirp_inited) {
e035649e
FB
7870 if (ret < 0) {
7871 FD_ZERO(&rfds);
7872 FD_ZERO(&wfds);
7873 FD_ZERO(&xfds);
c20709aa 7874 }
e035649e 7875 slirp_select_poll(&rfds, &wfds, &xfds);
fd1dff4b 7876 }
e035649e 7877#endif
b4608c04 7878
fd1dff4b 7879 if (vm_running) {
21b20814 7880 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
5fafdf24 7881 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
fd1dff4b
FB
7882 qemu_get_clock(vm_clock));
7883 /* run dma transfers, if any */
7884 DMA_run();
7885 }
423f0742 7886
fd1dff4b 7887 /* real time timers */
5fafdf24 7888 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
fd1dff4b 7889 qemu_get_clock(rt_clock));
423f0742 7890
d5d08334
AZ
7891 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7892 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7893 qemu_rearm_alarm_timer(alarm_timer);
7894 }
b99dc0d1 7895
423f0742
PB
7896 /* Check bottom-halves last in case any of the earlier events triggered
7897 them. */
7898 qemu_bh_poll();
3b46e624 7899
5905b2e5
FB
7900}
7901
9596ebb7 7902static int main_loop(void)
5905b2e5
FB
7903{
7904 int ret, timeout;
89bfc105
FB
7905#ifdef CONFIG_PROFILER
7906 int64_t ti;
7907#endif
6a00d601 7908 CPUState *env;
5905b2e5 7909
6a00d601 7910 cur_cpu = first_cpu;
ee5605e5 7911 next_cpu = cur_cpu->next_cpu ?: first_cpu;
5905b2e5
FB
7912 for(;;) {
7913 if (vm_running) {
15a76449 7914
15a76449
FB
7915 for(;;) {
7916 /* get next cpu */
ee5605e5 7917 env = next_cpu;
89bfc105
FB
7918#ifdef CONFIG_PROFILER
7919 ti = profile_getclock();
7920#endif
2e70f6ef
PB
7921 if (use_icount) {
7922 int64_t count;
7923 int decr;
7924 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7925 env->icount_decr.u16.low = 0;
7926 env->icount_extra = 0;
7927 count = qemu_next_deadline();
7928 count = (count + (1 << icount_time_shift) - 1)
7929 >> icount_time_shift;
7930 qemu_icount += count;
7931 decr = (count > 0xffff) ? 0xffff : count;
7932 count -= decr;
7933 env->icount_decr.u16.low = decr;
7934 env->icount_extra = count;
7935 }
6a00d601 7936 ret = cpu_exec(env);
89bfc105
FB
7937#ifdef CONFIG_PROFILER
7938 qemu_time += profile_getclock() - ti;
7939#endif
2e70f6ef
PB
7940 if (use_icount) {
7941 /* Fold pending instructions back into the
7942 instruction counter, and clear the interrupt flag. */
7943 qemu_icount -= (env->icount_decr.u16.low
7944 + env->icount_extra);
7945 env->icount_decr.u32 = 0;
7946 env->icount_extra = 0;
7947 }
ee5605e5 7948 next_cpu = env->next_cpu ?: first_cpu;
95b01009 7949 if (event_pending && likely(ret != EXCP_DEBUG)) {
ee5605e5
AZ
7950 ret = EXCP_INTERRUPT;
7951 event_pending = 0;
7952 break;
7953 }
bd967e05
PB
7954 if (ret == EXCP_HLT) {
7955 /* Give the next CPU a chance to run. */
7956 cur_cpu = env;
7957 continue;
7958 }
15a76449
FB
7959 if (ret != EXCP_HALTED)
7960 break;
7961 /* all CPUs are halted ? */
bd967e05 7962 if (env == cur_cpu)
15a76449 7963 break;
15a76449
FB
7964 }
7965 cur_cpu = env;
7966
5905b2e5 7967 if (shutdown_requested) {
3475187d 7968 ret = EXCP_INTERRUPT;
b2f76161
AJ
7969 if (no_shutdown) {
7970 vm_stop(0);
7971 no_shutdown = 0;
7972 }
7973 else
7974 break;
5905b2e5
FB
7975 }
7976 if (reset_requested) {
7977 reset_requested = 0;
7978 qemu_system_reset();
3475187d
FB
7979 ret = EXCP_INTERRUPT;
7980 }
7981 if (powerdown_requested) {
7982 powerdown_requested = 0;
7983 qemu_system_powerdown();
7984 ret = EXCP_INTERRUPT;
5905b2e5 7985 }
95b01009 7986 if (unlikely(ret == EXCP_DEBUG)) {
5905b2e5
FB
7987 vm_stop(EXCP_DEBUG);
7988 }
bd967e05 7989 /* If all cpus are halted then wait until the next IRQ */
5905b2e5 7990 /* XXX: use timeout computed from timers */
2e70f6ef
PB
7991 if (ret == EXCP_HALTED) {
7992 if (use_icount) {
7993 int64_t add;
7994 int64_t delta;
7995 /* Advance virtual time to the next event. */
7996 if (use_icount == 1) {
7997 /* When not using an adaptive execution frequency
7998 we tend to get badly out of sync with real time,
bf20dc07 7999 so just delay for a reasonable amount of time. */
2e70f6ef
PB
8000 delta = 0;
8001 } else {
8002 delta = cpu_get_icount() - cpu_get_clock();
8003 }
8004 if (delta > 0) {
8005 /* If virtual time is ahead of real time then just
8006 wait for IO. */
8007 timeout = (delta / 1000000) + 1;
8008 } else {
8009 /* Wait for either IO to occur or the next
8010 timer event. */
8011 add = qemu_next_deadline();
8012 /* We advance the timer before checking for IO.
8013 Limit the amount we advance so that early IO
8014 activity won't get the guest too far ahead. */
8015 if (add > 10000000)
8016 add = 10000000;
8017 delta += add;
8018 add = (add + (1 << icount_time_shift) - 1)
8019 >> icount_time_shift;
8020 qemu_icount += add;
8021 timeout = delta / 1000000;
8022 if (timeout < 0)
8023 timeout = 0;
8024 }
8025 } else {
8026 timeout = 10;
8027 }
8028 } else {
5905b2e5 8029 timeout = 0;
2e70f6ef 8030 }
5905b2e5 8031 } else {
98448f58
BS
8032 if (shutdown_requested) {
8033 ret = EXCP_INTERRUPT;
5b08fc10 8034 break;
98448f58 8035 }
5905b2e5
FB
8036 timeout = 10;
8037 }
89bfc105
FB
8038#ifdef CONFIG_PROFILER
8039 ti = profile_getclock();
8040#endif
5905b2e5 8041 main_loop_wait(timeout);
89bfc105
FB
8042#ifdef CONFIG_PROFILER
8043 dev_time += profile_getclock() - ti;
8044#endif
b4608c04 8045 }
34865134
FB
8046 cpu_disable_ticks();
8047 return ret;
b4608c04
FB
8048}
8049
15f82208 8050static void help(int exitcode)
0824d6fc 8051{
68d0f70e 8052 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
0db63474 8053 "usage: %s [options] [disk_image]\n"
0824d6fc 8054 "\n"
a20dd508 8055 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 8056 "\n"
a20dd508 8057 "Standard options:\n"
cc1daa40 8058 "-M machine select emulated machine (-M ? for list)\n"
5adb4839 8059 "-cpu cpu select CPU (-cpu ? for list)\n"
c45886db 8060 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
36b486bb
FB
8061 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8062 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
c4b1fcc0 8063 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
a1620fac
AJ
8064 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8065 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8066 " [,cache=on|off][,format=f]\n"
e4bcb14c 8067 " use 'file' as a drive image\n"
3e3d5815 8068 "-mtdblock file use 'file' as on-board Flash memory image\n"
a1bb27b1 8069 "-sd file use 'file' as SecureDigital card image\n"
86f55663 8070 "-pflash file use 'file' as a parallel flash image\n"
eec85c2a 8071 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
667accab
TS
8072 "-snapshot write to temporary files instead of disk image files\n"
8073#ifdef CONFIG_SDL
43523e93 8074 "-no-frame open SDL window without a frame and window decorations\n"
3780e197 8075 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
667accab
TS
8076 "-no-quit disable SDL window close capability\n"
8077#endif
52ca8d6a
FB
8078#ifdef TARGET_I386
8079 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8080#endif
a00bad7e 8081 "-m megs set virtual RAM size to megs MB [default=%d]\n"
91fc2119 8082 "-smp n set the number of CPUs to 'n' [default=1]\n"
c4b1fcc0 8083 "-nographic disable graphical output and redirect serial I/Os to console\n"
a171fe39 8084 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4ca0074c 8085#ifndef _WIN32
667accab 8086 "-k language use keyboard layout (for example \"fr\" for French)\n"
4ca0074c 8087#endif
1d14ffa9 8088#ifdef HAS_AUDIO
1d14ffa9 8089 "-audio-help print list of audio drivers and their options\n"
c0fe3827
FB
8090 "-soundhw c1,... enable audio support\n"
8091 " and only specified sound cards (comma separated list)\n"
8092 " use -soundhw ? to get the list of supported cards\n"
6a36d84e 8093 " use -soundhw all to enable all of them\n"
1d14ffa9 8094#endif
3893c124 8095 "-vga [std|cirrus|vmware]\n"
8096 " select video card type\n"
89980284 8097 "-localtime set the real time clock to local time [default=utc]\n"
d63d307f 8098 "-full-screen start in full screen\n"
a09db21f
FB
8099#ifdef TARGET_I386
8100 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8101#endif
b389dbfb
FB
8102 "-usb enable the USB driver (will be the default soon)\n"
8103 "-usbdevice name add the host or guest USB device 'name'\n"
6f7e9aec
FB
8104#if defined(TARGET_PPC) || defined(TARGET_SPARC)
8105 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
bb0c6722 8106#endif
c35734b2 8107 "-name string set the name of the guest\n"
8fcb1b90 8108 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
c4b1fcc0
FB
8109 "\n"
8110 "Network options:\n"
a41b2ff2 8111 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7c9d8e07 8112 " create a new Network Interface Card and connect it to VLAN 'n'\n"
c20709aa 8113#ifdef CONFIG_SLIRP
115defd1
PB
8114 "-net user[,vlan=n][,hostname=host]\n"
8115 " connect the user mode network stack to VLAN 'n' and send\n"
8116 " hostname 'host' to DHCP clients\n"
7c9d8e07 8117#endif
7fb843f8
FB
8118#ifdef _WIN32
8119 "-net tap[,vlan=n],ifname=name\n"
8120 " connect the host TAP network interface to VLAN 'n'\n"
8121#else
b46a8906
TS
8122 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8123 " connect the host TAP network interface to VLAN 'n' and use the\n"
8124 " network scripts 'file' (default=%s)\n"
8125 " and 'dfile' (default=%s);\n"
8126 " use '[down]script=no' to disable script execution;\n"
7c9d8e07 8127 " use 'fd=h' to connect to an already opened TAP interface\n"
7fb843f8 8128#endif
6a00d601 8129 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7c9d8e07 8130 " connect the vlan 'n' to another VLAN using a socket connection\n"
3d830459
FB
8131 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8132 " connect the vlan 'n' to multicast maddr and port\n"
8a16d273
TS
8133#ifdef CONFIG_VDE
8134 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8135 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8136 " on host and listening for incoming connections on 'socketpath'.\n"
8137 " Use group 'groupname' and mode 'octalmode' to change default\n"
8138 " ownership and permissions for communication port.\n"
8139#endif
7c9d8e07
FB
8140 "-net none use it alone to have zero network devices; if no -net option\n"
8141 " is provided, the default is '-net nic -net user'\n"
8142 "\n"
8143#ifdef CONFIG_SLIRP
0db1137d 8144 "-tftp dir allow tftp access to files in dir [-net user]\n"
47d5d01a 8145 "-bootp file advertise file in BOOTP replies\n"
7c9d8e07
FB
8146#ifndef _WIN32
8147 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
c94c8d64 8148#endif
9bf05444 8149 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7c9d8e07 8150 " redirect TCP or UDP connections from host to guest [-net user]\n"
c20709aa 8151#endif
a20dd508 8152 "\n"
c4b1fcc0 8153 "Linux boot specific:\n"
a20dd508
FB
8154 "-kernel bzImage use 'bzImage' as kernel image\n"
8155 "-append cmdline use 'cmdline' as kernel command line\n"
8156 "-initrd file use 'file' as initial ram disk\n"
fc01f7e7 8157 "\n"
330d0414 8158 "Debug/Expert options:\n"
82c643ff
FB
8159 "-monitor dev redirect the monitor to char device 'dev'\n"
8160 "-serial dev redirect the serial port to char device 'dev'\n"
6508fe59 8161 "-parallel dev redirect the parallel port to char device 'dev'\n"
f7cce898 8162 "-pidfile file Write PID to 'file'\n"
cd6f1169 8163 "-S freeze CPU at startup (use 'c' to start execution)\n"
cfc3475a
PB
8164 "-s wait gdb connection to port\n"
8165 "-p port set gdb connection port [default=%s]\n"
f193c797 8166 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
46d4767d
FB
8167 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8168 " translation (t=none or lba) (usually qemu can guess them)\n"
87b47350 8169 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
d993e026 8170#ifdef USE_KQEMU
6515b203 8171 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
d993e026
FB
8172 "-no-kqemu disable KQEMU kernel module usage\n"
8173#endif
bb0c6722 8174#ifdef TARGET_I386
6515b203 8175 "-no-acpi disable ACPI\n"
4d3b6f6e
AZ
8176#endif
8177#ifdef CONFIG_CURSES
8178 "-curses use a curses/ncurses interface instead of SDL\n"
bb0c6722 8179#endif
d1beab82 8180 "-no-reboot exit instead of rebooting\n"
b2f76161 8181 "-no-shutdown stop before shutdown\n"
a8080006 8182 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
24236869 8183 "-vnc display start a VNC server on display\n"
71e3ceb8
TS
8184#ifndef _WIN32
8185 "-daemonize daemonize QEMU after initializing\n"
8186#endif
9ae02555 8187 "-option-rom rom load a file, rom, into the option ROM space\n"
66508601
BS
8188#ifdef TARGET_SPARC
8189 "-prom-env variable=value set OpenBIOS nvram variables\n"
8190#endif
f3dcfada 8191 "-clock force the use of the given methods for timer alarm.\n"
3adda04c 8192 " To see what timers are available use -clock ?\n"
bce61846 8193 "-startdate select initial date of the clock\n"
2e70f6ef 8194 "-icount [N|auto]\n"
dd5d6fe9 8195 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
0824d6fc 8196 "\n"
82c643ff 8197 "During emulation, the following keys are useful:\n"
032a8c9e
FB
8198 "ctrl-alt-f toggle full screen\n"
8199 "ctrl-alt-n switch to virtual console 'n'\n"
8200 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
8201 "\n"
8202 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8203 ,
0db63474 8204 "qemu",
a00bad7e 8205 DEFAULT_RAM_SIZE,
7c9d8e07 8206#ifndef _WIN32
a00bad7e 8207 DEFAULT_NETWORK_SCRIPT,
b46a8906 8208 DEFAULT_NETWORK_DOWN_SCRIPT,
7c9d8e07 8209#endif
6e44ba7f 8210 DEFAULT_GDBSTUB_PORT,
bce61846 8211 "/tmp/qemu.log");
15f82208 8212 exit(exitcode);
0824d6fc
FB
8213}
8214
cd6f1169
FB
8215#define HAS_ARG 0x0001
8216
8217enum {
8218 QEMU_OPTION_h,
8219
cc1daa40 8220 QEMU_OPTION_M,
94fc95cd 8221 QEMU_OPTION_cpu,
cd6f1169
FB
8222 QEMU_OPTION_fda,
8223 QEMU_OPTION_fdb,
8224 QEMU_OPTION_hda,
8225 QEMU_OPTION_hdb,
8226 QEMU_OPTION_hdc,
8227 QEMU_OPTION_hdd,
e4bcb14c 8228 QEMU_OPTION_drive,
cd6f1169 8229 QEMU_OPTION_cdrom,
3e3d5815 8230 QEMU_OPTION_mtdblock,
a1bb27b1 8231 QEMU_OPTION_sd,
86f55663 8232 QEMU_OPTION_pflash,
cd6f1169
FB
8233 QEMU_OPTION_boot,
8234 QEMU_OPTION_snapshot,
52ca8d6a
FB
8235#ifdef TARGET_I386
8236 QEMU_OPTION_no_fd_bootchk,
8237#endif
cd6f1169
FB
8238 QEMU_OPTION_m,
8239 QEMU_OPTION_nographic,
a171fe39 8240 QEMU_OPTION_portrait,
1d14ffa9 8241#ifdef HAS_AUDIO
1d14ffa9
FB
8242 QEMU_OPTION_audio_help,
8243 QEMU_OPTION_soundhw,
8244#endif
cd6f1169 8245
7c9d8e07 8246 QEMU_OPTION_net,
c7f74643 8247 QEMU_OPTION_tftp,
47d5d01a 8248 QEMU_OPTION_bootp,
9d728e8c 8249 QEMU_OPTION_smb,
9bf05444 8250 QEMU_OPTION_redir,
cd6f1169
FB
8251
8252 QEMU_OPTION_kernel,
8253 QEMU_OPTION_append,
8254 QEMU_OPTION_initrd,
8255
8256 QEMU_OPTION_S,
8257 QEMU_OPTION_s,
8258 QEMU_OPTION_p,
8259 QEMU_OPTION_d,
8260 QEMU_OPTION_hdachs,
8261 QEMU_OPTION_L,
1192dad8 8262 QEMU_OPTION_bios,
3d11d0eb 8263 QEMU_OPTION_k,
ee22c2f7 8264 QEMU_OPTION_localtime,
e9b137c2 8265 QEMU_OPTION_g,
3893c124 8266 QEMU_OPTION_vga,
20d8a3ed 8267 QEMU_OPTION_echr,
82c643ff
FB
8268 QEMU_OPTION_monitor,
8269 QEMU_OPTION_serial,
6508fe59 8270 QEMU_OPTION_parallel,
d63d307f
FB
8271 QEMU_OPTION_loadvm,
8272 QEMU_OPTION_full_screen,
43523e93 8273 QEMU_OPTION_no_frame,
3780e197 8274 QEMU_OPTION_alt_grab,
667accab 8275 QEMU_OPTION_no_quit,
f7cce898 8276 QEMU_OPTION_pidfile,
d993e026 8277 QEMU_OPTION_no_kqemu,
89bfc105 8278 QEMU_OPTION_kernel_kqemu,
a09db21f 8279 QEMU_OPTION_win2k_hack,
bb36d470 8280 QEMU_OPTION_usb,
a594cfbf 8281 QEMU_OPTION_usbdevice,
6a00d601 8282 QEMU_OPTION_smp,
24236869 8283 QEMU_OPTION_vnc,
6515b203 8284 QEMU_OPTION_no_acpi,
4d3b6f6e 8285 QEMU_OPTION_curses,
d1beab82 8286 QEMU_OPTION_no_reboot,
b2f76161 8287 QEMU_OPTION_no_shutdown,
9467cd46 8288 QEMU_OPTION_show_cursor,
71e3ceb8 8289 QEMU_OPTION_daemonize,
9ae02555 8290 QEMU_OPTION_option_rom,
c35734b2
TS
8291 QEMU_OPTION_semihosting,
8292 QEMU_OPTION_name,
66508601 8293 QEMU_OPTION_prom_env,
2b8f2d41 8294 QEMU_OPTION_old_param,
f3dcfada 8295 QEMU_OPTION_clock,
7e0af5d0 8296 QEMU_OPTION_startdate,
26a5f13b 8297 QEMU_OPTION_tb_size,
2e70f6ef 8298 QEMU_OPTION_icount,
8fcb1b90 8299 QEMU_OPTION_uuid,
cd6f1169
FB
8300};
8301
8302typedef struct QEMUOption {
8303 const char *name;
8304 int flags;
8305 int index;
8306} QEMUOption;
8307
dbed7e40 8308static const QEMUOption qemu_options[] = {
cd6f1169 8309 { "h", 0, QEMU_OPTION_h },
64423fb2 8310 { "help", 0, QEMU_OPTION_h },
cd6f1169 8311
cc1daa40 8312 { "M", HAS_ARG, QEMU_OPTION_M },
94fc95cd 8313 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
cd6f1169
FB
8314 { "fda", HAS_ARG, QEMU_OPTION_fda },
8315 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8316 { "hda", HAS_ARG, QEMU_OPTION_hda },
8317 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8318 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8319 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
e4bcb14c 8320 { "drive", HAS_ARG, QEMU_OPTION_drive },
cd6f1169 8321 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3e3d5815 8322 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
a1bb27b1 8323 { "sd", HAS_ARG, QEMU_OPTION_sd },
86f55663 8324 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
cd6f1169
FB
8325 { "boot", HAS_ARG, QEMU_OPTION_boot },
8326 { "snapshot", 0, QEMU_OPTION_snapshot },
52ca8d6a
FB
8327#ifdef TARGET_I386
8328 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8329#endif
cd6f1169
FB
8330 { "m", HAS_ARG, QEMU_OPTION_m },
8331 { "nographic", 0, QEMU_OPTION_nographic },
a171fe39 8332 { "portrait", 0, QEMU_OPTION_portrait },
3d11d0eb 8333 { "k", HAS_ARG, QEMU_OPTION_k },
1d14ffa9 8334#ifdef HAS_AUDIO
1d14ffa9
FB
8335 { "audio-help", 0, QEMU_OPTION_audio_help },
8336 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8337#endif
cd6f1169 8338
7c9d8e07 8339 { "net", HAS_ARG, QEMU_OPTION_net},
158156d1 8340#ifdef CONFIG_SLIRP
c7f74643 8341 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
47d5d01a 8342 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
c94c8d64 8343#ifndef _WIN32
9d728e8c 8344 { "smb", HAS_ARG, QEMU_OPTION_smb },
c94c8d64 8345#endif
9bf05444 8346 { "redir", HAS_ARG, QEMU_OPTION_redir },
158156d1 8347#endif
cd6f1169
FB
8348
8349 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8350 { "append", HAS_ARG, QEMU_OPTION_append },
8351 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8352
8353 { "S", 0, QEMU_OPTION_S },
8354 { "s", 0, QEMU_OPTION_s },
8355 { "p", HAS_ARG, QEMU_OPTION_p },
8356 { "d", HAS_ARG, QEMU_OPTION_d },
8357 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8358 { "L", HAS_ARG, QEMU_OPTION_L },
1192dad8 8359 { "bios", HAS_ARG, QEMU_OPTION_bios },
d993e026
FB
8360#ifdef USE_KQEMU
8361 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
89bfc105 8362 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
d993e026 8363#endif
6f7e9aec 8364#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2 8365 { "g", 1, QEMU_OPTION_g },
77d4bc34 8366#endif
ee22c2f7 8367 { "localtime", 0, QEMU_OPTION_localtime },
3893c124 8368 { "vga", HAS_ARG, QEMU_OPTION_vga },
8b6e0729
AZ
8369 { "echr", HAS_ARG, QEMU_OPTION_echr },
8370 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8371 { "serial", HAS_ARG, QEMU_OPTION_serial },
8372 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
d63d307f
FB
8373 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8374 { "full-screen", 0, QEMU_OPTION_full_screen },
667accab 8375#ifdef CONFIG_SDL
43523e93 8376 { "no-frame", 0, QEMU_OPTION_no_frame },
3780e197 8377 { "alt-grab", 0, QEMU_OPTION_alt_grab },
667accab
TS
8378 { "no-quit", 0, QEMU_OPTION_no_quit },
8379#endif
f7cce898 8380 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
a09db21f 8381 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
a594cfbf 8382 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6a00d601 8383 { "smp", HAS_ARG, QEMU_OPTION_smp },
24236869 8384 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4d3b6f6e
AZ
8385#ifdef CONFIG_CURSES
8386 { "curses", 0, QEMU_OPTION_curses },
8387#endif
8fcb1b90 8388 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
96d30e48 8389
1f04275e 8390 /* temporary options */
a594cfbf 8391 { "usb", 0, QEMU_OPTION_usb },
6515b203 8392 { "no-acpi", 0, QEMU_OPTION_no_acpi },
d1beab82 8393 { "no-reboot", 0, QEMU_OPTION_no_reboot },
b2f76161 8394 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
9467cd46 8395 { "show-cursor", 0, QEMU_OPTION_show_cursor },
71e3ceb8 8396 { "daemonize", 0, QEMU_OPTION_daemonize },
9ae02555 8397 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
a87295e8 8398#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
8399 { "semihosting", 0, QEMU_OPTION_semihosting },
8400#endif
c35734b2 8401 { "name", HAS_ARG, QEMU_OPTION_name },
66508601
BS
8402#if defined(TARGET_SPARC)
8403 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
2b8f2d41
AZ
8404#endif
8405#if defined(TARGET_ARM)
8406 { "old-param", 0, QEMU_OPTION_old_param },
66508601 8407#endif
f3dcfada 8408 { "clock", HAS_ARG, QEMU_OPTION_clock },
7e0af5d0 8409 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
26a5f13b 8410 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
2e70f6ef 8411 { "icount", HAS_ARG, QEMU_OPTION_icount },
cd6f1169 8412 { NULL },
fc01f7e7
FB
8413};
8414
5905b2e5
FB
8415/* password input */
8416
2bac6019
AZ
8417int qemu_key_check(BlockDriverState *bs, const char *name)
8418{
8419 char password[256];
8420 int i;
8421
8422 if (!bdrv_is_encrypted(bs))
8423 return 0;
8424
8425 term_printf("%s is encrypted.\n", name);
8426 for(i = 0; i < 3; i++) {
8427 monitor_readline("Password: ", 1, password, sizeof(password));
8428 if (bdrv_set_key(bs, password) == 0)
8429 return 0;
8430 term_printf("invalid password\n");
8431 }
8432 return -EPERM;
8433}
8434
83ab7950
AL
8435static BlockDriverState *get_bdrv(int index)
8436{
8437 if (index > nb_drives)
8438 return NULL;
8439 return drives_table[index].bdrv;
8440}
8441
5905b2e5
FB
8442static void read_passwords(void)
8443{
8444 BlockDriverState *bs;
2bac6019 8445 int i;
5905b2e5 8446
83ab7950
AL
8447 for(i = 0; i < 6; i++) {
8448 bs = get_bdrv(i);
8449 if (bs)
8450 qemu_key_check(bs, bdrv_get_device_name(bs));
5905b2e5
FB
8451 }
8452}
8453
1d14ffa9 8454#ifdef HAS_AUDIO
6a36d84e 8455struct soundhw soundhw[] = {
b00052e4 8456#ifdef HAS_AUDIO_CHOICE
4ce7ff6e 8457#if defined(TARGET_I386) || defined(TARGET_MIPS)
fd06c375
FB
8458 {
8459 "pcspk",
8460 "PC speaker",
8461 0,
8462 1,
8463 { .init_isa = pcspk_audio_init }
8464 },
8465#endif
6a36d84e
FB
8466 {
8467 "sb16",
8468 "Creative Sound Blaster 16",
8469 0,
8470 1,
8471 { .init_isa = SB16_init }
8472 },
8473
cc53d26d 8474#ifdef CONFIG_CS4231A
8475 {
8476 "cs4231a",
8477 "CS4231A",
8478 0,
8479 1,
8480 { .init_isa = cs4231a_init }
8481 },
8482#endif
8483
1d14ffa9 8484#ifdef CONFIG_ADLIB
6a36d84e
FB
8485 {
8486 "adlib",
1d14ffa9 8487#ifdef HAS_YMF262
6a36d84e 8488 "Yamaha YMF262 (OPL3)",
1d14ffa9 8489#else
6a36d84e 8490 "Yamaha YM3812 (OPL2)",
1d14ffa9 8491#endif
6a36d84e
FB
8492 0,
8493 1,
8494 { .init_isa = Adlib_init }
8495 },
1d14ffa9 8496#endif
6a36d84e 8497
1d14ffa9 8498#ifdef CONFIG_GUS
6a36d84e
FB
8499 {
8500 "gus",
8501 "Gravis Ultrasound GF1",
8502 0,
8503 1,
8504 { .init_isa = GUS_init }
8505 },
1d14ffa9 8506#endif
6a36d84e 8507
e5c9a13e
AZ
8508#ifdef CONFIG_AC97
8509 {
8510 "ac97",
8511 "Intel 82801AA AC97 Audio",
8512 0,
8513 0,
8514 { .init_pci = ac97_init }
8515 },
8516#endif
8517
6a36d84e
FB
8518 {
8519 "es1370",
8520 "ENSONIQ AudioPCI ES1370",
8521 0,
8522 0,
8523 { .init_pci = es1370_init }
8524 },
b00052e4 8525#endif
6a36d84e
FB
8526
8527 { NULL, NULL, 0, 0, { NULL } }
8528};
8529
8530static void select_soundhw (const char *optarg)
8531{
8532 struct soundhw *c;
8533
8534 if (*optarg == '?') {
8535 show_valid_cards:
8536
8537 printf ("Valid sound card names (comma separated):\n");
8538 for (c = soundhw; c->name; ++c) {
8539 printf ("%-11s %s\n", c->name, c->descr);
8540 }
8541 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
8542 exit (*optarg != '?');
8543 }
8544 else {
6a36d84e 8545 size_t l;
1d14ffa9
FB
8546 const char *p;
8547 char *e;
8548 int bad_card = 0;
8549
6a36d84e
FB
8550 if (!strcmp (optarg, "all")) {
8551 for (c = soundhw; c->name; ++c) {
8552 c->enabled = 1;
8553 }
8554 return;
8555 }
1d14ffa9 8556
6a36d84e 8557 p = optarg;
1d14ffa9
FB
8558 while (*p) {
8559 e = strchr (p, ',');
8560 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
8561
8562 for (c = soundhw; c->name; ++c) {
8563 if (!strncmp (c->name, p, l)) {
8564 c->enabled = 1;
1d14ffa9
FB
8565 break;
8566 }
8567 }
6a36d84e
FB
8568
8569 if (!c->name) {
1d14ffa9
FB
8570 if (l > 80) {
8571 fprintf (stderr,
8572 "Unknown sound card name (too big to show)\n");
8573 }
8574 else {
8575 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8576 (int) l, p);
8577 }
8578 bad_card = 1;
8579 }
8580 p += l + (e != NULL);
8581 }
8582
8583 if (bad_card)
8584 goto show_valid_cards;
8585 }
8586}
8587#endif
8588
3893c124 8589static void select_vgahw (const char *p)
8590{
8591 const char *opts;
8592
8593 if (strstart(p, "std", &opts)) {
8594 cirrus_vga_enabled = 0;
8595 vmsvga_enabled = 0;
8596 } else if (strstart(p, "cirrus", &opts)) {
8597 cirrus_vga_enabled = 1;
8598 vmsvga_enabled = 0;
8599 } else if (strstart(p, "vmware", &opts)) {
8600 cirrus_vga_enabled = 0;
8601 vmsvga_enabled = 1;
8602 } else {
8603 invalid_vga:
8604 fprintf(stderr, "Unknown vga type: %s\n", p);
8605 exit(1);
8606 }
cb5a7aa8 8607 while (*opts) {
8608 const char *nextopt;
8609
8610 if (strstart(opts, ",retrace=", &nextopt)) {
8611 opts = nextopt;
8612 if (strstart(opts, "dumb", &nextopt))
8613 vga_retrace_method = VGA_RETRACE_DUMB;
8614 else if (strstart(opts, "precise", &nextopt))
8615 vga_retrace_method = VGA_RETRACE_PRECISE;
8616 else goto invalid_vga;
8617 } else goto invalid_vga;
8618 opts = nextopt;
8619 }
3893c124 8620}
8621
3587d7e6
FB
8622#ifdef _WIN32
8623static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8624{
8625 exit(STATUS_CONTROL_C_EXIT);
8626 return TRUE;
8627}
8628#endif
8629
8fcb1b90
BS
8630static int qemu_uuid_parse(const char *str, uint8_t *uuid)
8631{
8632 int ret;
8633
8634 if(strlen(str) != 36)
8635 return -1;
8636
8637 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
8638 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
8639 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
8640
8641 if(ret != 16)
8642 return -1;
8643
8644 return 0;
8645}
8646
7c9d8e07 8647#define MAX_NET_CLIENTS 32
c20709aa 8648
5b08fc10
AL
8649#ifndef _WIN32
8650
8651static void termsig_handler(int signal)
8652{
8653 qemu_system_shutdown_request();
8654}
8655
6f9e3801 8656static void termsig_setup(void)
5b08fc10
AL
8657{
8658 struct sigaction act;
8659
8660 memset(&act, 0, sizeof(act));
8661 act.sa_handler = termsig_handler;
8662 sigaction(SIGINT, &act, NULL);
8663 sigaction(SIGHUP, &act, NULL);
8664 sigaction(SIGTERM, &act, NULL);
8665}
8666
8667#endif
8668
0824d6fc
FB
8669int main(int argc, char **argv)
8670{
67b915a5 8671#ifdef CONFIG_GDBSTUB
cfc3475a
PB
8672 int use_gdbstub;
8673 const char *gdbstub_port;
67b915a5 8674#endif
28c5af54 8675 uint32_t boot_devices_bitmap = 0;
e4bcb14c 8676 int i;
28c5af54 8677 int snapshot, linux_boot, net_boot;
7f7f9873 8678 const char *initrd_filename;
a20dd508 8679 const char *kernel_filename, *kernel_cmdline;
28c5af54 8680 const char *boot_devices = "";
313aa567 8681 DisplayState *ds = &display_state;
46d4767d 8682 int cyls, heads, secs, translation;
fd5f393a 8683 const char *net_clients[MAX_NET_CLIENTS];
7c9d8e07 8684 int nb_net_clients;
e4bcb14c 8685 int hda_index;
cd6f1169
FB
8686 int optind;
8687 const char *r, *optarg;
82c643ff 8688 CharDriverState *monitor_hd;
fd5f393a
PB
8689 const char *monitor_device;
8690 const char *serial_devices[MAX_SERIAL_PORTS];
8d11df9e 8691 int serial_device_index;
fd5f393a 8692 const char *parallel_devices[MAX_PARALLEL_PORTS];
6508fe59 8693 int parallel_device_index;
d63d307f 8694 const char *loadvm = NULL;
cc1daa40 8695 QEMUMachine *machine;
94fc95cd 8696 const char *cpu_model;
fd5f393a 8697 const char *usb_devices[MAX_USB_CMDLINE];
a594cfbf 8698 int usb_devices_index;
71e3ceb8 8699 int fds[2];
26a5f13b 8700 int tb_size;
93815bc2 8701 const char *pid_file = NULL;
833c7174 8702 VLANState *vlan;
41bd639b 8703 int autostart;
0bd48850
FB
8704
8705 LIST_INIT (&vm_change_state_head);
be995c27
FB
8706#ifndef _WIN32
8707 {
8708 struct sigaction act;
8709 sigfillset(&act.sa_mask);
8710 act.sa_flags = 0;
8711 act.sa_handler = SIG_IGN;
8712 sigaction(SIGPIPE, &act, NULL);
8713 }
3587d7e6
FB
8714#else
8715 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
8716 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8717 QEMU to run on a single CPU */
8718 {
8719 HANDLE h;
8720 DWORD mask, smask;
8721 int i;
8722 h = GetCurrentProcess();
8723 if (GetProcessAffinityMask(h, &mask, &smask)) {
8724 for(i = 0; i < 32; i++) {
8725 if (mask & (1 << i))
8726 break;
8727 }
8728 if (i != 32) {
8729 mask = 1 << i;
8730 SetProcessAffinityMask(h, mask);
8731 }
8732 }
8733 }
67b915a5 8734#endif
be995c27 8735
cc1daa40
FB
8736 register_machines();
8737 machine = first_machine;
94fc95cd 8738 cpu_model = NULL;
fc01f7e7 8739 initrd_filename = NULL;
4fc5d071 8740 ram_size = 0;
313aa567 8741 vga_ram_size = VGA_RAM_SIZE;
67b915a5 8742#ifdef CONFIG_GDBSTUB
b4608c04 8743 use_gdbstub = 0;
c636bb66 8744 gdbstub_port = DEFAULT_GDBSTUB_PORT;
67b915a5 8745#endif
33e3963e 8746 snapshot = 0;
a20dd508 8747 nographic = 0;
4d3b6f6e 8748 curses = 0;
a20dd508
FB
8749 kernel_filename = NULL;
8750 kernel_cmdline = "";
c4b1fcc0 8751 cyls = heads = secs = 0;
46d4767d 8752 translation = BIOS_ATA_TRANSLATION_AUTO;
c60e08d9 8753 monitor_device = "vc";
c4b1fcc0 8754
c75a823c 8755 serial_devices[0] = "vc:80Cx24C";
8d11df9e 8756 for(i = 1; i < MAX_SERIAL_PORTS; i++)
fd5f393a 8757 serial_devices[i] = NULL;
8d11df9e 8758 serial_device_index = 0;
3b46e624 8759
c75a823c 8760 parallel_devices[0] = "vc:640x480";
6508fe59 8761 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
fd5f393a 8762 parallel_devices[i] = NULL;
6508fe59 8763 parallel_device_index = 0;
3b46e624 8764
a594cfbf 8765 usb_devices_index = 0;
3b46e624 8766
7c9d8e07 8767 nb_net_clients = 0;
e4bcb14c
TS
8768 nb_drives = 0;
8769 nb_drives_opt = 0;
8770 hda_index = -1;
7c9d8e07
FB
8771
8772 nb_nics = 0;
3b46e624 8773
26a5f13b 8774 tb_size = 0;
41bd639b
BS
8775 autostart= 1;
8776
cd6f1169 8777 optind = 1;
0824d6fc 8778 for(;;) {
cd6f1169 8779 if (optind >= argc)
0824d6fc 8780 break;
cd6f1169
FB
8781 r = argv[optind];
8782 if (r[0] != '-') {
609497ab 8783 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
cd6f1169
FB
8784 } else {
8785 const QEMUOption *popt;
8786
8787 optind++;
dff5efc8
PB
8788 /* Treat --foo the same as -foo. */
8789 if (r[1] == '-')
8790 r++;
cd6f1169
FB
8791 popt = qemu_options;
8792 for(;;) {
8793 if (!popt->name) {
5fafdf24 8794 fprintf(stderr, "%s: invalid option -- '%s'\n",
cd6f1169
FB
8795 argv[0], r);
8796 exit(1);
8797 }
8798 if (!strcmp(popt->name, r + 1))
8799 break;
8800 popt++;
8801 }
8802 if (popt->flags & HAS_ARG) {
8803 if (optind >= argc) {
8804 fprintf(stderr, "%s: option '%s' requires an argument\n",
8805 argv[0], r);
8806 exit(1);
8807 }
8808 optarg = argv[optind++];
8809 } else {
8810 optarg = NULL;
8811 }
8812
8813 switch(popt->index) {
cc1daa40
FB
8814 case QEMU_OPTION_M:
8815 machine = find_machine(optarg);
8816 if (!machine) {
8817 QEMUMachine *m;
8818 printf("Supported machines are:\n");
8819 for(m = first_machine; m != NULL; m = m->next) {
8820 printf("%-10s %s%s\n",
5fafdf24 8821 m->name, m->desc,
cc1daa40
FB
8822 m == first_machine ? " (default)" : "");
8823 }
15f82208 8824 exit(*optarg != '?');
cc1daa40
FB
8825 }
8826 break;
94fc95cd
JM
8827 case QEMU_OPTION_cpu:
8828 /* hw initialization will check this */
15f82208 8829 if (*optarg == '?') {
c732abe2
JM
8830/* XXX: implement xxx_cpu_list for targets that still miss it */
8831#if defined(cpu_list)
8832 cpu_list(stdout, &fprintf);
94fc95cd 8833#endif
15f82208 8834 exit(0);
94fc95cd
JM
8835 } else {
8836 cpu_model = optarg;
8837 }
8838 break;
cd6f1169 8839 case QEMU_OPTION_initrd:
fc01f7e7
FB
8840 initrd_filename = optarg;
8841 break;
cd6f1169 8842 case QEMU_OPTION_hda:
e4bcb14c 8843 if (cyls == 0)
609497ab 8844 hda_index = drive_add(optarg, HD_ALIAS, 0);
e4bcb14c 8845 else
609497ab 8846 hda_index = drive_add(optarg, HD_ALIAS
e4bcb14c 8847 ",cyls=%d,heads=%d,secs=%d%s",
609497ab 8848 0, cyls, heads, secs,
e4bcb14c
TS
8849 translation == BIOS_ATA_TRANSLATION_LBA ?
8850 ",trans=lba" :
8851 translation == BIOS_ATA_TRANSLATION_NONE ?
8852 ",trans=none" : "");
8853 break;
cd6f1169 8854 case QEMU_OPTION_hdb:
cc1daa40
FB
8855 case QEMU_OPTION_hdc:
8856 case QEMU_OPTION_hdd:
609497ab 8857 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
fc01f7e7 8858 break;
e4bcb14c 8859 case QEMU_OPTION_drive:
609497ab 8860 drive_add(NULL, "%s", optarg);
e4bcb14c 8861 break;
3e3d5815 8862 case QEMU_OPTION_mtdblock:
609497ab 8863 drive_add(optarg, MTD_ALIAS);
3e3d5815 8864 break;
a1bb27b1 8865 case QEMU_OPTION_sd:
609497ab 8866 drive_add(optarg, SD_ALIAS);
a1bb27b1 8867 break;
86f55663 8868 case QEMU_OPTION_pflash:
609497ab 8869 drive_add(optarg, PFLASH_ALIAS);
86f55663 8870 break;
cd6f1169 8871 case QEMU_OPTION_snapshot:
33e3963e
FB
8872 snapshot = 1;
8873 break;
cd6f1169 8874 case QEMU_OPTION_hdachs:
330d0414 8875 {
330d0414
FB
8876 const char *p;
8877 p = optarg;
8878 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
8879 if (cyls < 1 || cyls > 16383)
8880 goto chs_fail;
330d0414
FB
8881 if (*p != ',')
8882 goto chs_fail;
8883 p++;
8884 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
8885 if (heads < 1 || heads > 16)
8886 goto chs_fail;
330d0414
FB
8887 if (*p != ',')
8888 goto chs_fail;
8889 p++;
8890 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
8891 if (secs < 1 || secs > 63)
8892 goto chs_fail;
8893 if (*p == ',') {
8894 p++;
8895 if (!strcmp(p, "none"))
8896 translation = BIOS_ATA_TRANSLATION_NONE;
8897 else if (!strcmp(p, "lba"))
8898 translation = BIOS_ATA_TRANSLATION_LBA;
8899 else if (!strcmp(p, "auto"))
8900 translation = BIOS_ATA_TRANSLATION_AUTO;
8901 else
8902 goto chs_fail;
8903 } else if (*p != '\0') {
c4b1fcc0 8904 chs_fail:
46d4767d
FB
8905 fprintf(stderr, "qemu: invalid physical CHS format\n");
8906 exit(1);
c4b1fcc0 8907 }
e4bcb14c 8908 if (hda_index != -1)
609497ab
AZ
8909 snprintf(drives_opt[hda_index].opt,
8910 sizeof(drives_opt[hda_index].opt),
8911 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8912 0, cyls, heads, secs,
e4bcb14c
TS
8913 translation == BIOS_ATA_TRANSLATION_LBA ?
8914 ",trans=lba" :
8915 translation == BIOS_ATA_TRANSLATION_NONE ?
8916 ",trans=none" : "");
330d0414
FB
8917 }
8918 break;
cd6f1169 8919 case QEMU_OPTION_nographic:
a20dd508
FB
8920 nographic = 1;
8921 break;
4d3b6f6e
AZ
8922#ifdef CONFIG_CURSES
8923 case QEMU_OPTION_curses:
8924 curses = 1;
8925 break;
8926#endif
a171fe39
AZ
8927 case QEMU_OPTION_portrait:
8928 graphic_rotate = 1;
8929 break;
cd6f1169 8930 case QEMU_OPTION_kernel:
a20dd508
FB
8931 kernel_filename = optarg;
8932 break;
cd6f1169 8933 case QEMU_OPTION_append:
a20dd508 8934 kernel_cmdline = optarg;
313aa567 8935 break;
cd6f1169 8936 case QEMU_OPTION_cdrom:
609497ab 8937 drive_add(optarg, CDROM_ALIAS);
36b486bb 8938 break;
cd6f1169 8939 case QEMU_OPTION_boot:
28c5af54
JM
8940 boot_devices = optarg;
8941 /* We just do some generic consistency checks */
8942 {
8943 /* Could easily be extended to 64 devices if needed */
60fe76f3 8944 const char *p;
28c5af54
JM
8945
8946 boot_devices_bitmap = 0;
8947 for (p = boot_devices; *p != '\0'; p++) {
8948 /* Allowed boot devices are:
8949 * a b : floppy disk drives
8950 * c ... f : IDE disk drives
8951 * g ... m : machine implementation dependant drives
8952 * n ... p : network devices
8953 * It's up to each machine implementation to check
8954 * if the given boot devices match the actual hardware
8955 * implementation and firmware features.
8956 */
8957 if (*p < 'a' || *p > 'q') {
8958 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8959 exit(1);
8960 }
8961 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8962 fprintf(stderr,
8963 "Boot device '%c' was given twice\n",*p);
8964 exit(1);
8965 }
8966 boot_devices_bitmap |= 1 << (*p - 'a');
8967 }
36b486bb
FB
8968 }
8969 break;
cd6f1169 8970 case QEMU_OPTION_fda:
cd6f1169 8971 case QEMU_OPTION_fdb:
609497ab 8972 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
c45886db 8973 break;
52ca8d6a
FB
8974#ifdef TARGET_I386
8975 case QEMU_OPTION_no_fd_bootchk:
8976 fd_bootchk = 0;
8977 break;
8978#endif
7c9d8e07
FB
8979 case QEMU_OPTION_net:
8980 if (nb_net_clients >= MAX_NET_CLIENTS) {
8981 fprintf(stderr, "qemu: too many network clients\n");
c4b1fcc0
FB
8982 exit(1);
8983 }
fd5f393a 8984 net_clients[nb_net_clients] = optarg;
7c9d8e07 8985 nb_net_clients++;
702c651c 8986 break;
c7f74643
FB
8987#ifdef CONFIG_SLIRP
8988 case QEMU_OPTION_tftp:
c7f74643 8989 tftp_prefix = optarg;
9bf05444 8990 break;
47d5d01a
TS
8991 case QEMU_OPTION_bootp:
8992 bootp_filename = optarg;
8993 break;
c94c8d64 8994#ifndef _WIN32
9d728e8c
FB
8995 case QEMU_OPTION_smb:
8996 net_slirp_smb(optarg);
8997 break;
c94c8d64 8998#endif
9bf05444 8999 case QEMU_OPTION_redir:
3b46e624 9000 net_slirp_redir(optarg);
9bf05444 9001 break;
c7f74643 9002#endif
1d14ffa9 9003#ifdef HAS_AUDIO
1d14ffa9
FB
9004 case QEMU_OPTION_audio_help:
9005 AUD_help ();
9006 exit (0);
9007 break;
9008 case QEMU_OPTION_soundhw:
9009 select_soundhw (optarg);
9010 break;
9011#endif
cd6f1169 9012 case QEMU_OPTION_h:
15f82208 9013 help(0);
cd6f1169 9014 break;
00f82b8a
AJ
9015 case QEMU_OPTION_m: {
9016 uint64_t value;
9017 char *ptr;
9018
9019 value = strtoul(optarg, &ptr, 10);
9020 switch (*ptr) {
9021 case 0: case 'M': case 'm':
9022 value <<= 20;
9023 break;
9024 case 'G': case 'g':
9025 value <<= 30;
9026 break;
9027 default:
9028 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
cd6f1169
FB
9029 exit(1);
9030 }
00f82b8a
AJ
9031
9032 /* On 32-bit hosts, QEMU is limited by virtual address space */
9033 if (value > (2047 << 20)
9034#ifndef USE_KQEMU
9035 && HOST_LONG_BITS == 32
9036#endif
9037 ) {
9038 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9039 exit(1);
9040 }
9041 if (value != (uint64_t)(ram_addr_t)value) {
9042 fprintf(stderr, "qemu: ram size too large\n");
9043 exit(1);
9044 }
9045 ram_size = value;
cd6f1169 9046 break;
00f82b8a 9047 }
cd6f1169
FB
9048 case QEMU_OPTION_d:
9049 {
9050 int mask;
c7cd6a37 9051 const CPULogItem *item;
3b46e624 9052
cd6f1169
FB
9053 mask = cpu_str_to_log_mask(optarg);
9054 if (!mask) {
9055 printf("Log items (comma separated):\n");
f193c797
FB
9056 for(item = cpu_log_items; item->mask != 0; item++) {
9057 printf("%-10s %s\n", item->name, item->help);
9058 }
9059 exit(1);
cd6f1169
FB
9060 }
9061 cpu_set_log(mask);
f193c797 9062 }
cd6f1169 9063 break;
67b915a5 9064#ifdef CONFIG_GDBSTUB
cd6f1169
FB
9065 case QEMU_OPTION_s:
9066 use_gdbstub = 1;
9067 break;
9068 case QEMU_OPTION_p:
cfc3475a 9069 gdbstub_port = optarg;
cd6f1169 9070 break;
67b915a5 9071#endif
cd6f1169
FB
9072 case QEMU_OPTION_L:
9073 bios_dir = optarg;
9074 break;
1192dad8
JM
9075 case QEMU_OPTION_bios:
9076 bios_name = optarg;
9077 break;
cd6f1169 9078 case QEMU_OPTION_S:
3c07f8e8 9079 autostart = 0;
cd6f1169 9080 break;
3d11d0eb
FB
9081 case QEMU_OPTION_k:
9082 keyboard_layout = optarg;
9083 break;
ee22c2f7
FB
9084 case QEMU_OPTION_localtime:
9085 rtc_utc = 0;
9086 break;
3893c124 9087 case QEMU_OPTION_vga:
9088 select_vgahw (optarg);
1bfe856e 9089 break;
e9b137c2
FB
9090 case QEMU_OPTION_g:
9091 {
9092 const char *p;
9093 int w, h, depth;
9094 p = optarg;
9095 w = strtol(p, (char **)&p, 10);
9096 if (w <= 0) {
9097 graphic_error:
9098 fprintf(stderr, "qemu: invalid resolution or depth\n");
9099 exit(1);
9100 }
9101 if (*p != 'x')
9102 goto graphic_error;
9103 p++;
9104 h = strtol(p, (char **)&p, 10);
9105 if (h <= 0)
9106 goto graphic_error;
9107 if (*p == 'x') {
9108 p++;
9109 depth = strtol(p, (char **)&p, 10);
5fafdf24 9110 if (depth != 8 && depth != 15 && depth != 16 &&
e9b137c2
FB
9111 depth != 24 && depth != 32)
9112 goto graphic_error;
9113 } else if (*p == '\0') {
9114 depth = graphic_depth;
9115 } else {
9116 goto graphic_error;
9117 }
3b46e624 9118
e9b137c2
FB
9119 graphic_width = w;
9120 graphic_height = h;
9121 graphic_depth = depth;
9122 }
9123 break;
20d8a3ed
TS
9124 case QEMU_OPTION_echr:
9125 {
9126 char *r;
9127 term_escape_char = strtol(optarg, &r, 0);
9128 if (r == optarg)
9129 printf("Bad argument to echr\n");
9130 break;
9131 }
82c643ff 9132 case QEMU_OPTION_monitor:
fd5f393a 9133 monitor_device = optarg;
82c643ff
FB
9134 break;
9135 case QEMU_OPTION_serial:
8d11df9e
FB
9136 if (serial_device_index >= MAX_SERIAL_PORTS) {
9137 fprintf(stderr, "qemu: too many serial ports\n");
9138 exit(1);
9139 }
fd5f393a 9140 serial_devices[serial_device_index] = optarg;
8d11df9e 9141 serial_device_index++;
82c643ff 9142 break;
6508fe59
FB
9143 case QEMU_OPTION_parallel:
9144 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9145 fprintf(stderr, "qemu: too many parallel ports\n");
9146 exit(1);
9147 }
fd5f393a 9148 parallel_devices[parallel_device_index] = optarg;
6508fe59
FB
9149 parallel_device_index++;
9150 break;
d63d307f
FB
9151 case QEMU_OPTION_loadvm:
9152 loadvm = optarg;
9153 break;
9154 case QEMU_OPTION_full_screen:
9155 full_screen = 1;
9156 break;
667accab 9157#ifdef CONFIG_SDL
43523e93
TS
9158 case QEMU_OPTION_no_frame:
9159 no_frame = 1;
9160 break;
3780e197
TS
9161 case QEMU_OPTION_alt_grab:
9162 alt_grab = 1;
9163 break;
667accab
TS
9164 case QEMU_OPTION_no_quit:
9165 no_quit = 1;
9166 break;
9167#endif
f7cce898 9168 case QEMU_OPTION_pidfile:
93815bc2 9169 pid_file = optarg;
f7cce898 9170 break;
a09db21f
FB
9171#ifdef TARGET_I386
9172 case QEMU_OPTION_win2k_hack:
9173 win2k_install_hack = 1;
9174 break;
9175#endif
d993e026
FB
9176#ifdef USE_KQEMU
9177 case QEMU_OPTION_no_kqemu:
9178 kqemu_allowed = 0;
9179 break;
89bfc105
FB
9180 case QEMU_OPTION_kernel_kqemu:
9181 kqemu_allowed = 2;
9182 break;
d993e026 9183#endif
bb36d470
FB
9184 case QEMU_OPTION_usb:
9185 usb_enabled = 1;
9186 break;
a594cfbf
FB
9187 case QEMU_OPTION_usbdevice:
9188 usb_enabled = 1;
0d92ed30 9189 if (usb_devices_index >= MAX_USB_CMDLINE) {
a594cfbf
FB
9190 fprintf(stderr, "Too many USB devices\n");
9191 exit(1);
9192 }
fd5f393a 9193 usb_devices[usb_devices_index] = optarg;
a594cfbf
FB
9194 usb_devices_index++;
9195 break;
6a00d601
FB
9196 case QEMU_OPTION_smp:
9197 smp_cpus = atoi(optarg);
ba3c64fb 9198 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6a00d601
FB
9199 fprintf(stderr, "Invalid number of CPUs\n");
9200 exit(1);
9201 }
9202 break;
24236869 9203 case QEMU_OPTION_vnc:
73fc9742 9204 vnc_display = optarg;
24236869 9205 break;
6515b203
FB
9206 case QEMU_OPTION_no_acpi:
9207 acpi_enabled = 0;
9208 break;
d1beab82
FB
9209 case QEMU_OPTION_no_reboot:
9210 no_reboot = 1;
9211 break;
b2f76161
AJ
9212 case QEMU_OPTION_no_shutdown:
9213 no_shutdown = 1;
9214 break;
9467cd46
AZ
9215 case QEMU_OPTION_show_cursor:
9216 cursor_hide = 0;
9217 break;
8fcb1b90
BS
9218 case QEMU_OPTION_uuid:
9219 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
9220 fprintf(stderr, "Fail to parse UUID string."
9221 " Wrong format.\n");
9222 exit(1);
9223 }
9224 break;
71e3ceb8
TS
9225 case QEMU_OPTION_daemonize:
9226 daemonize = 1;
9227 break;
9ae02555
TS
9228 case QEMU_OPTION_option_rom:
9229 if (nb_option_roms >= MAX_OPTION_ROMS) {
9230 fprintf(stderr, "Too many option ROMs\n");
9231 exit(1);
9232 }
9233 option_rom[nb_option_roms] = optarg;
9234 nb_option_roms++;
9235 break;
8e71621f
PB
9236 case QEMU_OPTION_semihosting:
9237 semihosting_enabled = 1;
9238 break;
c35734b2
TS
9239 case QEMU_OPTION_name:
9240 qemu_name = optarg;
9241 break;
66508601
BS
9242#ifdef TARGET_SPARC
9243 case QEMU_OPTION_prom_env:
9244 if (nb_prom_envs >= MAX_PROM_ENVS) {
9245 fprintf(stderr, "Too many prom variables\n");
9246 exit(1);
9247 }
9248 prom_envs[nb_prom_envs] = optarg;
9249 nb_prom_envs++;
9250 break;
2b8f2d41
AZ
9251#endif
9252#ifdef TARGET_ARM
9253 case QEMU_OPTION_old_param:
9254 old_param = 1;
05ebd537 9255 break;
66508601 9256#endif
f3dcfada
TS
9257 case QEMU_OPTION_clock:
9258 configure_alarms(optarg);
9259 break;
7e0af5d0
FB
9260 case QEMU_OPTION_startdate:
9261 {
9262 struct tm tm;
f6503059 9263 time_t rtc_start_date;
7e0af5d0 9264 if (!strcmp(optarg, "now")) {
f6503059 9265 rtc_date_offset = -1;
7e0af5d0
FB
9266 } else {
9267 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9268 &tm.tm_year,
9269 &tm.tm_mon,
9270 &tm.tm_mday,
9271 &tm.tm_hour,
9272 &tm.tm_min,
9273 &tm.tm_sec) == 6) {
9274 /* OK */
9275 } else if (sscanf(optarg, "%d-%d-%d",
9276 &tm.tm_year,
9277 &tm.tm_mon,
9278 &tm.tm_mday) == 3) {
9279 tm.tm_hour = 0;
9280 tm.tm_min = 0;
9281 tm.tm_sec = 0;
9282 } else {
9283 goto date_fail;
9284 }
9285 tm.tm_year -= 1900;
9286 tm.tm_mon--;
3c6b2088 9287 rtc_start_date = mktimegm(&tm);
7e0af5d0
FB
9288 if (rtc_start_date == -1) {
9289 date_fail:
9290 fprintf(stderr, "Invalid date format. Valid format are:\n"
9291 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9292 exit(1);
9293 }
f6503059 9294 rtc_date_offset = time(NULL) - rtc_start_date;
7e0af5d0
FB
9295 }
9296 }
9297 break;
26a5f13b
FB
9298 case QEMU_OPTION_tb_size:
9299 tb_size = strtol(optarg, NULL, 0);
9300 if (tb_size < 0)
9301 tb_size = 0;
9302 break;
2e70f6ef
PB
9303 case QEMU_OPTION_icount:
9304 use_icount = 1;
9305 if (strcmp(optarg, "auto") == 0) {
9306 icount_time_shift = -1;
9307 } else {
9308 icount_time_shift = strtol(optarg, NULL, 0);
9309 }
9310 break;
cd6f1169 9311 }
0824d6fc
FB
9312 }
9313 }
330d0414 9314
bc0129d9
AL
9315 if (nographic) {
9316 if (serial_device_index == 0)
9317 serial_devices[0] = "stdio";
9318 if (parallel_device_index == 0)
9319 parallel_devices[0] = "null";
9320 if (strncmp(monitor_device, "vc", 2) == 0)
9321 monitor_device = "stdio";
9322 }
9323
71e3ceb8 9324#ifndef _WIN32
71e3ceb8
TS
9325 if (daemonize) {
9326 pid_t pid;
9327
9328 if (pipe(fds) == -1)
9329 exit(1);
9330
9331 pid = fork();
9332 if (pid > 0) {
9333 uint8_t status;
9334 ssize_t len;
9335
9336 close(fds[1]);
9337
9338 again:
93815bc2
TS
9339 len = read(fds[0], &status, 1);
9340 if (len == -1 && (errno == EINTR))
9341 goto again;
9342
9343 if (len != 1)
9344 exit(1);
9345 else if (status == 1) {
9346 fprintf(stderr, "Could not acquire pidfile\n");
9347 exit(1);
9348 } else
9349 exit(0);
71e3ceb8 9350 } else if (pid < 0)
93815bc2 9351 exit(1);
71e3ceb8
TS
9352
9353 setsid();
9354
9355 pid = fork();
9356 if (pid > 0)
9357 exit(0);
9358 else if (pid < 0)
9359 exit(1);
9360
9361 umask(027);
71e3ceb8
TS
9362
9363 signal(SIGTSTP, SIG_IGN);
9364 signal(SIGTTOU, SIG_IGN);
9365 signal(SIGTTIN, SIG_IGN);
9366 }
9367#endif
9368
aa26bb2d 9369 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
9370 if (daemonize) {
9371 uint8_t status = 1;
9372 write(fds[1], &status, 1);
9373 } else
9374 fprintf(stderr, "Could not acquire pid file\n");
9375 exit(1);
9376 }
9377
ff3fbb30
FB
9378#ifdef USE_KQEMU
9379 if (smp_cpus > 1)
9380 kqemu_allowed = 0;
9381#endif
a20dd508 9382 linux_boot = (kernel_filename != NULL);
7317b8ca 9383 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6c41b272 9384
28c5af54 9385 if (!linux_boot && net_boot == 0 &&
f88e4b91 9386 !machine->nodisk_ok && nb_drives_opt == 0)
15f82208 9387 help(1);
0824d6fc 9388
f8d39c01
TS
9389 if (!linux_boot && *kernel_cmdline != '\0') {
9390 fprintf(stderr, "-append only allowed with -kernel option\n");
9391 exit(1);
9392 }
9393
9394 if (!linux_boot && initrd_filename != NULL) {
9395 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9396 exit(1);
9397 }
9398
96d30e48 9399 /* boot to floppy or the default cd if no hard disk defined yet */
28c5af54 9400 if (!boot_devices[0]) {
e4bcb14c 9401 boot_devices = "cad";
96d30e48 9402 }
b118d61e 9403 setvbuf(stdout, NULL, _IOLBF, 0);
3b46e624 9404
634fce96
PB
9405 init_timers();
9406 init_timer_alarm();
2e70f6ef
PB
9407 if (use_icount && icount_time_shift < 0) {
9408 use_icount = 2;
9409 /* 125MIPS seems a reasonable initial guess at the guest speed.
9410 It will be corrected fairly quickly anyway. */
9411 icount_time_shift = 3;
9412 init_icount_adjust();
9413 }
634fce96 9414
fd1dff4b
FB
9415#ifdef _WIN32
9416 socket_init();
9417#endif
9418
7c9d8e07
FB
9419 /* init network clients */
9420 if (nb_net_clients == 0) {
9421 /* if no clients, we use a default config */
f441b28b
AL
9422 net_clients[nb_net_clients++] = "nic";
9423#ifdef CONFIG_SLIRP
9424 net_clients[nb_net_clients++] = "user";
9425#endif
c20709aa
FB
9426 }
9427
7c9d8e07 9428 for(i = 0;i < nb_net_clients; i++) {
9ad97e65 9429 if (net_client_parse(net_clients[i]) < 0)
7c9d8e07 9430 exit(1);
702c651c 9431 }
833c7174
BS
9432 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9433 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9434 continue;
9ad97e65
AZ
9435 if (vlan->nb_guest_devs == 0)
9436 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
833c7174
BS
9437 if (vlan->nb_host_devs == 0)
9438 fprintf(stderr,
9439 "Warning: vlan %d is not connected to host network\n",
9440 vlan->id);
9441 }
f1510b2c 9442
eec85c2a 9443#ifdef TARGET_I386
ed494d87 9444 /* XXX: this should be moved in the PC machine instantiation code */
28c5af54
JM
9445 if (net_boot != 0) {
9446 int netroms = 0;
9447 for (i = 0; i < nb_nics && i < 4; i++) {
eec85c2a
TS
9448 const char *model = nd_table[i].model;
9449 char buf[1024];
28c5af54
JM
9450 if (net_boot & (1 << i)) {
9451 if (model == NULL)
9452 model = "ne2k_pci";
9453 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9454 if (get_image_size(buf) > 0) {
9455 if (nb_option_roms >= MAX_OPTION_ROMS) {
9456 fprintf(stderr, "Too many option ROMs\n");
9457 exit(1);
9458 }
9459 option_rom[nb_option_roms] = strdup(buf);
9460 nb_option_roms++;
9461 netroms++;
9462 }
9463 }
eec85c2a 9464 }
28c5af54 9465 if (netroms == 0) {
eec85c2a
TS
9466 fprintf(stderr, "No valid PXE rom found for network device\n");
9467 exit(1);
9468 }
eec85c2a
TS
9469 }
9470#endif
9471
0824d6fc 9472 /* init the memory */
7fb4fdcf
AZ
9473 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9474
9475 if (machine->ram_require & RAMSIZE_FIXED) {
9476 if (ram_size > 0) {
9477 if (ram_size < phys_ram_size) {
cd940061
AJ
9478 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9479 machine->name, (unsigned long long) phys_ram_size);
7fb4fdcf
AZ
9480 exit(-1);
9481 }
9482
9483 phys_ram_size = ram_size;
9484 } else
9485 ram_size = phys_ram_size;
9486 } else {
4fc5d071 9487 if (ram_size == 0)
7fb4fdcf
AZ
9488 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9489
9490 phys_ram_size += ram_size;
9491 }
9ae02555 9492
d993e026 9493 phys_ram_base = qemu_vmalloc(phys_ram_size);
7f7f9873
FB
9494 if (!phys_ram_base) {
9495 fprintf(stderr, "Could not allocate physical memory\n");
0824d6fc
FB
9496 exit(1);
9497 }
9498
26a5f13b
FB
9499 /* init the dynamic translator */
9500 cpu_exec_init_all(tb_size * 1024 * 1024);
9501
5905b2e5 9502 bdrv_init();
c4b1fcc0 9503
e4bcb14c 9504 /* we always create the cdrom drive, even if no disk is there */
c4b1fcc0 9505
e4bcb14c 9506 if (nb_drives_opt < MAX_DRIVES)
609497ab 9507 drive_add(NULL, CDROM_ALIAS);
c4b1fcc0 9508
9d413d1d 9509 /* we always create at least one floppy */
33e3963e 9510
e4bcb14c 9511 if (nb_drives_opt < MAX_DRIVES)
609497ab 9512 drive_add(NULL, FD_ALIAS, 0);
86f55663 9513
9d413d1d
AZ
9514 /* we always create one sd slot, even if no card is in it */
9515
9516 if (nb_drives_opt < MAX_DRIVES)
609497ab 9517 drive_add(NULL, SD_ALIAS);
9d413d1d 9518
e4bcb14c
TS
9519 /* open the virtual block devices */
9520
9521 for(i = 0; i < nb_drives_opt; i++)
609497ab 9522 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
e4bcb14c 9523 exit(1);
3e3d5815 9524
c88676f8 9525 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
475e4277 9526 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
8a7ddc38 9527
313aa567 9528 /* terminal init */
740733bb 9529 memset(&display_state, 0, sizeof(display_state));
a20dd508 9530 if (nographic) {
4d3b6f6e
AZ
9531 if (curses) {
9532 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9533 exit(1);
9534 }
2ff89790
TS
9535 /* nearly nothing to do */
9536 dumb_display_init(ds);
73fc9742 9537 } else if (vnc_display != NULL) {
71cab5ca
TS
9538 vnc_display_init(ds);
9539 if (vnc_display_open(ds, vnc_display) < 0)
9540 exit(1);
4d3b6f6e
AZ
9541 } else
9542#if defined(CONFIG_CURSES)
9543 if (curses) {
9544 curses_display_init(ds, full_screen);
9545 } else
9546#endif
9547 {
5b0753e0 9548#if defined(CONFIG_SDL)
43523e93 9549 sdl_display_init(ds, full_screen, no_frame);
5b0753e0
FB
9550#elif defined(CONFIG_COCOA)
9551 cocoa_display_init(ds, full_screen);
67276f53
PB
9552#else
9553 dumb_display_init(ds);
313aa567
FB
9554#endif
9555 }
0824d6fc 9556
5b08fc10
AL
9557#ifndef _WIN32
9558 /* must be after terminal init, SDL library changes signal handlers */
9559 termsig_setup();
9560#endif
9561
20d8a3ed
TS
9562 /* Maintain compatibility with multiple stdio monitors */
9563 if (!strcmp(monitor_device,"stdio")) {
9564 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
fd5f393a
PB
9565 const char *devname = serial_devices[i];
9566 if (devname && !strcmp(devname,"mon:stdio")) {
9567 monitor_device = NULL;
20d8a3ed 9568 break;
fd5f393a
PB
9569 } else if (devname && !strcmp(devname,"stdio")) {
9570 monitor_device = NULL;
9571 serial_devices[i] = "mon:stdio";
20d8a3ed
TS
9572 break;
9573 }
9574 }
9575 }
fd5f393a 9576 if (monitor_device) {
20d8a3ed
TS
9577 monitor_hd = qemu_chr_open(monitor_device);
9578 if (!monitor_hd) {
9579 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9580 exit(1);
9581 }
9582 monitor_init(monitor_hd, !nographic);
82c643ff 9583 }
82c643ff 9584
8d11df9e 9585 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
c03b0f0f 9586 const char *devname = serial_devices[i];
fd5f393a 9587 if (devname && strcmp(devname, "none")) {
c03b0f0f 9588 serial_hds[i] = qemu_chr_open(devname);
8d11df9e 9589 if (!serial_hds[i]) {
5fafdf24 9590 fprintf(stderr, "qemu: could not open serial device '%s'\n",
c03b0f0f 9591 devname);
8d11df9e
FB
9592 exit(1);
9593 }
af3a9031 9594 if (strstart(devname, "vc", 0))
7ba1260a 9595 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8d11df9e 9596 }
82c643ff 9597 }
82c643ff 9598
6508fe59 9599 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
c03b0f0f 9600 const char *devname = parallel_devices[i];
fd5f393a 9601 if (devname && strcmp(devname, "none")) {
c03b0f0f 9602 parallel_hds[i] = qemu_chr_open(devname);
6508fe59 9603 if (!parallel_hds[i]) {
5fafdf24 9604 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
c03b0f0f 9605 devname);
6508fe59
FB
9606 exit(1);
9607 }
af3a9031 9608 if (strstart(devname, "vc", 0))
7ba1260a 9609 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6508fe59
FB
9610 }
9611 }
9612
b881c2c6 9613 machine->init(ram_size, vga_ram_size, boot_devices, ds,
94fc95cd 9614 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
73332e5c 9615
0d92ed30
PB
9616 /* init USB devices */
9617 if (usb_enabled) {
9618 for(i = 0; i < usb_devices_index; i++) {
9619 if (usb_device_add(usb_devices[i]) < 0) {
9620 fprintf(stderr, "Warning: could not add USB device %s\n",
9621 usb_devices[i]);
9622 }
9623 }
9624 }
9625
740733bb
TS
9626 if (display_state.dpy_refresh) {
9627 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9628 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9629 }
7f7f9873 9630
67b915a5 9631#ifdef CONFIG_GDBSTUB
b4608c04 9632 if (use_gdbstub) {
c636bb66
FB
9633 /* XXX: use standard host:port notation and modify options
9634 accordingly. */
cfc3475a
PB
9635 if (gdbserver_start(gdbstub_port) < 0) {
9636 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
c636bb66 9637 gdbstub_port);
8a7ddc38 9638 exit(1);
8a7ddc38 9639 }
45669e00 9640 }
67b915a5 9641#endif
45669e00 9642
d63d307f 9643 if (loadvm)
faea38e7 9644 do_loadvm(loadvm);
d63d307f 9645
67b915a5 9646 {
5905b2e5 9647 /* XXX: simplify init */
83ab7950 9648 read_passwords();
3c07f8e8 9649 if (autostart) {
5905b2e5
FB
9650 vm_start();
9651 }
0824d6fc 9652 }
ffd843bc 9653
71e3ceb8
TS
9654 if (daemonize) {
9655 uint8_t status = 0;
9656 ssize_t len;
9657 int fd;
9658
9659 again1:
9660 len = write(fds[1], &status, 1);
9661 if (len == -1 && (errno == EINTR))
9662 goto again1;
9663
9664 if (len != 1)
9665 exit(1);
9666
bd54b863 9667 chdir("/");
aeb30be6 9668 TFR(fd = open("/dev/null", O_RDWR));
71e3ceb8
TS
9669 if (fd == -1)
9670 exit(1);
9671
9672 dup2(fd, 0);
9673 dup2(fd, 1);
9674 dup2(fd, 2);
9675
9676 close(fd);
9677 }
9678
8a7ddc38 9679 main_loop();
40c3bac3 9680 quit_timers();
b46a8906 9681
7d294b61 9682#if !defined(_WIN32)
b46a8906
TS
9683 /* close network clients */
9684 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9685 VLANClientState *vc;
9686
7d294b61 9687 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
b46a8906
TS
9688 if (vc->fd_read == tap_receive) {
9689 char ifname[64];
9690 TAPState *s = vc->opaque;
9691
9692 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9693 s->down_script[0])
9694 launch_script(s->down_script, ifname, s->fd);
9695 }
8a16d273
TS
9696#if defined(CONFIG_VDE)
9697 if (vc->fd_read == vde_from_qemu) {
9698 VDEState *s = vc->opaque;
9699 vde_close(s->vde);
9700 }
9701#endif
4fddf62a 9702 }
7d294b61
TS
9703 }
9704#endif
0824d6fc
FB
9705 return 0;
9706}