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