]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
Hack to keep wine happy, by Alexander Graf.
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
0824d6fc 3 *
84f2e8ef 4 * Copyright (c) 2003-2007 Fabrice Bellard
0824d6fc 5 *
1df912cf
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
0824d6fc 23 */
67b915a5
FB
24#include "vl.h"
25
0824d6fc 26#include <unistd.h>
0824d6fc
FB
27#include <fcntl.h>
28#include <signal.h>
29#include <time.h>
0824d6fc 30#include <errno.h>
67b915a5 31#include <sys/time.h>
c88676f8 32#include <zlib.h>
67b915a5
FB
33
34#ifndef _WIN32
35#include <sys/times.h>
f1510b2c 36#include <sys/wait.h>
67b915a5
FB
37#include <termios.h>
38#include <sys/poll.h>
39#include <sys/mman.h>
f1510b2c
FB
40#include <sys/ioctl.h>
41#include <sys/socket.h>
c94c8d64 42#include <netinet/in.h>
9d728e8c 43#include <dirent.h>
7c9d8e07 44#include <netdb.h>
7d3505c5
FB
45#ifdef _BSD
46#include <sys/stat.h>
83fb7adf 47#ifndef __APPLE__
7d3505c5 48#include <libutil.h>
83fb7adf 49#endif
7d3505c5 50#else
ec530c81 51#ifndef __sun__
f1510b2c
FB
52#include <linux/if.h>
53#include <linux/if_tun.h>
7d3505c5
FB
54#include <pty.h>
55#include <malloc.h>
fd872598 56#include <linux/rtc.h>
e57a8c0e 57#include <linux/ppdev.h>
5867c88a 58#include <linux/parport.h>
d5d10bc3
TS
59#else
60#include <sys/stat.h>
61#include <sys/ethernet.h>
62#include <sys/sockio.h>
63#include <arpa/inet.h>
64#include <netinet/arp.h>
65#include <netinet/in.h>
66#include <netinet/in_systm.h>
67#include <netinet/ip.h>
68#include <netinet/ip_icmp.h> // must come after ip.h
69#include <netinet/udp.h>
70#include <netinet/tcp.h>
71#include <net/if.h>
72#include <syslog.h>
73#include <stropts.h>
67b915a5 74#endif
7d3505c5 75#endif
ec530c81 76#endif
67b915a5 77
c20709aa
FB
78#if defined(CONFIG_SLIRP)
79#include "libslirp.h"
80#endif
81
67b915a5 82#ifdef _WIN32
7d3505c5 83#include <malloc.h>
67b915a5
FB
84#include <sys/timeb.h>
85#include <windows.h>
86#define getopt_long_only getopt_long
87#define memalign(align, size) malloc(size)
88#endif
89
6ca957f0
FB
90#include "qemu_socket.h"
91
73332e5c 92#ifdef CONFIG_SDL
96bcd4f8 93#ifdef __APPLE__
83fb7adf 94#include <SDL/SDL.h>
96bcd4f8 95#endif
73332e5c 96#endif /* CONFIG_SDL */
0824d6fc 97
5b0753e0
FB
98#ifdef CONFIG_COCOA
99#undef main
100#define main qemu_main
101#endif /* CONFIG_COCOA */
102
0824d6fc 103#include "disas.h"
fc01f7e7 104
8a7ddc38 105#include "exec-all.h"
0824d6fc 106
5a67135a 107#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
a14d6c8c
PB
108#ifdef __sun__
109#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110#else
111#define SMBD_COMMAND "/usr/sbin/smbd"
112#endif
f1510b2c 113
0824d6fc 114//#define DEBUG_UNUSED_IOPORT
fd872598 115//#define DEBUG_IOPORT
330d0414 116
bb551faa 117#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
7916e224 118
77d4bc34
FB
119#ifdef TARGET_PPC
120#define DEFAULT_RAM_SIZE 144
121#else
1bfe856e 122#define DEFAULT_RAM_SIZE 128
77d4bc34 123#endif
8a7ddc38
FB
124/* in ms */
125#define GUI_REFRESH_INTERVAL 30
313aa567 126
0d92ed30
PB
127/* Max number of USB devices that can be specified on the commandline. */
128#define MAX_USB_CMDLINE 8
129
7dea1da4
FB
130/* XXX: use a two level table to limit memory usage */
131#define MAX_IOPORTS 65536
0824d6fc 132
80cabfad 133const char *bios_dir = CONFIG_QEMU_SHAREDIR;
0824d6fc 134char phys_ram_file[1024];
c4b1fcc0 135void *ioport_opaque[MAX_IOPORTS];
fc01f7e7
FB
136IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
faea38e7
FB
138/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
86f55663 141BlockDriverState *pflash_table[MAX_PFLASH];
a1bb27b1 142BlockDriverState *sd_bdrv;
3e3d5815 143BlockDriverState *mtd_bdrv;
faea38e7
FB
144/* point to the block driver where the snapshots are managed */
145BlockDriverState *bs_snapshots;
313aa567
FB
146int vga_ram_size;
147static DisplayState display_state;
a20dd508 148int nographic;
3d11d0eb 149const char* keyboard_layout = NULL;
313aa567 150int64_t ticks_per_sec;
36b486bb 151int boot_device = 'c';
0ced6589 152int ram_size;
80cabfad 153int pit_min_timer_count = 0;
c4b1fcc0 154int nb_nics;
7c9d8e07 155NICInfo nd_table[MAX_NICS];
8a7ddc38 156int vm_running;
ee22c2f7 157int rtc_utc = 1;
1bfe856e 158int cirrus_vga_enabled = 1;
d34cab9f 159int vmsvga_enabled = 0;
d827220b
FB
160#ifdef TARGET_SPARC
161int graphic_width = 1024;
162int graphic_height = 768;
eee0b836 163int graphic_depth = 8;
d827220b 164#else
1bfe856e
FB
165int graphic_width = 800;
166int graphic_height = 600;
e9b137c2 167int graphic_depth = 15;
eee0b836 168#endif
d63d307f 169int full_screen = 0;
43523e93 170int no_frame = 0;
667accab 171int no_quit = 0;
8d11df9e 172CharDriverState *serial_hds[MAX_SERIAL_PORTS];
6508fe59 173CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
a09db21f
FB
174#ifdef TARGET_I386
175int win2k_install_hack = 0;
176#endif
bb36d470 177int usb_enabled = 0;
7c9d8e07 178static VLANState *first_vlan;
6a00d601 179int smp_cpus = 1;
73fc9742 180const char *vnc_display;
d3e9db93 181#if defined(TARGET_SPARC)
ba3c64fb 182#define MAX_CPUS 16
d3e9db93
FB
183#elif defined(TARGET_I386)
184#define MAX_CPUS 255
ba3c64fb 185#else
d3e9db93 186#define MAX_CPUS 1
ba3c64fb 187#endif
6515b203 188int acpi_enabled = 1;
52ca8d6a 189int fd_bootchk = 1;
d1beab82 190int no_reboot = 0;
9467cd46 191int cursor_hide = 1;
a171fe39 192int graphic_rotate = 0;
71e3ceb8 193int daemonize = 0;
9ae02555
TS
194const char *option_rom[MAX_OPTION_ROMS];
195int nb_option_roms;
8e71621f 196int semihosting_enabled = 0;
3c07f8e8 197int autostart = 1;
c35734b2 198const char *qemu_name;
3780e197 199int alt_grab = 0;
66508601
BS
200#ifdef TARGET_SPARC
201unsigned int nb_prom_envs = 0;
202const char *prom_envs[MAX_PROM_ENVS];
203#endif
0824d6fc
FB
204
205/***********************************************************/
26aa7d72
FB
206/* x86 ISA bus support */
207
208target_phys_addr_t isa_mem_base = 0;
3de388f6 209PicState2 *isa_pic;
0824d6fc 210
c4b1fcc0 211uint32_t default_ioport_readb(void *opaque, uint32_t address)
0824d6fc
FB
212{
213#ifdef DEBUG_UNUSED_IOPORT
1196be37 214 fprintf(stderr, "unused inb: port=0x%04x\n", address);
0824d6fc 215#endif
fc01f7e7 216 return 0xff;
0824d6fc
FB
217}
218
c4b1fcc0 219void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
0824d6fc
FB
220{
221#ifdef DEBUG_UNUSED_IOPORT
1196be37 222 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
0824d6fc
FB
223#endif
224}
225
226/* default is to make two byte accesses */
c4b1fcc0 227uint32_t default_ioport_readw(void *opaque, uint32_t address)
0824d6fc
FB
228{
229 uint32_t data;
db45c29a
FB
230 data = ioport_read_table[0][address](ioport_opaque[address], address);
231 address = (address + 1) & (MAX_IOPORTS - 1);
232 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
0824d6fc
FB
233 return data;
234}
235
c4b1fcc0 236void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
0824d6fc 237{
db45c29a
FB
238 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
239 address = (address + 1) & (MAX_IOPORTS - 1);
240 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
0824d6fc
FB
241}
242
c4b1fcc0 243uint32_t default_ioport_readl(void *opaque, uint32_t address)
0824d6fc 244{
fc01f7e7 245#ifdef DEBUG_UNUSED_IOPORT
1196be37 246 fprintf(stderr, "unused inl: port=0x%04x\n", address);
fc01f7e7
FB
247#endif
248 return 0xffffffff;
0824d6fc
FB
249}
250
c4b1fcc0 251void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
0824d6fc 252{
fc01f7e7 253#ifdef DEBUG_UNUSED_IOPORT
1196be37 254 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
fc01f7e7 255#endif
0824d6fc
FB
256}
257
fc01f7e7 258void init_ioports(void)
0824d6fc
FB
259{
260 int i;
261
fc01f7e7
FB
262 for(i = 0; i < MAX_IOPORTS; i++) {
263 ioport_read_table[0][i] = default_ioport_readb;
264 ioport_write_table[0][i] = default_ioport_writeb;
265 ioport_read_table[1][i] = default_ioport_readw;
266 ioport_write_table[1][i] = default_ioport_writew;
267 ioport_read_table[2][i] = default_ioport_readl;
268 ioport_write_table[2][i] = default_ioport_writel;
269 }
0824d6fc
FB
270}
271
fc01f7e7 272/* size is the word size in byte */
c4b1fcc0
FB
273int register_ioport_read(int start, int length, int size,
274 IOPortReadFunc *func, void *opaque)
f1510b2c 275{
fc01f7e7 276 int i, bsize;
f1510b2c 277
c4b1fcc0 278 if (size == 1) {
fc01f7e7 279 bsize = 0;
c4b1fcc0 280 } else if (size == 2) {
fc01f7e7 281 bsize = 1;
c4b1fcc0 282 } else if (size == 4) {
fc01f7e7 283 bsize = 2;
c4b1fcc0
FB
284 } else {
285 hw_error("register_ioport_read: invalid size");
fc01f7e7 286 return -1;
c4b1fcc0
FB
287 }
288 for(i = start; i < start + length; i += size) {
fc01f7e7 289 ioport_read_table[bsize][i] = func;
c4b1fcc0
FB
290 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
291 hw_error("register_ioport_read: invalid opaque");
292 ioport_opaque[i] = opaque;
293 }
f1510b2c
FB
294 return 0;
295}
296
fc01f7e7 297/* size is the word size in byte */
c4b1fcc0
FB
298int register_ioport_write(int start, int length, int size,
299 IOPortWriteFunc *func, void *opaque)
f1510b2c 300{
fc01f7e7 301 int i, bsize;
f1510b2c 302
c4b1fcc0 303 if (size == 1) {
fc01f7e7 304 bsize = 0;
c4b1fcc0 305 } else if (size == 2) {
fc01f7e7 306 bsize = 1;
c4b1fcc0 307 } else if (size == 4) {
fc01f7e7 308 bsize = 2;
c4b1fcc0
FB
309 } else {
310 hw_error("register_ioport_write: invalid size");
fc01f7e7 311 return -1;
c4b1fcc0
FB
312 }
313 for(i = start; i < start + length; i += size) {
fc01f7e7 314 ioport_write_table[bsize][i] = func;
c4b1fcc0 315 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
52f61fde 316 hw_error("register_ioport_write: invalid opaque");
c4b1fcc0
FB
317 ioport_opaque[i] = opaque;
318 }
f1510b2c
FB
319 return 0;
320}
321
69b91039
FB
322void isa_unassign_ioport(int start, int length)
323{
324 int i;
325
326 for(i = start; i < start + length; i++) {
327 ioport_read_table[0][i] = default_ioport_readb;
328 ioport_read_table[1][i] = default_ioport_readw;
329 ioport_read_table[2][i] = default_ioport_readl;
330
331 ioport_write_table[0][i] = default_ioport_writeb;
332 ioport_write_table[1][i] = default_ioport_writew;
333 ioport_write_table[2][i] = default_ioport_writel;
334 }
335}
336
20f32282
FB
337/***********************************************************/
338
c45886db 339void cpu_outb(CPUState *env, int addr, int val)
0824d6fc 340{
fd872598
FB
341#ifdef DEBUG_IOPORT
342 if (loglevel & CPU_LOG_IOPORT)
343 fprintf(logfile, "outb: %04x %02x\n", addr, val);
344#endif
c4b1fcc0 345 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
346#ifdef USE_KQEMU
347 if (env)
348 env->last_io_time = cpu_get_time_fast();
349#endif
0824d6fc
FB
350}
351
c45886db 352void cpu_outw(CPUState *env, int addr, int val)
0824d6fc 353{
fd872598
FB
354#ifdef DEBUG_IOPORT
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "outw: %04x %04x\n", addr, val);
357#endif
c4b1fcc0 358 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
359#ifdef USE_KQEMU
360 if (env)
361 env->last_io_time = cpu_get_time_fast();
362#endif
0824d6fc
FB
363}
364
c45886db 365void cpu_outl(CPUState *env, int addr, int val)
0824d6fc 366{
fd872598
FB
367#ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outl: %04x %08x\n", addr, val);
370#endif
c4b1fcc0 371 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
89bfc105
FB
372#ifdef USE_KQEMU
373 if (env)
374 env->last_io_time = cpu_get_time_fast();
375#endif
0824d6fc
FB
376}
377
c45886db 378int cpu_inb(CPUState *env, int addr)
0824d6fc 379{
fd872598 380 int val;
fd872598
FB
381 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
382#ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inb : %04x %02x\n", addr, val);
89bfc105
FB
385#endif
386#ifdef USE_KQEMU
387 if (env)
388 env->last_io_time = cpu_get_time_fast();
fd872598
FB
389#endif
390 return val;
0824d6fc
FB
391}
392
c45886db 393int cpu_inw(CPUState *env, int addr)
0824d6fc 394{
fd872598 395 int val;
fd872598
FB
396 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
397#ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inw : %04x %04x\n", addr, val);
89bfc105
FB
400#endif
401#ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
fd872598
FB
404#endif
405 return val;
0824d6fc
FB
406}
407
c45886db 408int cpu_inl(CPUState *env, int addr)
0824d6fc 409{
fd872598 410 int val;
fd872598
FB
411 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
412#ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inl : %04x %08x\n", addr, val);
89bfc105
FB
415#endif
416#ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
fd872598
FB
419#endif
420 return val;
0824d6fc
FB
421}
422
423/***********************************************************/
0824d6fc
FB
424void hw_error(const char *fmt, ...)
425{
426 va_list ap;
6a00d601 427 CPUState *env;
0824d6fc
FB
428
429 va_start(ap, fmt);
430 fprintf(stderr, "qemu: hardware error: ");
431 vfprintf(stderr, fmt, ap);
432 fprintf(stderr, "\n");
6a00d601
FB
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
0824d6fc 435#ifdef TARGET_I386
6a00d601 436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
c45886db 437#else
6a00d601 438 cpu_dump_state(env, stderr, fprintf, 0);
0824d6fc 439#endif
6a00d601 440 }
0824d6fc
FB
441 va_end(ap);
442 abort();
443}
444
63066f4f
FB
445/***********************************************************/
446/* keyboard/mouse */
447
448static QEMUPutKBDEvent *qemu_put_kbd_event;
449static void *qemu_put_kbd_event_opaque;
455204eb
TS
450static QEMUPutMouseEntry *qemu_put_mouse_event_head;
451static QEMUPutMouseEntry *qemu_put_mouse_event_current;
63066f4f
FB
452
453void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454{
455 qemu_put_kbd_event_opaque = opaque;
456 qemu_put_kbd_event = func;
457}
458
455204eb
TS
459QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
460 void *opaque, int absolute,
461 const char *name)
63066f4f 462{
455204eb
TS
463 QEMUPutMouseEntry *s, *cursor;
464
465 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
466 if (!s)
467 return NULL;
468
469 s->qemu_put_mouse_event = func;
470 s->qemu_put_mouse_event_opaque = opaque;
471 s->qemu_put_mouse_event_absolute = absolute;
472 s->qemu_put_mouse_event_name = qemu_strdup(name);
473 s->next = NULL;
474
475 if (!qemu_put_mouse_event_head) {
476 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
477 return s;
478 }
479
480 cursor = qemu_put_mouse_event_head;
481 while (cursor->next != NULL)
482 cursor = cursor->next;
483
484 cursor->next = s;
485 qemu_put_mouse_event_current = s;
486
487 return s;
488}
489
490void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
491{
492 QEMUPutMouseEntry *prev = NULL, *cursor;
493
494 if (!qemu_put_mouse_event_head || entry == NULL)
495 return;
496
497 cursor = qemu_put_mouse_event_head;
498 while (cursor != NULL && cursor != entry) {
499 prev = cursor;
500 cursor = cursor->next;
501 }
502
503 if (cursor == NULL) // does not exist or list empty
504 return;
505 else if (prev == NULL) { // entry is head
506 qemu_put_mouse_event_head = cursor->next;
507 if (qemu_put_mouse_event_current == entry)
508 qemu_put_mouse_event_current = cursor->next;
509 qemu_free(entry->qemu_put_mouse_event_name);
510 qemu_free(entry);
511 return;
512 }
513
514 prev->next = entry->next;
515
516 if (qemu_put_mouse_event_current == entry)
517 qemu_put_mouse_event_current = prev;
518
519 qemu_free(entry->qemu_put_mouse_event_name);
520 qemu_free(entry);
63066f4f
FB
521}
522
523void kbd_put_keycode(int keycode)
524{
525 if (qemu_put_kbd_event) {
526 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
527 }
528}
529
530void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
531{
455204eb
TS
532 QEMUPutMouseEvent *mouse_event;
533 void *mouse_event_opaque;
a171fe39 534 int width;
455204eb
TS
535
536 if (!qemu_put_mouse_event_current) {
537 return;
538 }
539
540 mouse_event =
541 qemu_put_mouse_event_current->qemu_put_mouse_event;
542 mouse_event_opaque =
543 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
544
545 if (mouse_event) {
a171fe39
AZ
546 if (graphic_rotate) {
547 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
548 width = 0x7fff;
549 else
550 width = graphic_width;
551 mouse_event(mouse_event_opaque,
552 width - dy, dx, dz, buttons_state);
553 } else
554 mouse_event(mouse_event_opaque,
555 dx, dy, dz, buttons_state);
63066f4f
FB
556 }
557}
558
09b26c5e
FB
559int kbd_mouse_is_absolute(void)
560{
455204eb
TS
561 if (!qemu_put_mouse_event_current)
562 return 0;
563
564 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
565}
566
567void do_info_mice(void)
568{
569 QEMUPutMouseEntry *cursor;
570 int index = 0;
571
572 if (!qemu_put_mouse_event_head) {
573 term_printf("No mouse devices connected\n");
574 return;
575 }
576
577 term_printf("Mouse devices available:\n");
578 cursor = qemu_put_mouse_event_head;
579 while (cursor != NULL) {
580 term_printf("%c Mouse #%d: %s\n",
581 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
582 index, cursor->qemu_put_mouse_event_name);
583 index++;
584 cursor = cursor->next;
585 }
586}
587
588void do_mouse_set(int index)
589{
590 QEMUPutMouseEntry *cursor;
591 int i = 0;
592
593 if (!qemu_put_mouse_event_head) {
594 term_printf("No mouse devices connected\n");
595 return;
596 }
597
598 cursor = qemu_put_mouse_event_head;
599 while (cursor != NULL && index != i) {
600 i++;
601 cursor = cursor->next;
602 }
603
604 if (cursor != NULL)
605 qemu_put_mouse_event_current = cursor;
606 else
607 term_printf("Mouse at given index not found\n");
09b26c5e
FB
608}
609
1dce7c3c
FB
610/* compute with 96 bit intermediate result: (a*b)/c */
611uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
0824d6fc 612{
1dce7c3c
FB
613 union {
614 uint64_t ll;
615 struct {
616#ifdef WORDS_BIGENDIAN
617 uint32_t high, low;
618#else
619 uint32_t low, high;
620#endif
621 } l;
622 } u, res;
623 uint64_t rl, rh;
0824d6fc 624
1dce7c3c
FB
625 u.ll = a;
626 rl = (uint64_t)u.l.low * (uint64_t)b;
627 rh = (uint64_t)u.l.high * (uint64_t)b;
628 rh += (rl >> 32);
629 res.l.high = rh / c;
630 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
631 return res.ll;
34865134
FB
632}
633
1dce7c3c
FB
634/***********************************************************/
635/* real time host monotonic timer */
34865134 636
1dce7c3c 637#define QEMU_TIMER_BASE 1000000000LL
34865134 638
1dce7c3c 639#ifdef WIN32
0824d6fc 640
1dce7c3c 641static int64_t clock_freq;
1115dde7 642
1dce7c3c 643static void init_get_clock(void)
1115dde7 644{
a8e5ac33
FB
645 LARGE_INTEGER freq;
646 int ret;
1dce7c3c
FB
647 ret = QueryPerformanceFrequency(&freq);
648 if (ret == 0) {
649 fprintf(stderr, "Could not calibrate ticks\n");
650 exit(1);
651 }
652 clock_freq = freq.QuadPart;
1115dde7
FB
653}
654
1dce7c3c 655static int64_t get_clock(void)
b8076a74 656{
1dce7c3c
FB
657 LARGE_INTEGER ti;
658 QueryPerformanceCounter(&ti);
659 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
b8076a74
FB
660}
661
1dce7c3c 662#else
90cb9493 663
1dce7c3c
FB
664static int use_rt_clock;
665
666static void init_get_clock(void)
90cb9493 667{
1dce7c3c
FB
668 use_rt_clock = 0;
669#if defined(__linux__)
670 {
671 struct timespec ts;
672 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
673 use_rt_clock = 1;
674 }
675 }
676#endif
90cb9493
FB
677}
678
1dce7c3c 679static int64_t get_clock(void)
fdbb4691 680{
1dce7c3c
FB
681#if defined(__linux__)
682 if (use_rt_clock) {
683 struct timespec ts;
684 clock_gettime(CLOCK_MONOTONIC, &ts);
685 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
686 } else
fdbb4691 687#endif
1dce7c3c
FB
688 {
689 /* XXX: using gettimeofday leads to problems if the date
690 changes, so it should be avoided. */
691 struct timeval tv;
692 gettimeofday(&tv, NULL);
693 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
694 }
fdbb4691
FB
695}
696
34865134
FB
697#endif
698
1dce7c3c
FB
699/***********************************************************/
700/* guest cycle counter */
701
eade0f19 702static int64_t cpu_ticks_prev;
34865134 703static int64_t cpu_ticks_offset;
1dce7c3c 704static int64_t cpu_clock_offset;
8a7ddc38 705static int cpu_ticks_enabled;
34865134 706
1dce7c3c
FB
707/* return the host CPU cycle counter and handle stop/restart */
708int64_t cpu_get_ticks(void)
34865134 709{
8a7ddc38
FB
710 if (!cpu_ticks_enabled) {
711 return cpu_ticks_offset;
712 } else {
eade0f19
FB
713 int64_t ticks;
714 ticks = cpu_get_real_ticks();
715 if (cpu_ticks_prev > ticks) {
716 /* Note: non increasing ticks may happen if the host uses
717 software suspend */
718 cpu_ticks_offset += cpu_ticks_prev - ticks;
719 }
720 cpu_ticks_prev = ticks;
721 return ticks + cpu_ticks_offset;
8a7ddc38 722 }
34865134
FB
723}
724
1dce7c3c
FB
725/* return the host CPU monotonic timer and handle stop/restart */
726static int64_t cpu_get_clock(void)
727{
728 int64_t ti;
729 if (!cpu_ticks_enabled) {
730 return cpu_clock_offset;
731 } else {
732 ti = get_clock();
733 return ti + cpu_clock_offset;
734 }
735}
736
34865134
FB
737/* enable cpu_get_ticks() */
738void cpu_enable_ticks(void)
739{
8a7ddc38
FB
740 if (!cpu_ticks_enabled) {
741 cpu_ticks_offset -= cpu_get_real_ticks();
1dce7c3c 742 cpu_clock_offset -= get_clock();
8a7ddc38
FB
743 cpu_ticks_enabled = 1;
744 }
34865134
FB
745}
746
747/* disable cpu_get_ticks() : the clock is stopped. You must not call
748 cpu_get_ticks() after that. */
749void cpu_disable_ticks(void)
750{
8a7ddc38
FB
751 if (cpu_ticks_enabled) {
752 cpu_ticks_offset = cpu_get_ticks();
1dce7c3c 753 cpu_clock_offset = cpu_get_clock();
8a7ddc38
FB
754 cpu_ticks_enabled = 0;
755 }
34865134
FB
756}
757
1dce7c3c
FB
758/***********************************************************/
759/* timers */
760
8a7ddc38
FB
761#define QEMU_TIMER_REALTIME 0
762#define QEMU_TIMER_VIRTUAL 1
763
764struct QEMUClock {
765 int type;
766 /* XXX: add frequency */
767};
768
769struct QEMUTimer {
770 QEMUClock *clock;
771 int64_t expire_time;
772 QEMUTimerCB *cb;
773 void *opaque;
774 struct QEMUTimer *next;
775};
776
777QEMUClock *rt_clock;
778QEMUClock *vm_clock;
779
780static QEMUTimer *active_timers[2];
40c3bac3
FB
781#ifdef _WIN32
782static MMRESULT timerID;
06d9f2f7
FB
783static HANDLE host_alarm = NULL;
784static unsigned int period = 1;
40c3bac3 785#else
8a7ddc38
FB
786/* frequency of the times() clock tick */
787static int timer_freq;
67b915a5 788#endif
8a7ddc38
FB
789
790QEMUClock *qemu_new_clock(int type)
791{
792 QEMUClock *clock;
793 clock = qemu_mallocz(sizeof(QEMUClock));
794 if (!clock)
795 return NULL;
796 clock->type = type;
797 return clock;
798}
799
800QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
801{
802 QEMUTimer *ts;
803
804 ts = qemu_mallocz(sizeof(QEMUTimer));
805 ts->clock = clock;
806 ts->cb = cb;
807 ts->opaque = opaque;
808 return ts;
809}
810
811void qemu_free_timer(QEMUTimer *ts)
812{
813 qemu_free(ts);
814}
815
816/* stop a timer, but do not dealloc it */
817void qemu_del_timer(QEMUTimer *ts)
818{
819 QEMUTimer **pt, *t;
820
821 /* NOTE: this code must be signal safe because
822 qemu_timer_expired() can be called from a signal. */
823 pt = &active_timers[ts->clock->type];
824 for(;;) {
825 t = *pt;
826 if (!t)
827 break;
828 if (t == ts) {
829 *pt = t->next;
830 break;
831 }
832 pt = &t->next;
833 }
834}
835
836/* modify the current timer so that it will be fired when current_time
837 >= expire_time. The corresponding callback will be called. */
838void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
839{
840 QEMUTimer **pt, *t;
841
842 qemu_del_timer(ts);
843
844 /* add the timer in the sorted list */
845 /* NOTE: this code must be signal safe because
846 qemu_timer_expired() can be called from a signal. */
847 pt = &active_timers[ts->clock->type];
848 for(;;) {
849 t = *pt;
850 if (!t)
851 break;
852 if (t->expire_time > expire_time)
853 break;
854 pt = &t->next;
855 }
856 ts->expire_time = expire_time;
857 ts->next = *pt;
858 *pt = ts;
859}
860
861int qemu_timer_pending(QEMUTimer *ts)
862{
863 QEMUTimer *t;
864 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
865 if (t == ts)
866 return 1;
867 }
868 return 0;
869}
870
871static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
872{
873 if (!timer_head)
874 return 0;
875 return (timer_head->expire_time <= current_time);
876}
877
878static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
879{
880 QEMUTimer *ts;
881
882 for(;;) {
883 ts = *ptimer_head;
e95c8d51 884 if (!ts || ts->expire_time > current_time)
8a7ddc38
FB
885 break;
886 /* remove timer from the list before calling the callback */
887 *ptimer_head = ts->next;
888 ts->next = NULL;
889
890 /* run the callback (the timer list can be modified) */
891 ts->cb(ts->opaque);
892 }
893}
894
895int64_t qemu_get_clock(QEMUClock *clock)
896{
897 switch(clock->type) {
898 case QEMU_TIMER_REALTIME:
1dce7c3c 899 return get_clock() / 1000000;
8a7ddc38
FB
900 default:
901 case QEMU_TIMER_VIRTUAL:
1dce7c3c 902 return cpu_get_clock();
8a7ddc38
FB
903 }
904}
905
1dce7c3c
FB
906static void init_timers(void)
907{
908 init_get_clock();
909 ticks_per_sec = QEMU_TIMER_BASE;
910 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
911 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
912}
913
8a7ddc38
FB
914/* save a timer */
915void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
916{
917 uint64_t expire_time;
918
919 if (qemu_timer_pending(ts)) {
920 expire_time = ts->expire_time;
921 } else {
922 expire_time = -1;
923 }
924 qemu_put_be64(f, expire_time);
925}
926
927void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
928{
929 uint64_t expire_time;
930
931 expire_time = qemu_get_be64(f);
932 if (expire_time != -1) {
933 qemu_mod_timer(ts, expire_time);
934 } else {
935 qemu_del_timer(ts);
936 }
937}
938
939static void timer_save(QEMUFile *f, void *opaque)
940{
941 if (cpu_ticks_enabled) {
942 hw_error("cannot save state if virtual timers are running");
943 }
944 qemu_put_be64s(f, &cpu_ticks_offset);
945 qemu_put_be64s(f, &ticks_per_sec);
c88676f8 946 qemu_put_be64s(f, &cpu_clock_offset);
8a7ddc38
FB
947}
948
949static int timer_load(QEMUFile *f, void *opaque, int version_id)
950{
c88676f8 951 if (version_id != 1 && version_id != 2)
8a7ddc38
FB
952 return -EINVAL;
953 if (cpu_ticks_enabled) {
954 return -EINVAL;
955 }
956 qemu_get_be64s(f, &cpu_ticks_offset);
957 qemu_get_be64s(f, &ticks_per_sec);
c88676f8
FB
958 if (version_id == 2) {
959 qemu_get_be64s(f, &cpu_clock_offset);
960 }
8a7ddc38
FB
961 return 0;
962}
963
67b915a5
FB
964#ifdef _WIN32
965void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
966 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
967#else
8a7ddc38 968static void host_alarm_handler(int host_signum)
67b915a5 969#endif
8a7ddc38 970{
02ba45c5
FB
971#if 0
972#define DISP_FREQ 1000
973 {
974 static int64_t delta_min = INT64_MAX;
975 static int64_t delta_max, delta_cum, last_clock, delta, ti;
976 static int count;
977 ti = qemu_get_clock(vm_clock);
978 if (last_clock != 0) {
979 delta = ti - last_clock;
980 if (delta < delta_min)
981 delta_min = delta;
982 if (delta > delta_max)
983 delta_max = delta;
984 delta_cum += delta;
985 if (++count == DISP_FREQ) {
26a76461 986 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
02ba45c5
FB
987 muldiv64(delta_min, 1000000, ticks_per_sec),
988 muldiv64(delta_max, 1000000, ticks_per_sec),
989 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
990 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
991 count = 0;
992 delta_min = INT64_MAX;
993 delta_max = 0;
994 delta_cum = 0;
995 }
996 }
997 last_clock = ti;
998 }
999#endif
8a7ddc38
FB
1000 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1001 qemu_get_clock(vm_clock)) ||
1002 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1003 qemu_get_clock(rt_clock))) {
06d9f2f7
FB
1004#ifdef _WIN32
1005 SetEvent(host_alarm);
1006#endif
6a00d601
FB
1007 CPUState *env = cpu_single_env;
1008 if (env) {
1009 /* stop the currently executing cpu because a timer occured */
1010 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
a332e112 1011#ifdef USE_KQEMU
6a00d601
FB
1012 if (env->kqemu_enabled) {
1013 kqemu_cpu_interrupt(env);
1014 }
a332e112 1015#endif
6a00d601 1016 }
8a7ddc38
FB
1017 }
1018}
1019
fd872598
FB
1020#ifndef _WIN32
1021
829309c7
FB
1022#if defined(__linux__)
1023
fd872598
FB
1024#define RTC_FREQ 1024
1025
1026static int rtc_fd;
829309c7 1027
fd872598
FB
1028static int start_rtc_timer(void)
1029{
1030 rtc_fd = open("/dev/rtc", O_RDONLY);
1031 if (rtc_fd < 0)
1032 return -1;
1033 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1034 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1035 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1036 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1037 goto fail;
1038 }
1039 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1040 fail:
1041 close(rtc_fd);
1042 return -1;
1043 }
1044 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1045 return 0;
1046}
1047
829309c7
FB
1048#else
1049
1050static int start_rtc_timer(void)
1051{
1052 return -1;
1053}
1054
1055#endif /* !defined(__linux__) */
1056
1057#endif /* !defined(_WIN32) */
fd872598 1058
1dce7c3c 1059static void init_timer_alarm(void)
8a7ddc38 1060{
67b915a5
FB
1061#ifdef _WIN32
1062 {
1063 int count=0;
06d9f2f7
FB
1064 TIMECAPS tc;
1065
1066 ZeroMemory(&tc, sizeof(TIMECAPS));
1067 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1068 if (period < tc.wPeriodMin)
1069 period = tc.wPeriodMin;
1070 timeBeginPeriod(period);
1d14ffa9 1071 timerID = timeSetEvent(1, // interval (ms)
06d9f2f7 1072 period, // resolution
40c3bac3
FB
1073 host_alarm_handler, // function
1074 (DWORD)&count, // user parameter
1075 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
67b915a5
FB
1076 if( !timerID ) {
1077 perror("failed timer alarm");
1078 exit(1);
1079 }
06d9f2f7
FB
1080 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1081 if (!host_alarm) {
1082 perror("failed CreateEvent");
1083 exit(1);
1084 }
a18e524a 1085 qemu_add_wait_object(host_alarm, NULL, NULL);
67b915a5
FB
1086 }
1087 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1088#else
1089 {
1090 struct sigaction act;
1091 struct itimerval itv;
1092
1093 /* get times() syscall frequency */
1094 timer_freq = sysconf(_SC_CLK_TCK);
1095
1096 /* timer signal */
1097 sigfillset(&act.sa_mask);
a09db21f 1098 act.sa_flags = 0;
8a7ddc38 1099#if defined (TARGET_I386) && defined(USE_CODE_COPY)
67b915a5
FB
1100 act.sa_flags |= SA_ONSTACK;
1101#endif
1102 act.sa_handler = host_alarm_handler;
1103 sigaction(SIGALRM, &act, NULL);
fd872598 1104
67b915a5 1105 itv.it_interval.tv_sec = 0;
d79284e0 1106 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
67b915a5
FB
1107 itv.it_value.tv_sec = 0;
1108 itv.it_value.tv_usec = 10 * 1000;
1109 setitimer(ITIMER_REAL, &itv, NULL);
1110 /* we probe the tick duration of the kernel to inform the user if
1111 the emulated kernel requested a too high timer frequency */
1112 getitimer(ITIMER_REAL, &itv);
fd872598 1113
83fb7adf 1114#if defined(__linux__)
29e3055c
FB
1115 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1116 have timers with 1 ms resolution. The correct solution will
1117 be to use the POSIX real time timers available in recent
1118 2.6 kernels */
1119 if (itv.it_interval.tv_usec > 1000 || 1) {
fd872598
FB
1120 /* try to use /dev/rtc to have a faster timer */
1121 if (start_rtc_timer() < 0)
1122 goto use_itimer;
1123 /* disable itimer */
1124 itv.it_interval.tv_sec = 0;
1125 itv.it_interval.tv_usec = 0;
1126 itv.it_value.tv_sec = 0;
1127 itv.it_value.tv_usec = 0;
1128 setitimer(ITIMER_REAL, &itv, NULL);
1129
1130 /* use the RTC */
a1968d71 1131 sigaction(SIGIO, &act, NULL);
fd872598
FB
1132 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1133 fcntl(rtc_fd, F_SETOWN, getpid());
83fb7adf
FB
1134 } else
1135#endif /* defined(__linux__) */
1136 {
fd872598
FB
1137 use_itimer:
1138 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1139 PIT_FREQ) / 1000000;
1140 }
67b915a5 1141 }
8a7ddc38 1142#endif
8a7ddc38
FB
1143}
1144
40c3bac3
FB
1145void quit_timers(void)
1146{
1147#ifdef _WIN32
1148 timeKillEvent(timerID);
06d9f2f7
FB
1149 timeEndPeriod(period);
1150 if (host_alarm) {
1151 CloseHandle(host_alarm);
1152 host_alarm = NULL;
1153 }
40c3bac3
FB
1154#endif
1155}
1156
c4b1fcc0 1157/***********************************************************/
82c643ff 1158/* character device */
313aa567 1159
e5b0bc44
PB
1160static void qemu_chr_event(CharDriverState *s, int event)
1161{
1162 if (!s->chr_event)
1163 return;
1164 s->chr_event(s->handler_opaque, event);
1165}
1166
86e94dea
TS
1167static void qemu_chr_reset_bh(void *opaque)
1168{
1169 CharDriverState *s = opaque;
e5b0bc44 1170 qemu_chr_event(s, CHR_EVENT_RESET);
86e94dea
TS
1171 qemu_bh_delete(s->bh);
1172 s->bh = NULL;
1173}
1174
1175void qemu_chr_reset(CharDriverState *s)
1176{
1177 if (s->bh == NULL) {
1178 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1179 qemu_bh_schedule(s->bh);
1180 }
1181}
1182
82c643ff
FB
1183int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1184{
1185 return s->chr_write(s, buf, len);
1186}
67b915a5 1187
e57a8c0e 1188int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
f8d179e3 1189{
e57a8c0e
FB
1190 if (!s->chr_ioctl)
1191 return -ENOTSUP;
1192 return s->chr_ioctl(s, cmd, arg);
f8d179e3
FB
1193}
1194
e5b0bc44
PB
1195int qemu_chr_can_read(CharDriverState *s)
1196{
1197 if (!s->chr_can_read)
1198 return 0;
1199 return s->chr_can_read(s->handler_opaque);
1200}
1201
1202void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1203{
1204 s->chr_read(s->handler_opaque, buf, len);
1205}
1206
1207
82c643ff 1208void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
67b915a5 1209{
82c643ff
FB
1210 char buf[4096];
1211 va_list ap;
1212 va_start(ap, fmt);
1213 vsnprintf(buf, sizeof(buf), fmt, ap);
1214 qemu_chr_write(s, buf, strlen(buf));
1215 va_end(ap);
67b915a5
FB
1216}
1217
5905b2e5
FB
1218void qemu_chr_send_event(CharDriverState *s, int event)
1219{
1220 if (s->chr_send_event)
1221 s->chr_send_event(s, event);
1222}
1223
e5b0bc44
PB
1224void qemu_chr_add_handlers(CharDriverState *s,
1225 IOCanRWHandler *fd_can_read,
1226 IOReadHandler *fd_read,
1227 IOEventHandler *fd_event,
1228 void *opaque)
82c643ff 1229{
e5b0bc44
PB
1230 s->chr_can_read = fd_can_read;
1231 s->chr_read = fd_read;
1232 s->chr_event = fd_event;
1233 s->handler_opaque = opaque;
1234 if (s->chr_update_read_handler)
1235 s->chr_update_read_handler(s);
82c643ff
FB
1236}
1237
82c643ff 1238static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
313aa567 1239{
82c643ff
FB
1240 return len;
1241}
1242
52f61fde 1243static CharDriverState *qemu_chr_open_null(void)
82c643ff
FB
1244{
1245 CharDriverState *chr;
1246
1247 chr = qemu_mallocz(sizeof(CharDriverState));
1248 if (!chr)
1249 return NULL;
1250 chr->chr_write = null_chr_write;
82c643ff
FB
1251 return chr;
1252}
1253
20d8a3ed
TS
1254/* MUX driver for serial I/O splitting */
1255static int term_timestamps;
1256static int64_t term_timestamps_start;
9c1de612 1257#define MAX_MUX 4
20d8a3ed
TS
1258typedef struct {
1259 IOCanRWHandler *chr_can_read[MAX_MUX];
1260 IOReadHandler *chr_read[MAX_MUX];
1261 IOEventHandler *chr_event[MAX_MUX];
1262 void *ext_opaque[MAX_MUX];
1263 CharDriverState *drv;
1264 int mux_cnt;
1265 int term_got_escape;
1266 int max_size;
1267} MuxDriver;
1268
1269
1270static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1271{
1272 MuxDriver *d = chr->opaque;
1273 int ret;
1274 if (!term_timestamps) {
1275 ret = d->drv->chr_write(d->drv, buf, len);
1276 } else {
1277 int i;
1278
1279 ret = 0;
1280 for(i = 0; i < len; i++) {
1281 ret += d->drv->chr_write(d->drv, buf+i, 1);
1282 if (buf[i] == '\n') {
1283 char buf1[64];
1284 int64_t ti;
1285 int secs;
1286
1287 ti = get_clock();
1288 if (term_timestamps_start == -1)
1289 term_timestamps_start = ti;
1290 ti -= term_timestamps_start;
1291 secs = ti / 1000000000;
1292 snprintf(buf1, sizeof(buf1),
1293 "[%02d:%02d:%02d.%03d] ",
1294 secs / 3600,
1295 (secs / 60) % 60,
1296 secs % 60,
1297 (int)((ti / 1000000) % 1000));
1298 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1299 }
1300 }
1301 }
1302 return ret;
1303}
1304
1305static char *mux_help[] = {
1306 "% h print this help\n\r",
1307 "% x exit emulator\n\r",
1308 "% s save disk data back to file (if -snapshot)\n\r",
1309 "% t toggle console timestamps\n\r"
1310 "% b send break (magic sysrq)\n\r",
1311 "% c switch between console and monitor\n\r",
1312 "% % sends %\n\r",
1313 NULL
1314};
1315
1316static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1317static void mux_print_help(CharDriverState *chr)
1318{
1319 int i, j;
1320 char ebuf[15] = "Escape-Char";
1321 char cbuf[50] = "\n\r";
1322
1323 if (term_escape_char > 0 && term_escape_char < 26) {
1324 sprintf(cbuf,"\n\r");
1325 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1326 } else {
1327 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1328 }
1329 chr->chr_write(chr, cbuf, strlen(cbuf));
1330 for (i = 0; mux_help[i] != NULL; i++) {
1331 for (j=0; mux_help[i][j] != '\0'; j++) {
1332 if (mux_help[i][j] == '%')
1333 chr->chr_write(chr, ebuf, strlen(ebuf));
1334 else
1335 chr->chr_write(chr, &mux_help[i][j], 1);
1336 }
1337 }
1338}
1339
1340static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1341{
1342 if (d->term_got_escape) {
1343 d->term_got_escape = 0;
1344 if (ch == term_escape_char)
1345 goto send_char;
1346 switch(ch) {
1347 case '?':
1348 case 'h':
1349 mux_print_help(chr);
1350 break;
1351 case 'x':
1352 {
1353 char *term = "QEMU: Terminated\n\r";
1354 chr->chr_write(chr,term,strlen(term));
1355 exit(0);
1356 break;
1357 }
1358 case 's':
1359 {
1360 int i;
1361 for (i = 0; i < MAX_DISKS; i++) {
1362 if (bs_table[i])
1363 bdrv_commit(bs_table[i]);
1364 }
2dc7b602
AZ
1365 if (mtd_bdrv)
1366 bdrv_commit(mtd_bdrv);
20d8a3ed
TS
1367 }
1368 break;
1369 case 'b':
36ddb83b 1370 qemu_chr_event(chr, CHR_EVENT_BREAK);
20d8a3ed
TS
1371 break;
1372 case 'c':
1373 /* Switch to the next registered device */
1374 chr->focus++;
1375 if (chr->focus >= d->mux_cnt)
1376 chr->focus = 0;
1377 break;
1378 case 't':
1379 term_timestamps = !term_timestamps;
1380 term_timestamps_start = -1;
1381 break;
1382 }
1383 } else if (ch == term_escape_char) {
1384 d->term_got_escape = 1;
1385 } else {
1386 send_char:
1387 return 1;
1388 }
1389 return 0;
1390}
1391
1392static int mux_chr_can_read(void *opaque)
1393{
1394 CharDriverState *chr = opaque;
1395 MuxDriver *d = chr->opaque;
1396 if (d->chr_can_read[chr->focus])
1397 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1398 return 0;
1399}
1400
1401static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1402{
1403 CharDriverState *chr = opaque;
1404 MuxDriver *d = chr->opaque;
1405 int i;
1406 for(i = 0; i < size; i++)
1407 if (mux_proc_byte(chr, d, buf[i]))
1408 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1409}
1410
1411static void mux_chr_event(void *opaque, int event)
1412{
1413 CharDriverState *chr = opaque;
1414 MuxDriver *d = chr->opaque;
1415 int i;
1416
1417 /* Send the event to all registered listeners */
1418 for (i = 0; i < d->mux_cnt; i++)
1419 if (d->chr_event[i])
1420 d->chr_event[i](d->ext_opaque[i], event);
1421}
1422
1423static void mux_chr_update_read_handler(CharDriverState *chr)
1424{
1425 MuxDriver *d = chr->opaque;
1426
1427 if (d->mux_cnt >= MAX_MUX) {
1428 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1429 return;
1430 }
1431 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1432 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1433 d->chr_read[d->mux_cnt] = chr->chr_read;
1434 d->chr_event[d->mux_cnt] = chr->chr_event;
1435 /* Fix up the real driver with mux routines */
1436 if (d->mux_cnt == 0) {
1437 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1438 mux_chr_event, chr);
1439 }
1440 chr->focus = d->mux_cnt;
1441 d->mux_cnt++;
1442}
1443
1444CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1445{
1446 CharDriverState *chr;
1447 MuxDriver *d;
1448
1449 chr = qemu_mallocz(sizeof(CharDriverState));
1450 if (!chr)
1451 return NULL;
1452 d = qemu_mallocz(sizeof(MuxDriver));
1453 if (!d) {
1454 free(chr);
1455 return NULL;
1456 }
1457
1458 chr->opaque = d;
1459 d->drv = drv;
1460 chr->focus = -1;
1461 chr->chr_write = mux_chr_write;
1462 chr->chr_update_read_handler = mux_chr_update_read_handler;
1463 return chr;
1464}
1465
1466
fd1dff4b 1467#ifdef _WIN32
82c643ff 1468
fd1dff4b
FB
1469static void socket_cleanup(void)
1470{
1471 WSACleanup();
1472}
82c643ff 1473
fd1dff4b
FB
1474static int socket_init(void)
1475{
1476 WSADATA Data;
1477 int ret, err;
1478
1479 ret = WSAStartup(MAKEWORD(2,2), &Data);
1480 if (ret != 0) {
1481 err = WSAGetLastError();
1482 fprintf(stderr, "WSAStartup: %d\n", err);
1483 return -1;
1484 }
1485 atexit(socket_cleanup);
1486 return 0;
1487}
1488
1489static int send_all(int fd, const uint8_t *buf, int len1)
1490{
1491 int ret, len;
1492
1493 len = len1;
1494 while (len > 0) {
1495 ret = send(fd, buf, len, 0);
1496 if (ret < 0) {
1497 int errno;
1498 errno = WSAGetLastError();
1499 if (errno != WSAEWOULDBLOCK) {
1500 return -1;
1501 }
1502 } else if (ret == 0) {
1503 break;
1504 } else {
1505 buf += ret;
1506 len -= ret;
1507 }
1508 }
1509 return len1 - len;
1510}
1511
1512void socket_set_nonblock(int fd)
1513{
1514 unsigned long opt = 1;
1515 ioctlsocket(fd, FIONBIO, &opt);
1516}
1517
1518#else
1519
1d96905d
FB
1520static int unix_write(int fd, const uint8_t *buf, int len1)
1521{
1522 int ret, len;
1523
1524 len = len1;
1525 while (len > 0) {
1526 ret = write(fd, buf, len);
1527 if (ret < 0) {
1528 if (errno != EINTR && errno != EAGAIN)
1529 return -1;
1530 } else if (ret == 0) {
1531 break;
1532 } else {
1533 buf += ret;
1534 len -= ret;
1535 }
1536 }
1537 return len1 - len;
1538}
1539
fd1dff4b
FB
1540static inline int send_all(int fd, const uint8_t *buf, int len1)
1541{
1542 return unix_write(fd, buf, len1);
1543}
1544
1545void socket_set_nonblock(int fd)
1546{
1547 fcntl(fd, F_SETFL, O_NONBLOCK);
1548}
1549#endif /* !_WIN32 */
1550
1551#ifndef _WIN32
1552
1553typedef struct {
1554 int fd_in, fd_out;
fd1dff4b
FB
1555 int max_size;
1556} FDCharDriver;
1557
20d8a3ed
TS
1558#define STDIO_MAX_CLIENTS 1
1559static int stdio_nb_clients = 0;
fd1dff4b 1560
82c643ff
FB
1561static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1562{
1563 FDCharDriver *s = chr->opaque;
1d96905d 1564 return unix_write(s->fd_out, buf, len);
82c643ff
FB
1565}
1566
7c9d8e07
FB
1567static int fd_chr_read_poll(void *opaque)
1568{
1569 CharDriverState *chr = opaque;
1570 FDCharDriver *s = chr->opaque;
1571
e5b0bc44 1572 s->max_size = qemu_chr_can_read(chr);
7c9d8e07
FB
1573 return s->max_size;
1574}
1575
1576static void fd_chr_read(void *opaque)
1577{
1578 CharDriverState *chr = opaque;
1579 FDCharDriver *s = chr->opaque;
1580 int size, len;
1581 uint8_t buf[1024];
1582
1583 len = sizeof(buf);
1584 if (len > s->max_size)
1585 len = s->max_size;
1586 if (len == 0)
1587 return;
1588 size = read(s->fd_in, buf, len);
188157fe
PB
1589 if (size == 0) {
1590 /* FD has been closed. Remove it from the active list. */
1591 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1592 return;
1593 }
7c9d8e07 1594 if (size > 0) {
e5b0bc44 1595 qemu_chr_read(chr, buf, size);
7c9d8e07
FB
1596 }
1597}
1598
e5b0bc44 1599static void fd_chr_update_read_handler(CharDriverState *chr)
82c643ff
FB
1600{
1601 FDCharDriver *s = chr->opaque;
1602
f8d179e3
FB
1603 if (s->fd_in >= 0) {
1604 if (nographic && s->fd_in == 0) {
f8d179e3 1605 } else {
7c9d8e07
FB
1606 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1607 fd_chr_read, NULL, chr);
f8d179e3 1608 }
82c643ff
FB
1609 }
1610}
1611
1612/* open a character device to a unix fd */
52f61fde 1613static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
82c643ff
FB
1614{
1615 CharDriverState *chr;
1616 FDCharDriver *s;
1617
1618 chr = qemu_mallocz(sizeof(CharDriverState));
1619 if (!chr)
1620 return NULL;
1621 s = qemu_mallocz(sizeof(FDCharDriver));
1622 if (!s) {
1623 free(chr);
1624 return NULL;
1625 }
1626 s->fd_in = fd_in;
1627 s->fd_out = fd_out;
1628 chr->opaque = s;
1629 chr->chr_write = fd_chr_write;
e5b0bc44 1630 chr->chr_update_read_handler = fd_chr_update_read_handler;
86e94dea
TS
1631
1632 qemu_chr_reset(chr);
1633
82c643ff
FB
1634 return chr;
1635}
1636
52f61fde 1637static CharDriverState *qemu_chr_open_file_out(const char *file_out)
f8d179e3
FB
1638{
1639 int fd_out;
1640
89ba1a73 1641 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
f8d179e3
FB
1642 if (fd_out < 0)
1643 return NULL;
1644 return qemu_chr_open_fd(-1, fd_out);
1645}
1646
52f61fde 1647static CharDriverState *qemu_chr_open_pipe(const char *filename)
f8d179e3 1648{
c26c1c4b
TS
1649 int fd_in, fd_out;
1650 char filename_in[256], filename_out[256];
1651
1652 snprintf(filename_in, 256, "%s.in", filename);
1653 snprintf(filename_out, 256, "%s.out", filename);
1654 fd_in = open(filename_in, O_RDWR | O_BINARY);
1655 fd_out = open(filename_out, O_RDWR | O_BINARY);
1656 if (fd_in < 0 || fd_out < 0) {
1657 if (fd_in >= 0)
1658 close(fd_in);
1659 if (fd_out >= 0)
1660 close(fd_out);
1661 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1662 if (fd_in < 0)
1663 return NULL;
1664 }
1665 return qemu_chr_open_fd(fd_in, fd_out);
f8d179e3
FB
1666}
1667
1668
82c643ff
FB
1669/* for STDIO, we handle the case where several clients use it
1670 (nographic mode) */
1671
aa0bc6b6
FB
1672#define TERM_FIFO_MAX_SIZE 1
1673
aa0bc6b6 1674static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1dce7c3c 1675static int term_fifo_size;
330d0414 1676
7c9d8e07 1677static int stdio_read_poll(void *opaque)
82c643ff 1678{
20d8a3ed 1679 CharDriverState *chr = opaque;
aa0bc6b6 1680
20d8a3ed
TS
1681 /* try to flush the queue if needed */
1682 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1683 qemu_chr_read(chr, term_fifo, 1);
1684 term_fifo_size = 0;
aa0bc6b6 1685 }
20d8a3ed
TS
1686 /* see if we can absorb more chars */
1687 if (term_fifo_size == 0)
1688 return 1;
1689 else
1690 return 0;
82c643ff
FB
1691}
1692
7c9d8e07 1693static void stdio_read(void *opaque)
82c643ff 1694{
7c9d8e07
FB
1695 int size;
1696 uint8_t buf[1];
20d8a3ed
TS
1697 CharDriverState *chr = opaque;
1698
7c9d8e07 1699 size = read(0, buf, 1);
519945df
PB
1700 if (size == 0) {
1701 /* stdin has been closed. Remove it from the active list. */
1702 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1703 return;
1704 }
20d8a3ed
TS
1705 if (size > 0) {
1706 if (qemu_chr_can_read(chr) > 0) {
1707 qemu_chr_read(chr, buf, 1);
1708 } else if (term_fifo_size == 0) {
1709 term_fifo[term_fifo_size++] = buf[0];
1dce7c3c 1710 }
1dce7c3c
FB
1711 }
1712}
1713
8d11df9e
FB
1714/* init terminal so that we can grab keys */
1715static struct termios oldtty;
1716static int old_fd0_flags;
1717
1718static void term_exit(void)
1719{
1720 tcsetattr (0, TCSANOW, &oldtty);
1721 fcntl(0, F_SETFL, old_fd0_flags);
1722}
1723
1724static void term_init(void)
1725{
1726 struct termios tty;
1727
1728 tcgetattr (0, &tty);
1729 oldtty = tty;
1730 old_fd0_flags = fcntl(0, F_GETFL);
1731
1732 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1733 |INLCR|IGNCR|ICRNL|IXON);
1734 tty.c_oflag |= OPOST;
1735 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1736 /* if graphical mode, we allow Ctrl-C handling */
1737 if (nographic)
1738 tty.c_lflag &= ~ISIG;
1739 tty.c_cflag &= ~(CSIZE|PARENB);
1740 tty.c_cflag |= CS8;
1741 tty.c_cc[VMIN] = 1;
1742 tty.c_cc[VTIME] = 0;
1743
1744 tcsetattr (0, TCSANOW, &tty);
1745
1746 atexit(term_exit);
1747
1748 fcntl(0, F_SETFL, O_NONBLOCK);
1749}
1750
52f61fde 1751static CharDriverState *qemu_chr_open_stdio(void)
82c643ff
FB
1752{
1753 CharDriverState *chr;
1754
20d8a3ed
TS
1755 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1756 return NULL;
1757 chr = qemu_chr_open_fd(0, 1);
1758 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1759 stdio_nb_clients++;
1760 term_init();
1761
82c643ff
FB
1762 return chr;
1763}
1764
1765#if defined(__linux__)
52f61fde 1766static CharDriverState *qemu_chr_open_pty(void)
82c643ff 1767{
91fc2119 1768 struct termios tty;
82c643ff
FB
1769 char slave_name[1024];
1770 int master_fd, slave_fd;
1771
1772 /* Not satisfying */
1773 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1774 return NULL;
1775 }
91fc2119
FB
1776
1777 /* Disabling local echo and line-buffered output */
1778 tcgetattr (master_fd, &tty);
1779 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1780 tty.c_cc[VMIN] = 1;
1781 tty.c_cc[VTIME] = 0;
1782 tcsetattr (master_fd, TCSAFLUSH, &tty);
1783
82c643ff
FB
1784 fprintf(stderr, "char device redirected to %s\n", slave_name);
1785 return qemu_chr_open_fd(master_fd, master_fd);
1786}
f8d179e3
FB
1787
1788static void tty_serial_init(int fd, int speed,
1789 int parity, int data_bits, int stop_bits)
1790{
1791 struct termios tty;
1792 speed_t spd;
1793
e57a8c0e
FB
1794#if 0
1795 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1796 speed, parity, data_bits, stop_bits);
1797#endif
1798 tcgetattr (fd, &tty);
f8d179e3
FB
1799
1800 switch(speed) {
1801 case 50:
1802 spd = B50;
1803 break;
1804 case 75:
1805 spd = B75;
1806 break;
1807 case 300:
1808 spd = B300;
1809 break;
1810 case 600:
1811 spd = B600;
1812 break;
1813 case 1200:
1814 spd = B1200;
1815 break;
1816 case 2400:
1817 spd = B2400;
1818 break;
1819 case 4800:
1820 spd = B4800;
1821 break;
1822 case 9600:
1823 spd = B9600;
1824 break;
1825 case 19200:
1826 spd = B19200;
1827 break;
1828 case 38400:
1829 spd = B38400;
1830 break;
1831 case 57600:
1832 spd = B57600;
1833 break;
1834 default:
1835 case 115200:
1836 spd = B115200;
1837 break;
1838 }
1839
1840 cfsetispeed(&tty, spd);
1841 cfsetospeed(&tty, spd);
1842
1843 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1844 |INLCR|IGNCR|ICRNL|IXON);
1845 tty.c_oflag |= OPOST;
1846 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
094eed6c 1847 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
f8d179e3
FB
1848 switch(data_bits) {
1849 default:
1850 case 8:
1851 tty.c_cflag |= CS8;
1852 break;
1853 case 7:
1854 tty.c_cflag |= CS7;
1855 break;
1856 case 6:
1857 tty.c_cflag |= CS6;
1858 break;
1859 case 5:
1860 tty.c_cflag |= CS5;
1861 break;
1862 }
1863 switch(parity) {
1864 default:
1865 case 'N':
1866 break;
1867 case 'E':
1868 tty.c_cflag |= PARENB;
1869 break;
1870 case 'O':
1871 tty.c_cflag |= PARENB | PARODD;
1872 break;
1873 }
094eed6c
FB
1874 if (stop_bits == 2)
1875 tty.c_cflag |= CSTOPB;
f8d179e3
FB
1876
1877 tcsetattr (fd, TCSANOW, &tty);
1878}
1879
e57a8c0e 1880static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
f8d179e3
FB
1881{
1882 FDCharDriver *s = chr->opaque;
e57a8c0e
FB
1883
1884 switch(cmd) {
1885 case CHR_IOCTL_SERIAL_SET_PARAMS:
1886 {
1887 QEMUSerialSetParams *ssp = arg;
1888 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1889 ssp->data_bits, ssp->stop_bits);
1890 }
1891 break;
1892 case CHR_IOCTL_SERIAL_SET_BREAK:
1893 {
1894 int enable = *(int *)arg;
1895 if (enable)
1896 tcsendbreak(s->fd_in, 1);
1897 }
1898 break;
1899 default:
1900 return -ENOTSUP;
1901 }
1902 return 0;
f8d179e3
FB
1903}
1904
52f61fde 1905static CharDriverState *qemu_chr_open_tty(const char *filename)
f8d179e3
FB
1906{
1907 CharDriverState *chr;
1908 int fd;
1909
e57a8c0e 1910 fd = open(filename, O_RDWR | O_NONBLOCK);
f8d179e3
FB
1911 if (fd < 0)
1912 return NULL;
1913 fcntl(fd, F_SETFL, O_NONBLOCK);
1914 tty_serial_init(fd, 115200, 'N', 8, 1);
1915 chr = qemu_chr_open_fd(fd, fd);
1916 if (!chr)
1917 return NULL;
e57a8c0e 1918 chr->chr_ioctl = tty_serial_ioctl;
86e94dea 1919 qemu_chr_reset(chr);
e57a8c0e
FB
1920 return chr;
1921}
1922
5867c88a
TS
1923typedef struct {
1924 int fd;
1925 int mode;
1926} ParallelCharDriver;
1927
1928static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1929{
1930 if (s->mode != mode) {
1931 int m = mode;
1932 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1933 return 0;
1934 s->mode = mode;
1935 }
1936 return 1;
1937}
1938
e57a8c0e
FB
1939static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1940{
5867c88a
TS
1941 ParallelCharDriver *drv = chr->opaque;
1942 int fd = drv->fd;
e57a8c0e
FB
1943 uint8_t b;
1944
1945 switch(cmd) {
1946 case CHR_IOCTL_PP_READ_DATA:
1947 if (ioctl(fd, PPRDATA, &b) < 0)
1948 return -ENOTSUP;
1949 *(uint8_t *)arg = b;
1950 break;
1951 case CHR_IOCTL_PP_WRITE_DATA:
1952 b = *(uint8_t *)arg;
1953 if (ioctl(fd, PPWDATA, &b) < 0)
1954 return -ENOTSUP;
1955 break;
1956 case CHR_IOCTL_PP_READ_CONTROL:
1957 if (ioctl(fd, PPRCONTROL, &b) < 0)
1958 return -ENOTSUP;
5867c88a
TS
1959 /* Linux gives only the lowest bits, and no way to know data
1960 direction! For better compatibility set the fixed upper
1961 bits. */
1962 *(uint8_t *)arg = b | 0xc0;
e57a8c0e
FB
1963 break;
1964 case CHR_IOCTL_PP_WRITE_CONTROL:
1965 b = *(uint8_t *)arg;
1966 if (ioctl(fd, PPWCONTROL, &b) < 0)
1967 return -ENOTSUP;
1968 break;
1969 case CHR_IOCTL_PP_READ_STATUS:
1970 if (ioctl(fd, PPRSTATUS, &b) < 0)
1971 return -ENOTSUP;
1972 *(uint8_t *)arg = b;
1973 break;
5867c88a
TS
1974 case CHR_IOCTL_PP_EPP_READ_ADDR:
1975 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1976 struct ParallelIOArg *parg = arg;
1977 int n = read(fd, parg->buffer, parg->count);
1978 if (n != parg->count) {
1979 return -EIO;
1980 }
1981 }
1982 break;
1983 case CHR_IOCTL_PP_EPP_READ:
1984 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1985 struct ParallelIOArg *parg = arg;
1986 int n = read(fd, parg->buffer, parg->count);
1987 if (n != parg->count) {
1988 return -EIO;
1989 }
1990 }
1991 break;
1992 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1993 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1994 struct ParallelIOArg *parg = arg;
1995 int n = write(fd, parg->buffer, parg->count);
1996 if (n != parg->count) {
1997 return -EIO;
1998 }
1999 }
2000 break;
2001 case CHR_IOCTL_PP_EPP_WRITE:
2002 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2003 struct ParallelIOArg *parg = arg;
2004 int n = write(fd, parg->buffer, parg->count);
2005 if (n != parg->count) {
2006 return -EIO;
2007 }
2008 }
2009 break;
e57a8c0e
FB
2010 default:
2011 return -ENOTSUP;
2012 }
2013 return 0;
2014}
2015
5867c88a
TS
2016static void pp_close(CharDriverState *chr)
2017{
2018 ParallelCharDriver *drv = chr->opaque;
2019 int fd = drv->fd;
2020
2021 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2022 ioctl(fd, PPRELEASE);
2023 close(fd);
2024 qemu_free(drv);
2025}
2026
52f61fde 2027static CharDriverState *qemu_chr_open_pp(const char *filename)
e57a8c0e
FB
2028{
2029 CharDriverState *chr;
5867c88a 2030 ParallelCharDriver *drv;
e57a8c0e
FB
2031 int fd;
2032
2033 fd = open(filename, O_RDWR);
2034 if (fd < 0)
2035 return NULL;
2036
2037 if (ioctl(fd, PPCLAIM) < 0) {
2038 close(fd);
2039 return NULL;
2040 }
2041
5867c88a
TS
2042 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2043 if (!drv) {
2044 close(fd);
2045 return NULL;
2046 }
2047 drv->fd = fd;
2048 drv->mode = IEEE1284_MODE_COMPAT;
2049
e57a8c0e
FB
2050 chr = qemu_mallocz(sizeof(CharDriverState));
2051 if (!chr) {
5867c88a 2052 qemu_free(drv);
e57a8c0e
FB
2053 close(fd);
2054 return NULL;
2055 }
e57a8c0e 2056 chr->chr_write = null_chr_write;
e57a8c0e 2057 chr->chr_ioctl = pp_ioctl;
5867c88a
TS
2058 chr->chr_close = pp_close;
2059 chr->opaque = drv;
86e94dea
TS
2060
2061 qemu_chr_reset(chr);
2062
f8d179e3
FB
2063 return chr;
2064}
2065
82c643ff 2066#else
52f61fde 2067static CharDriverState *qemu_chr_open_pty(void)
82c643ff
FB
2068{
2069 return NULL;
2070}
67b915a5
FB
2071#endif
2072
82c643ff
FB
2073#endif /* !defined(_WIN32) */
2074
f331110f
FB
2075#ifdef _WIN32
2076typedef struct {
f331110f
FB
2077 int max_size;
2078 HANDLE hcom, hrecv, hsend;
2079 OVERLAPPED orecv, osend;
2080 BOOL fpipe;
2081 DWORD len;
2082} WinCharState;
2083
2084#define NSENDBUF 2048
2085#define NRECVBUF 2048
2086#define MAXCONNECT 1
2087#define NTIMEOUT 5000
2088
2089static int win_chr_poll(void *opaque);
2090static int win_chr_pipe_poll(void *opaque);
2091
087f4ae0 2092static void win_chr_close(CharDriverState *chr)
f331110f 2093{
087f4ae0
TS
2094 WinCharState *s = chr->opaque;
2095
f331110f
FB
2096 if (s->hsend) {
2097 CloseHandle(s->hsend);
2098 s->hsend = NULL;
2099 }
2100 if (s->hrecv) {
2101 CloseHandle(s->hrecv);
2102 s->hrecv = NULL;
2103 }
2104 if (s->hcom) {
2105 CloseHandle(s->hcom);
2106 s->hcom = NULL;
2107 }
2108 if (s->fpipe)
087f4ae0 2109 qemu_del_polling_cb(win_chr_pipe_poll, chr);
f331110f 2110 else
087f4ae0 2111 qemu_del_polling_cb(win_chr_poll, chr);
f331110f
FB
2112}
2113
087f4ae0 2114static int win_chr_init(CharDriverState *chr, const char *filename)
f331110f
FB
2115{
2116 WinCharState *s = chr->opaque;
f331110f
FB
2117 COMMCONFIG comcfg;
2118 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2119 COMSTAT comstat;
2120 DWORD size;
2121 DWORD err;
2122
2123 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2124 if (!s->hsend) {
2125 fprintf(stderr, "Failed CreateEvent\n");
2126 goto fail;
2127 }
2128 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2129 if (!s->hrecv) {
2130 fprintf(stderr, "Failed CreateEvent\n");
2131 goto fail;
2132 }
2133
2134 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2135 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2136 if (s->hcom == INVALID_HANDLE_VALUE) {
2137 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2138 s->hcom = NULL;
2139 goto fail;
2140 }
2141
2142 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2143 fprintf(stderr, "Failed SetupComm\n");
2144 goto fail;
2145 }
2146
2147 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2148 size = sizeof(COMMCONFIG);
2149 GetDefaultCommConfig(filename, &comcfg, &size);
2150 comcfg.dcb.DCBlength = sizeof(DCB);
2151 CommConfigDialog(filename, NULL, &comcfg);
2152
2153 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2154 fprintf(stderr, "Failed SetCommState\n");
2155 goto fail;
2156 }
2157
2158 if (!SetCommMask(s->hcom, EV_ERR)) {
2159 fprintf(stderr, "Failed SetCommMask\n");
2160 goto fail;
2161 }
2162
2163 cto.ReadIntervalTimeout = MAXDWORD;
2164 if (!SetCommTimeouts(s->hcom, &cto)) {
2165 fprintf(stderr, "Failed SetCommTimeouts\n");
2166 goto fail;
2167 }
2168
2169 if (!ClearCommError(s->hcom, &err, &comstat)) {
2170 fprintf(stderr, "Failed ClearCommError\n");
2171 goto fail;
2172 }
087f4ae0 2173 qemu_add_polling_cb(win_chr_poll, chr);
f331110f
FB
2174 return 0;
2175
2176 fail:
087f4ae0 2177 win_chr_close(chr);
f331110f
FB
2178 return -1;
2179}
2180
2181static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2182{
2183 WinCharState *s = chr->opaque;
2184 DWORD len, ret, size, err;
2185
2186 len = len1;
2187 ZeroMemory(&s->osend, sizeof(s->osend));
2188 s->osend.hEvent = s->hsend;
2189 while (len > 0) {
2190 if (s->hsend)
2191 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2192 else
2193 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2194 if (!ret) {
2195 err = GetLastError();
2196 if (err == ERROR_IO_PENDING) {
2197 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2198 if (ret) {
2199 buf += size;
2200 len -= size;
2201 } else {
2202 break;
2203 }
2204 } else {
2205 break;
2206 }
2207 } else {
2208 buf += size;
2209 len -= size;
2210 }
2211 }
2212 return len1 - len;
2213}
2214
087f4ae0 2215static int win_chr_read_poll(CharDriverState *chr)
f331110f 2216{
087f4ae0
TS
2217 WinCharState *s = chr->opaque;
2218
2219 s->max_size = qemu_chr_can_read(chr);
f331110f
FB
2220 return s->max_size;
2221}
e5b0bc44 2222
087f4ae0 2223static void win_chr_readfile(CharDriverState *chr)
f331110f 2224{
087f4ae0 2225 WinCharState *s = chr->opaque;
f331110f
FB
2226 int ret, err;
2227 uint8_t buf[1024];
2228 DWORD size;
2229
2230 ZeroMemory(&s->orecv, sizeof(s->orecv));
2231 s->orecv.hEvent = s->hrecv;
2232 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2233 if (!ret) {
2234 err = GetLastError();
2235 if (err == ERROR_IO_PENDING) {
2236 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2237 }
2238 }
2239
2240 if (size > 0) {
087f4ae0 2241 qemu_chr_read(chr, buf, size);
f331110f
FB
2242 }
2243}
2244
087f4ae0 2245static void win_chr_read(CharDriverState *chr)
f331110f 2246{
087f4ae0
TS
2247 WinCharState *s = chr->opaque;
2248
f331110f
FB
2249 if (s->len > s->max_size)
2250 s->len = s->max_size;
2251 if (s->len == 0)
2252 return;
2253
087f4ae0 2254 win_chr_readfile(chr);
f331110f
FB
2255}
2256
2257static int win_chr_poll(void *opaque)
2258{
087f4ae0
TS
2259 CharDriverState *chr = opaque;
2260 WinCharState *s = chr->opaque;
f331110f
FB
2261 COMSTAT status;
2262 DWORD comerr;
2263
2264 ClearCommError(s->hcom, &comerr, &status);
2265 if (status.cbInQue > 0) {
2266 s->len = status.cbInQue;
087f4ae0
TS
2267 win_chr_read_poll(chr);
2268 win_chr_read(chr);
f331110f
FB
2269 return 1;
2270 }
2271 return 0;
2272}
2273
52f61fde 2274static CharDriverState *qemu_chr_open_win(const char *filename)
f331110f
FB
2275{
2276 CharDriverState *chr;
2277 WinCharState *s;
2278
2279 chr = qemu_mallocz(sizeof(CharDriverState));
2280 if (!chr)
2281 return NULL;
2282 s = qemu_mallocz(sizeof(WinCharState));
2283 if (!s) {
2284 free(chr);
2285 return NULL;
2286 }
2287 chr->opaque = s;
2288 chr->chr_write = win_chr_write;
f331110f
FB
2289 chr->chr_close = win_chr_close;
2290
087f4ae0 2291 if (win_chr_init(chr, filename) < 0) {
f331110f
FB
2292 free(s);
2293 free(chr);
2294 return NULL;
2295 }
86e94dea 2296 qemu_chr_reset(chr);
f331110f
FB
2297 return chr;
2298}
2299
2300static int win_chr_pipe_poll(void *opaque)
2301{
087f4ae0
TS
2302 CharDriverState *chr = opaque;
2303 WinCharState *s = chr->opaque;
f331110f
FB
2304 DWORD size;
2305
2306 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2307 if (size > 0) {
2308 s->len = size;
087f4ae0
TS
2309 win_chr_read_poll(chr);
2310 win_chr_read(chr);
f331110f
FB
2311 return 1;
2312 }
2313 return 0;
2314}
2315
087f4ae0 2316static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
f331110f 2317{
087f4ae0 2318 WinCharState *s = chr->opaque;
f331110f
FB
2319 OVERLAPPED ov;
2320 int ret;
2321 DWORD size;
2322 char openname[256];
2323
2324 s->fpipe = TRUE;
2325
2326 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2327 if (!s->hsend) {
2328 fprintf(stderr, "Failed CreateEvent\n");
2329 goto fail;
2330 }
2331 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2332 if (!s->hrecv) {
2333 fprintf(stderr, "Failed CreateEvent\n");
2334 goto fail;
2335 }
2336
2337 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2338 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2339 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2340 PIPE_WAIT,
2341 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2342 if (s->hcom == INVALID_HANDLE_VALUE) {
2343 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2344 s->hcom = NULL;
2345 goto fail;
2346 }
2347
2348 ZeroMemory(&ov, sizeof(ov));
2349 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2350 ret = ConnectNamedPipe(s->hcom, &ov);
2351 if (ret) {
2352 fprintf(stderr, "Failed ConnectNamedPipe\n");
2353 goto fail;
2354 }
2355
2356 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2357 if (!ret) {
2358 fprintf(stderr, "Failed GetOverlappedResult\n");
2359 if (ov.hEvent) {
2360 CloseHandle(ov.hEvent);
2361 ov.hEvent = NULL;
2362 }
2363 goto fail;
2364 }
2365
2366 if (ov.hEvent) {
2367 CloseHandle(ov.hEvent);
2368 ov.hEvent = NULL;
2369 }
087f4ae0 2370 qemu_add_polling_cb(win_chr_pipe_poll, chr);
f331110f
FB
2371 return 0;
2372
2373 fail:
087f4ae0 2374 win_chr_close(chr);
f331110f
FB
2375 return -1;
2376}
2377
2378
52f61fde 2379static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
f331110f
FB
2380{
2381 CharDriverState *chr;
2382 WinCharState *s;
2383
2384 chr = qemu_mallocz(sizeof(CharDriverState));
2385 if (!chr)
2386 return NULL;
2387 s = qemu_mallocz(sizeof(WinCharState));
2388 if (!s) {
2389 free(chr);
2390 return NULL;
2391 }
2392 chr->opaque = s;
2393 chr->chr_write = win_chr_write;
f331110f
FB
2394 chr->chr_close = win_chr_close;
2395
087f4ae0 2396 if (win_chr_pipe_init(chr, filename) < 0) {
f331110f
FB
2397 free(s);
2398 free(chr);
2399 return NULL;
2400 }
86e94dea 2401 qemu_chr_reset(chr);
f331110f
FB
2402 return chr;
2403}
2404
52f61fde 2405static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
f331110f
FB
2406{
2407 CharDriverState *chr;
2408 WinCharState *s;
2409
2410 chr = qemu_mallocz(sizeof(CharDriverState));
2411 if (!chr)
2412 return NULL;
2413 s = qemu_mallocz(sizeof(WinCharState));
2414 if (!s) {
2415 free(chr);
2416 return NULL;
2417 }
2418 s->hcom = fd_out;
2419 chr->opaque = s;
2420 chr->chr_write = win_chr_write;
86e94dea 2421 qemu_chr_reset(chr);
f331110f
FB
2422 return chr;
2423}
72d46479
TS
2424
2425static CharDriverState *qemu_chr_open_win_con(const char *filename)
2426{
2427 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2428}
2429
52f61fde 2430static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
f331110f
FB
2431{
2432 HANDLE fd_out;
2433
2434 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2435 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2436 if (fd_out == INVALID_HANDLE_VALUE)
2437 return NULL;
2438
2439 return qemu_chr_open_win_file(fd_out);
2440}
2441#endif
2442
0bab00f3
FB
2443/***********************************************************/
2444/* UDP Net console */
2445
2446typedef struct {
0bab00f3
FB
2447 int fd;
2448 struct sockaddr_in daddr;
2449 char buf[1024];
2450 int bufcnt;
2451 int bufptr;
2452 int max_size;
2453} NetCharDriver;
2454
2455static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2456{
2457 NetCharDriver *s = chr->opaque;
2458
2459 return sendto(s->fd, buf, len, 0,
2460 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2461}
2462
2463static int udp_chr_read_poll(void *opaque)
2464{
2465 CharDriverState *chr = opaque;
2466 NetCharDriver *s = chr->opaque;
2467
e5b0bc44 2468 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
2469
2470 /* If there were any stray characters in the queue process them
2471 * first
2472 */
2473 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
e5b0bc44 2474 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
0bab00f3 2475 s->bufptr++;
e5b0bc44 2476 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
2477 }
2478 return s->max_size;
2479}
2480
2481static void udp_chr_read(void *opaque)
2482{
2483 CharDriverState *chr = opaque;
2484 NetCharDriver *s = chr->opaque;
2485
2486 if (s->max_size == 0)
2487 return;
2488 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2489 s->bufptr = s->bufcnt;
2490 if (s->bufcnt <= 0)
2491 return;
2492
2493 s->bufptr = 0;
2494 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
e5b0bc44 2495 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
0bab00f3 2496 s->bufptr++;
e5b0bc44 2497 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
2498 }
2499}
2500
e5b0bc44 2501static void udp_chr_update_read_handler(CharDriverState *chr)
0bab00f3
FB
2502{
2503 NetCharDriver *s = chr->opaque;
2504
2505 if (s->fd >= 0) {
0bab00f3
FB
2506 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2507 udp_chr_read, NULL, chr);
2508 }
2509}
2510
2511int parse_host_port(struct sockaddr_in *saddr, const char *str);
52f61fde
TS
2512#ifndef _WIN32
2513static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2514#endif
951f1351
FB
2515int parse_host_src_port(struct sockaddr_in *haddr,
2516 struct sockaddr_in *saddr,
2517 const char *str);
0bab00f3 2518
52f61fde 2519static CharDriverState *qemu_chr_open_udp(const char *def)
0bab00f3
FB
2520{
2521 CharDriverState *chr = NULL;
2522 NetCharDriver *s = NULL;
2523 int fd = -1;
951f1351 2524 struct sockaddr_in saddr;
0bab00f3
FB
2525
2526 chr = qemu_mallocz(sizeof(CharDriverState));
2527 if (!chr)
2528 goto return_err;
2529 s = qemu_mallocz(sizeof(NetCharDriver));
2530 if (!s)
2531 goto return_err;
2532
2533 fd = socket(PF_INET, SOCK_DGRAM, 0);
2534 if (fd < 0) {
2535 perror("socket(PF_INET, SOCK_DGRAM)");
2536 goto return_err;
2537 }
2538
951f1351
FB
2539 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2540 printf("Could not parse: %s\n", def);
2541 goto return_err;
0bab00f3
FB
2542 }
2543
951f1351 2544 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
0bab00f3
FB
2545 {
2546 perror("bind");
2547 goto return_err;
2548 }
2549
2550 s->fd = fd;
2551 s->bufcnt = 0;
2552 s->bufptr = 0;
2553 chr->opaque = s;
2554 chr->chr_write = udp_chr_write;
e5b0bc44 2555 chr->chr_update_read_handler = udp_chr_update_read_handler;
0bab00f3
FB
2556 return chr;
2557
2558return_err:
2559 if (chr)
2560 free(chr);
2561 if (s)
2562 free(s);
2563 if (fd >= 0)
2564 closesocket(fd);
2565 return NULL;
2566}
2567
2568/***********************************************************/
2569/* TCP Net console */
2570
2571typedef struct {
0bab00f3
FB
2572 int fd, listen_fd;
2573 int connected;
2574 int max_size;
951f1351 2575 int do_telnetopt;
e5b0bc44 2576 int do_nodelay;
ffd843bc 2577 int is_unix;
0bab00f3
FB
2578} TCPCharDriver;
2579
2580static void tcp_chr_accept(void *opaque);
2581
2582static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2583{
2584 TCPCharDriver *s = chr->opaque;
2585 if (s->connected) {
2586 return send_all(s->fd, buf, len);
2587 } else {
2588 /* XXX: indicate an error ? */
2589 return len;
2590 }
2591}
2592
2593static int tcp_chr_read_poll(void *opaque)
2594{
2595 CharDriverState *chr = opaque;
2596 TCPCharDriver *s = chr->opaque;
2597 if (!s->connected)
2598 return 0;
e5b0bc44 2599 s->max_size = qemu_chr_can_read(chr);
0bab00f3
FB
2600 return s->max_size;
2601}
2602
951f1351
FB
2603#define IAC 255
2604#define IAC_BREAK 243
2605static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2606 TCPCharDriver *s,
2607 char *buf, int *size)
2608{
2609 /* Handle any telnet client's basic IAC options to satisfy char by
2610 * char mode with no echo. All IAC options will be removed from
2611 * the buf and the do_telnetopt variable will be used to track the
2612 * state of the width of the IAC information.
2613 *
2614 * IAC commands come in sets of 3 bytes with the exception of the
2615 * "IAC BREAK" command and the double IAC.
2616 */
2617
2618 int i;
2619 int j = 0;
2620
2621 for (i = 0; i < *size; i++) {
2622 if (s->do_telnetopt > 1) {
2623 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2624 /* Double IAC means send an IAC */
2625 if (j != i)
2626 buf[j] = buf[i];
2627 j++;
2628 s->do_telnetopt = 1;
2629 } else {
2630 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2631 /* Handle IAC break commands by sending a serial break */
e5b0bc44 2632 qemu_chr_event(chr, CHR_EVENT_BREAK);
951f1351
FB
2633 s->do_telnetopt++;
2634 }
2635 s->do_telnetopt++;
2636 }
2637 if (s->do_telnetopt >= 4) {
2638 s->do_telnetopt = 1;
2639 }
2640 } else {
2641 if ((unsigned char)buf[i] == IAC) {
2642 s->do_telnetopt = 2;
2643 } else {
2644 if (j != i)
2645 buf[j] = buf[i];
2646 j++;
2647 }
2648 }
2649 }
2650 *size = j;
2651}
2652
0bab00f3
FB
2653static void tcp_chr_read(void *opaque)
2654{
2655 CharDriverState *chr = opaque;
2656 TCPCharDriver *s = chr->opaque;
2657 uint8_t buf[1024];
2658 int len, size;
2659
2660 if (!s->connected || s->max_size <= 0)
2661 return;
2662 len = sizeof(buf);
2663 if (len > s->max_size)
2664 len = s->max_size;
2665 size = recv(s->fd, buf, len, 0);
2666 if (size == 0) {
2667 /* connection closed */
2668 s->connected = 0;
2669 if (s->listen_fd >= 0) {
2670 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2671 }
2672 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2673 closesocket(s->fd);
2674 s->fd = -1;
2675 } else if (size > 0) {
951f1351
FB
2676 if (s->do_telnetopt)
2677 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2678 if (size > 0)
e5b0bc44 2679 qemu_chr_read(chr, buf, size);
0bab00f3
FB
2680 }
2681}
2682
0bab00f3
FB
2683static void tcp_chr_connect(void *opaque)
2684{
2685 CharDriverState *chr = opaque;
2686 TCPCharDriver *s = chr->opaque;
2687
2688 s->connected = 1;
2689 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2690 tcp_chr_read, NULL, chr);
86e94dea 2691 qemu_chr_reset(chr);
0bab00f3
FB
2692}
2693
951f1351
FB
2694#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2695static void tcp_chr_telnet_init(int fd)
2696{
2697 char buf[3];
2698 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2699 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2700 send(fd, (char *)buf, 3, 0);
2701 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2702 send(fd, (char *)buf, 3, 0);
2703 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2704 send(fd, (char *)buf, 3, 0);
2705 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2706 send(fd, (char *)buf, 3, 0);
2707}
2708
f7499989
PB
2709static void socket_set_nodelay(int fd)
2710{
2711 int val = 1;
2712 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2713}
2714
0bab00f3
FB
2715static void tcp_chr_accept(void *opaque)
2716{
2717 CharDriverState *chr = opaque;
2718 TCPCharDriver *s = chr->opaque;
2719 struct sockaddr_in saddr;
ffd843bc
TS
2720#ifndef _WIN32
2721 struct sockaddr_un uaddr;
2722#endif
2723 struct sockaddr *addr;
0bab00f3
FB
2724 socklen_t len;
2725 int fd;
2726
2727 for(;;) {
ffd843bc
TS
2728#ifndef _WIN32
2729 if (s->is_unix) {
2730 len = sizeof(uaddr);
2731 addr = (struct sockaddr *)&uaddr;
2732 } else
2733#endif
2734 {
2735 len = sizeof(saddr);
2736 addr = (struct sockaddr *)&saddr;
2737 }
2738 fd = accept(s->listen_fd, addr, &len);
0bab00f3
FB
2739 if (fd < 0 && errno != EINTR) {
2740 return;
2741 } else if (fd >= 0) {
951f1351
FB
2742 if (s->do_telnetopt)
2743 tcp_chr_telnet_init(fd);
0bab00f3
FB
2744 break;
2745 }
2746 }
2747 socket_set_nonblock(fd);
f7499989
PB
2748 if (s->do_nodelay)
2749 socket_set_nodelay(fd);
0bab00f3
FB
2750 s->fd = fd;
2751 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2752 tcp_chr_connect(chr);
2753}
2754
2755static void tcp_chr_close(CharDriverState *chr)
2756{
2757 TCPCharDriver *s = chr->opaque;
2758 if (s->fd >= 0)
2759 closesocket(s->fd);
2760 if (s->listen_fd >= 0)
2761 closesocket(s->listen_fd);
2762 qemu_free(s);
2763}
2764
2765static CharDriverState *qemu_chr_open_tcp(const char *host_str,
ffd843bc
TS
2766 int is_telnet,
2767 int is_unix)
0bab00f3
FB
2768{
2769 CharDriverState *chr = NULL;
2770 TCPCharDriver *s = NULL;
2771 int fd = -1, ret, err, val;
951f1351
FB
2772 int is_listen = 0;
2773 int is_waitconnect = 1;
f7499989 2774 int do_nodelay = 0;
951f1351 2775 const char *ptr;
0bab00f3 2776 struct sockaddr_in saddr;
ffd843bc
TS
2777#ifndef _WIN32
2778 struct sockaddr_un uaddr;
2779#endif
2780 struct sockaddr *addr;
2781 socklen_t addrlen;
0bab00f3 2782
ffd843bc
TS
2783#ifndef _WIN32
2784 if (is_unix) {
2785 addr = (struct sockaddr *)&uaddr;
2786 addrlen = sizeof(uaddr);
2787 if (parse_unix_path(&uaddr, host_str) < 0)
2788 goto fail;
2789 } else
2790#endif
2791 {
2792 addr = (struct sockaddr *)&saddr;
2793 addrlen = sizeof(saddr);
2794 if (parse_host_port(&saddr, host_str) < 0)
2795 goto fail;
2796 }
0bab00f3 2797
951f1351
FB
2798 ptr = host_str;
2799 while((ptr = strchr(ptr,','))) {
2800 ptr++;
2801 if (!strncmp(ptr,"server",6)) {
2802 is_listen = 1;
2803 } else if (!strncmp(ptr,"nowait",6)) {
2804 is_waitconnect = 0;
f7499989
PB
2805 } else if (!strncmp(ptr,"nodelay",6)) {
2806 do_nodelay = 1;
951f1351
FB
2807 } else {
2808 printf("Unknown option: %s\n", ptr);
2809 goto fail;
2810 }
2811 }
2812 if (!is_listen)
2813 is_waitconnect = 0;
2814
0bab00f3
FB
2815 chr = qemu_mallocz(sizeof(CharDriverState));
2816 if (!chr)
2817 goto fail;
2818 s = qemu_mallocz(sizeof(TCPCharDriver));
2819 if (!s)
2820 goto fail;
ffd843bc
TS
2821
2822#ifndef _WIN32
2823 if (is_unix)
2824 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2825 else
2826#endif
2827 fd = socket(PF_INET, SOCK_STREAM, 0);
2828
0bab00f3
FB
2829 if (fd < 0)
2830 goto fail;
951f1351
FB
2831
2832 if (!is_waitconnect)
2833 socket_set_nonblock(fd);
0bab00f3
FB
2834
2835 s->connected = 0;
2836 s->fd = -1;
2837 s->listen_fd = -1;
ffd843bc 2838 s->is_unix = is_unix;
f7499989 2839 s->do_nodelay = do_nodelay && !is_unix;
ffd843bc
TS
2840
2841 chr->opaque = s;
2842 chr->chr_write = tcp_chr_write;
ffd843bc
TS
2843 chr->chr_close = tcp_chr_close;
2844
0bab00f3
FB
2845 if (is_listen) {
2846 /* allow fast reuse */
ffd843bc
TS
2847#ifndef _WIN32
2848 if (is_unix) {
2849 char path[109];
2850 strncpy(path, uaddr.sun_path, 108);
2851 path[108] = 0;
2852 unlink(path);
2853 } else
2854#endif
2855 {
2856 val = 1;
2857 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2858 }
0bab00f3 2859
ffd843bc
TS
2860 ret = bind(fd, addr, addrlen);
2861 if (ret < 0)
0bab00f3 2862 goto fail;
ffd843bc 2863
0bab00f3
FB
2864 ret = listen(fd, 0);
2865 if (ret < 0)
2866 goto fail;
ffd843bc 2867
0bab00f3
FB
2868 s->listen_fd = fd;
2869 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
951f1351
FB
2870 if (is_telnet)
2871 s->do_telnetopt = 1;
0bab00f3
FB
2872 } else {
2873 for(;;) {
ffd843bc 2874 ret = connect(fd, addr, addrlen);
0bab00f3
FB
2875 if (ret < 0) {
2876 err = socket_error();
2877 if (err == EINTR || err == EWOULDBLOCK) {
2878 } else if (err == EINPROGRESS) {
2879 break;
f5b12268
TS
2880#ifdef _WIN32
2881 } else if (err == WSAEALREADY) {
2882 break;
2883#endif
0bab00f3
FB
2884 } else {
2885 goto fail;
2886 }
2887 } else {
2888 s->connected = 1;
2889 break;
2890 }
2891 }
2892 s->fd = fd;
f7499989 2893 socket_set_nodelay(fd);
0bab00f3
FB
2894 if (s->connected)
2895 tcp_chr_connect(chr);
2896 else
2897 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2898 }
2899
951f1351
FB
2900 if (is_listen && is_waitconnect) {
2901 printf("QEMU waiting for connection on: %s\n", host_str);
2902 tcp_chr_accept(chr);
2903 socket_set_nonblock(s->listen_fd);
2904 }
2905
0bab00f3
FB
2906 return chr;
2907 fail:
2908 if (fd >= 0)
2909 closesocket(fd);
2910 qemu_free(s);
2911 qemu_free(chr);
2912 return NULL;
2913}
2914
82c643ff
FB
2915CharDriverState *qemu_chr_open(const char *filename)
2916{
f8d179e3 2917 const char *p;
fd1dff4b 2918
82c643ff
FB
2919 if (!strcmp(filename, "vc")) {
2920 return text_console_init(&display_state);
2921 } else if (!strcmp(filename, "null")) {
2922 return qemu_chr_open_null();
7664728b 2923 } else
0bab00f3 2924 if (strstart(filename, "tcp:", &p)) {
ffd843bc 2925 return qemu_chr_open_tcp(p, 0, 0);
0bab00f3 2926 } else
951f1351 2927 if (strstart(filename, "telnet:", &p)) {
ffd843bc 2928 return qemu_chr_open_tcp(p, 1, 0);
0bab00f3
FB
2929 } else
2930 if (strstart(filename, "udp:", &p)) {
2931 return qemu_chr_open_udp(p);
2932 } else
20d8a3ed
TS
2933 if (strstart(filename, "mon:", &p)) {
2934 CharDriverState *drv = qemu_chr_open(p);
2935 if (drv) {
2936 drv = qemu_chr_open_mux(drv);
2937 monitor_init(drv, !nographic);
2938 return drv;
2939 }
2940 printf("Unable to open driver: %s\n", p);
2941 return 0;
2942 } else
7664728b 2943#ifndef _WIN32
ffd843bc
TS
2944 if (strstart(filename, "unix:", &p)) {
2945 return qemu_chr_open_tcp(p, 0, 1);
2946 } else if (strstart(filename, "file:", &p)) {
f8d179e3
FB
2947 return qemu_chr_open_file_out(p);
2948 } else if (strstart(filename, "pipe:", &p)) {
2949 return qemu_chr_open_pipe(p);
7664728b 2950 } else if (!strcmp(filename, "pty")) {
82c643ff
FB
2951 return qemu_chr_open_pty();
2952 } else if (!strcmp(filename, "stdio")) {
2953 return qemu_chr_open_stdio();
2954 } else
f8d179e3
FB
2955#endif
2956#if defined(__linux__)
e57a8c0e
FB
2957 if (strstart(filename, "/dev/parport", NULL)) {
2958 return qemu_chr_open_pp(filename);
2959 } else
f8d179e3
FB
2960 if (strstart(filename, "/dev/", NULL)) {
2961 return qemu_chr_open_tty(filename);
2962 } else
f331110f
FB
2963#endif
2964#ifdef _WIN32
2965 if (strstart(filename, "COM", NULL)) {
2966 return qemu_chr_open_win(filename);
2967 } else
2968 if (strstart(filename, "pipe:", &p)) {
2969 return qemu_chr_open_win_pipe(p);
2970 } else
72d46479
TS
2971 if (strstart(filename, "con:", NULL)) {
2972 return qemu_chr_open_win_con(filename);
2973 } else
f331110f
FB
2974 if (strstart(filename, "file:", &p)) {
2975 return qemu_chr_open_win_file_out(p);
2976 }
82c643ff
FB
2977#endif
2978 {
2979 return NULL;
2980 }
2981}
2982
f331110f
FB
2983void qemu_chr_close(CharDriverState *chr)
2984{
2985 if (chr->chr_close)
2986 chr->chr_close(chr);
2987}
2988
80cabfad 2989/***********************************************************/
7c9d8e07 2990/* network device redirectors */
330d0414 2991
c20709aa
FB
2992void hex_dump(FILE *f, const uint8_t *buf, int size)
2993{
2994 int len, i, j, c;
2995
2996 for(i=0;i<size;i+=16) {
2997 len = size - i;
2998 if (len > 16)
2999 len = 16;
3000 fprintf(f, "%08x ", i);
3001 for(j=0;j<16;j++) {
3002 if (j < len)
3003 fprintf(f, " %02x", buf[i+j]);
3004 else
3005 fprintf(f, " ");
3006 }
3007 fprintf(f, " ");
3008 for(j=0;j<len;j++) {
3009 c = buf[i+j];
3010 if (c < ' ' || c > '~')
3011 c = '.';
3012 fprintf(f, "%c", c);
3013 }
3014 fprintf(f, "\n");
3015 }
3016}
3017
7c9d8e07 3018static int parse_macaddr(uint8_t *macaddr, const char *p)
c20709aa 3019{
7c9d8e07
FB
3020 int i;
3021 for(i = 0; i < 6; i++) {
3022 macaddr[i] = strtol(p, (char **)&p, 16);
3023 if (i == 5) {
3024 if (*p != '\0')
3025 return -1;
3026 } else {
3027 if (*p != ':')
3028 return -1;
3029 p++;
3030 }
3031 }
3032 return 0;
c20709aa 3033}
67b915a5 3034
7c9d8e07 3035static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
67b915a5 3036{
7c9d8e07
FB
3037 const char *p, *p1;
3038 int len;
3039 p = *pp;
3040 p1 = strchr(p, sep);
3041 if (!p1)
3042 return -1;
3043 len = p1 - p;
3044 p1++;
3045 if (buf_size > 0) {
3046 if (len > buf_size - 1)
3047 len = buf_size - 1;
3048 memcpy(buf, p, len);
3049 buf[len] = '\0';
3050 }
3051 *pp = p1;
3052 return 0;
c20709aa
FB
3053}
3054
951f1351
FB
3055int parse_host_src_port(struct sockaddr_in *haddr,
3056 struct sockaddr_in *saddr,
3057 const char *input_str)
3058{
3059 char *str = strdup(input_str);
3060 char *host_str = str;
3061 char *src_str;
3062 char *ptr;
3063
3064 /*
3065 * Chop off any extra arguments at the end of the string which
3066 * would start with a comma, then fill in the src port information
3067 * if it was provided else use the "any address" and "any port".
3068 */
3069 if ((ptr = strchr(str,',')))
3070 *ptr = '\0';
3071
3072 if ((src_str = strchr(input_str,'@'))) {
3073 *src_str = '\0';
3074 src_str++;
3075 }
3076
3077 if (parse_host_port(haddr, host_str) < 0)
3078 goto fail;
3079
3080 if (!src_str || *src_str == '\0')
3081 src_str = ":0";
3082
3083 if (parse_host_port(saddr, src_str) < 0)
3084 goto fail;
3085
3086 free(str);
3087 return(0);
3088
3089fail:
3090 free(str);
3091 return -1;
3092}
3093
7c9d8e07
FB
3094int parse_host_port(struct sockaddr_in *saddr, const char *str)
3095{
3096 char buf[512];
3097 struct hostent *he;
3098 const char *p, *r;
3099 int port;
3100
3101 p = str;
3102 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3103 return -1;
3104 saddr->sin_family = AF_INET;
3105 if (buf[0] == '\0') {
3106 saddr->sin_addr.s_addr = 0;
3107 } else {
3108 if (isdigit(buf[0])) {
3109 if (!inet_aton(buf, &saddr->sin_addr))
3110 return -1;
3111 } else {
7c9d8e07
FB
3112 if ((he = gethostbyname(buf)) == NULL)
3113 return - 1;
3114 saddr->sin_addr = *(struct in_addr *)he->h_addr;
7c9d8e07
FB
3115 }
3116 }
3117 port = strtol(p, (char **)&r, 0);
3118 if (r == p)
3119 return -1;
3120 saddr->sin_port = htons(port);
3121 return 0;
3122}
c20709aa 3123
52f61fde
TS
3124#ifndef _WIN32
3125static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
ffd843bc
TS
3126{
3127 const char *p;
3128 int len;
3129
3130 len = MIN(108, strlen(str));
3131 p = strchr(str, ',');
3132 if (p)
3133 len = MIN(len, p - str);
3134
3135 memset(uaddr, 0, sizeof(*uaddr));
3136
3137 uaddr->sun_family = AF_UNIX;
3138 memcpy(uaddr->sun_path, str, len);
3139
3140 return 0;
3141}
52f61fde 3142#endif
ffd843bc 3143
7c9d8e07
FB
3144/* find or alloc a new VLAN */
3145VLANState *qemu_find_vlan(int id)
c20709aa 3146{
7c9d8e07
FB
3147 VLANState **pvlan, *vlan;
3148 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3149 if (vlan->id == id)
3150 return vlan;
3151 }
3152 vlan = qemu_mallocz(sizeof(VLANState));
3153 if (!vlan)
3154 return NULL;
3155 vlan->id = id;
3156 vlan->next = NULL;
3157 pvlan = &first_vlan;
3158 while (*pvlan != NULL)
3159 pvlan = &(*pvlan)->next;
3160 *pvlan = vlan;
3161 return vlan;
c20709aa
FB
3162}
3163
7c9d8e07 3164VLANClientState *qemu_new_vlan_client(VLANState *vlan,
d861b05e
PB
3165 IOReadHandler *fd_read,
3166 IOCanRWHandler *fd_can_read,
3167 void *opaque)
c20709aa 3168{
7c9d8e07
FB
3169 VLANClientState *vc, **pvc;
3170 vc = qemu_mallocz(sizeof(VLANClientState));
3171 if (!vc)
3172 return NULL;
3173 vc->fd_read = fd_read;
d861b05e 3174 vc->fd_can_read = fd_can_read;
7c9d8e07
FB
3175 vc->opaque = opaque;
3176 vc->vlan = vlan;
3177
3178 vc->next = NULL;
3179 pvc = &vlan->first_client;
3180 while (*pvc != NULL)
3181 pvc = &(*pvc)->next;
3182 *pvc = vc;
3183 return vc;
c20709aa
FB
3184}
3185
d861b05e
PB
3186int qemu_can_send_packet(VLANClientState *vc1)
3187{
3188 VLANState *vlan = vc1->vlan;
3189 VLANClientState *vc;
3190
3191 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3192 if (vc != vc1) {
3193 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3194 return 0;
3195 }
3196 }
3197 return 1;
3198}
3199
7c9d8e07 3200void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
c20709aa 3201{
7c9d8e07
FB
3202 VLANState *vlan = vc1->vlan;
3203 VLANClientState *vc;
3204
3205#if 0
3206 printf("vlan %d send:\n", vlan->id);
3207 hex_dump(stdout, buf, size);
3208#endif
3209 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3210 if (vc != vc1) {
3211 vc->fd_read(vc->opaque, buf, size);
3212 }
3213 }
67b915a5
FB
3214}
3215
c20709aa
FB
3216#if defined(CONFIG_SLIRP)
3217
3218/* slirp network adapter */
3219
c20709aa 3220static int slirp_inited;
7c9d8e07 3221static VLANClientState *slirp_vc;
c20709aa
FB
3222
3223int slirp_can_output(void)
3224{
3b7f5d47 3225 return !slirp_vc || qemu_can_send_packet(slirp_vc);
c20709aa
FB
3226}
3227
3228void slirp_output(const uint8_t *pkt, int pkt_len)
67b915a5 3229{
c20709aa 3230#if 0
7c9d8e07 3231 printf("slirp output:\n");
c20709aa
FB
3232 hex_dump(stdout, pkt, pkt_len);
3233#endif
3b7f5d47
PB
3234 if (!slirp_vc)
3235 return;
7c9d8e07 3236 qemu_send_packet(slirp_vc, pkt, pkt_len);
67b915a5
FB
3237}
3238
7c9d8e07 3239static void slirp_receive(void *opaque, const uint8_t *buf, int size)
c20709aa
FB
3240{
3241#if 0
7c9d8e07 3242 printf("slirp input:\n");
c20709aa
FB
3243 hex_dump(stdout, buf, size);
3244#endif
3245 slirp_input(buf, size);
3246}
3247
7c9d8e07 3248static int net_slirp_init(VLANState *vlan)
c20709aa
FB
3249{
3250 if (!slirp_inited) {
3251 slirp_inited = 1;
3252 slirp_init();
3253 }
7c9d8e07 3254 slirp_vc = qemu_new_vlan_client(vlan,
d861b05e 3255 slirp_receive, NULL, NULL);
7c9d8e07 3256 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
9bf05444
FB
3257 return 0;
3258}
3259
3260static void net_slirp_redir(const char *redir_str)
3261{
3262 int is_udp;
3263 char buf[256], *r;
3264 const char *p;
3265 struct in_addr guest_addr;
3266 int host_port, guest_port;
3267
3268 if (!slirp_inited) {
3269 slirp_inited = 1;
3270 slirp_init();
3271 }
3272
3273 p = redir_str;
3274 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3275 goto fail;
3276 if (!strcmp(buf, "tcp")) {
3277 is_udp = 0;
3278 } else if (!strcmp(buf, "udp")) {
3279 is_udp = 1;
3280 } else {
3281 goto fail;
3282 }
3283
3284 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3285 goto fail;
3286 host_port = strtol(buf, &r, 0);
3287 if (r == buf)
3288 goto fail;
3289
3290 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3291 goto fail;
3292 if (buf[0] == '\0') {
3293 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3294 }
3295 if (!inet_aton(buf, &guest_addr))
3296 goto fail;
3297
3298 guest_port = strtol(p, &r, 0);
3299 if (r == p)
3300 goto fail;
3301
3302 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3303 fprintf(stderr, "qemu: could not set up redirection\n");
3304 exit(1);
3305 }
3306 return;
3307 fail:
3308 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3309 exit(1);
3310}
9d728e8c 3311
c94c8d64
FB
3312#ifndef _WIN32
3313
9d728e8c
FB
3314char smb_dir[1024];
3315
3316static void smb_exit(void)
3317{
3318 DIR *d;
3319 struct dirent *de;
3320 char filename[1024];
3321
3322 /* erase all the files in the directory */
3323 d = opendir(smb_dir);
3324 for(;;) {
3325 de = readdir(d);
3326 if (!de)
3327 break;
3328 if (strcmp(de->d_name, ".") != 0 &&
3329 strcmp(de->d_name, "..") != 0) {
3330 snprintf(filename, sizeof(filename), "%s/%s",
3331 smb_dir, de->d_name);
3332 unlink(filename);
3333 }
3334 }
03ffbb69 3335 closedir(d);
9d728e8c
FB
3336 rmdir(smb_dir);
3337}
3338
3339/* automatic user mode samba server configuration */
3340void net_slirp_smb(const char *exported_dir)
3341{
3342 char smb_conf[1024];
3343 char smb_cmdline[1024];
3344 FILE *f;
3345
3346 if (!slirp_inited) {
3347 slirp_inited = 1;
3348 slirp_init();
3349 }
3350
3351 /* XXX: better tmp dir construction */
3352 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3353 if (mkdir(smb_dir, 0700) < 0) {
3354 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3355 exit(1);
3356 }
3357 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3358
3359 f = fopen(smb_conf, "w");
3360 if (!f) {
3361 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3362 exit(1);
3363 }
3364 fprintf(f,
3365 "[global]\n"
157777ef
FB
3366 "private dir=%s\n"
3367 "smb ports=0\n"
3368 "socket address=127.0.0.1\n"
9d728e8c
FB
3369 "pid directory=%s\n"
3370 "lock directory=%s\n"
3371 "log file=%s/log.smbd\n"
3372 "smb passwd file=%s/smbpasswd\n"
03ffbb69 3373 "security = share\n"
9d728e8c
FB
3374 "[qemu]\n"
3375 "path=%s\n"
3376 "read only=no\n"
3377 "guest ok=yes\n",
3378 smb_dir,
157777ef 3379 smb_dir,
9d728e8c
FB
3380 smb_dir,
3381 smb_dir,
3382 smb_dir,
3383 exported_dir
3384 );
3385 fclose(f);
3386 atexit(smb_exit);
3387
a14d6c8c
PB
3388 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3389 SMBD_COMMAND, smb_conf);
9d728e8c
FB
3390
3391 slirp_add_exec(0, smb_cmdline, 4, 139);
3392}
9bf05444 3393
c94c8d64
FB
3394#endif /* !defined(_WIN32) */
3395
c20709aa
FB
3396#endif /* CONFIG_SLIRP */
3397
3398#if !defined(_WIN32)
7c9d8e07
FB
3399
3400typedef struct TAPState {
3401 VLANClientState *vc;
3402 int fd;
3403} TAPState;
3404
3405static void tap_receive(void *opaque, const uint8_t *buf, int size)
3406{
3407 TAPState *s = opaque;
3408 int ret;
3409 for(;;) {
3410 ret = write(s->fd, buf, size);
3411 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3412 } else {
3413 break;
3414 }
3415 }
3416}
3417
3418static void tap_send(void *opaque)
3419{
3420 TAPState *s = opaque;
3421 uint8_t buf[4096];
3422 int size;
3423
d5d10bc3
TS
3424#ifdef __sun__
3425 struct strbuf sbuf;
3426 int f = 0;
3427 sbuf.maxlen = sizeof(buf);
3428 sbuf.buf = buf;
3429 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3430#else
7c9d8e07 3431 size = read(s->fd, buf, sizeof(buf));
d5d10bc3 3432#endif
7c9d8e07
FB
3433 if (size > 0) {
3434 qemu_send_packet(s->vc, buf, size);
3435 }
3436}
3437
3438/* fd support */
3439
3440static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3441{
3442 TAPState *s;
3443
3444 s = qemu_mallocz(sizeof(TAPState));
3445 if (!s)
3446 return NULL;
3447 s->fd = fd;
d861b05e 3448 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
7c9d8e07
FB
3449 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3450 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3451 return s;
3452}
3453
7d3505c5 3454#ifdef _BSD
7c9d8e07 3455static int tap_open(char *ifname, int ifname_size)
7d3505c5
FB
3456{
3457 int fd;
3458 char *dev;
3459 struct stat s;
67b915a5 3460
7d3505c5
FB
3461 fd = open("/dev/tap", O_RDWR);
3462 if (fd < 0) {
3463 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3464 return -1;
3465 }
3466
3467 fstat(fd, &s);
3468 dev = devname(s.st_rdev, S_IFCHR);
3469 pstrcpy(ifname, ifname_size, dev);
3470
3471 fcntl(fd, F_SETFL, O_NONBLOCK);
3472 return fd;
3473}
ec530c81 3474#elif defined(__sun__)
d5d10bc3
TS
3475#define TUNNEWPPA (('T'<<16) | 0x0001)
3476/*
3477 * Allocate TAP device, returns opened fd.
3478 * Stores dev name in the first arg(must be large enough).
3479 */
3480int tap_alloc(char *dev)
3481{
3482 int tap_fd, if_fd, ppa = -1;
3483 static int ip_fd = 0;
3484 char *ptr;
3485
3486 static int arp_fd = 0;
3487 int ip_muxid, arp_muxid;
3488 struct strioctl strioc_if, strioc_ppa;
3489 int link_type = I_PLINK;;
3490 struct lifreq ifr;
3491 char actual_name[32] = "";
3492
3493 memset(&ifr, 0x0, sizeof(ifr));
3494
3495 if( *dev ){
3496 ptr = dev;
3497 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3498 ppa = atoi(ptr);
3499 }
3500
3501 /* Check if IP device was opened */
3502 if( ip_fd )
3503 close(ip_fd);
3504
3505 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3506 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3507 return -1;
3508 }
3509
3510 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3511 syslog(LOG_ERR, "Can't open /dev/tap");
3512 return -1;
3513 }
3514
3515 /* Assign a new PPA and get its unit number. */
3516 strioc_ppa.ic_cmd = TUNNEWPPA;
3517 strioc_ppa.ic_timout = 0;
3518 strioc_ppa.ic_len = sizeof(ppa);
3519 strioc_ppa.ic_dp = (char *)&ppa;
3520 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3521 syslog (LOG_ERR, "Can't assign new interface");
3522
3523 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3524 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3525 return -1;
3526 }
3527 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3528 syslog(LOG_ERR, "Can't push IP module");
3529 return -1;
3530 }
3531
3532 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3533 syslog(LOG_ERR, "Can't get flags\n");
3534
3535 snprintf (actual_name, 32, "tap%d", ppa);
3536 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3537
3538 ifr.lifr_ppa = ppa;
3539 /* Assign ppa according to the unit number returned by tun device */
3540
3541 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3542 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3543 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3544 syslog (LOG_ERR, "Can't get flags\n");
3545 /* Push arp module to if_fd */
3546 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3547 syslog (LOG_ERR, "Can't push ARP module (2)");
3548
3549 /* Push arp module to ip_fd */
3550 if (ioctl (ip_fd, I_POP, NULL) < 0)
3551 syslog (LOG_ERR, "I_POP failed\n");
3552 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3553 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3554 /* Open arp_fd */
3555 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3556 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3557
3558 /* Set ifname to arp */
3559 strioc_if.ic_cmd = SIOCSLIFNAME;
3560 strioc_if.ic_timout = 0;
3561 strioc_if.ic_len = sizeof(ifr);
3562 strioc_if.ic_dp = (char *)&ifr;
3563 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3564 syslog (LOG_ERR, "Can't set ifname to arp\n");
3565 }
3566
3567 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3568 syslog(LOG_ERR, "Can't link TAP device to IP");
3569 return -1;
3570 }
3571
3572 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3573 syslog (LOG_ERR, "Can't link TAP device to ARP");
3574
3575 close (if_fd);
3576
3577 memset(&ifr, 0x0, sizeof(ifr));
3578 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3579 ifr.lifr_ip_muxid = ip_muxid;
3580 ifr.lifr_arp_muxid = arp_muxid;
3581
3582 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3583 {
3584 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3585 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3586 syslog (LOG_ERR, "Can't set multiplexor id");
3587 }
3588
3589 sprintf(dev, "tap%d", ppa);
3590 return tap_fd;
3591}
3592
ec530c81
FB
3593static int tap_open(char *ifname, int ifname_size)
3594{
d5d10bc3
TS
3595 char dev[10]="";
3596 int fd;
3597 if( (fd = tap_alloc(dev)) < 0 ){
3598 fprintf(stderr, "Cannot allocate TAP device\n");
3599 return -1;
3600 }
3601 pstrcpy(ifname, ifname_size, dev);
3602 fcntl(fd, F_SETFL, O_NONBLOCK);
3603 return fd;
ec530c81 3604}
7d3505c5 3605#else
7c9d8e07 3606static int tap_open(char *ifname, int ifname_size)
330d0414 3607{
80cabfad 3608 struct ifreq ifr;
c4b1fcc0 3609 int fd, ret;
80cabfad
FB
3610
3611 fd = open("/dev/net/tun", O_RDWR);
3612 if (fd < 0) {
3613 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3614 return -1;
330d0414 3615 }
80cabfad
FB
3616 memset(&ifr, 0, sizeof(ifr));
3617 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
7c9d8e07
FB
3618 if (ifname[0] != '\0')
3619 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3620 else
3621 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
80cabfad
FB
3622 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3623 if (ret != 0) {
3624 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3625 close(fd);
3626 return -1;
3627 }
c4b1fcc0 3628 pstrcpy(ifname, ifname_size, ifr.ifr_name);
80cabfad 3629 fcntl(fd, F_SETFL, O_NONBLOCK);
c4b1fcc0
FB
3630 return fd;
3631}
7d3505c5 3632#endif
330d0414 3633
7c9d8e07
FB
3634static int net_tap_init(VLANState *vlan, const char *ifname1,
3635 const char *setup_script)
3636{
3637 TAPState *s;
3638 int pid, status, fd;
3639 char *args[3];
3640 char **parg;
3641 char ifname[128];
3642
3643 if (ifname1 != NULL)
3644 pstrcpy(ifname, sizeof(ifname), ifname1);
3645 else
3646 ifname[0] = '\0';
3647 fd = tap_open(ifname, sizeof(ifname));
3648 if (fd < 0)
3649 return -1;
3650
6a1cbf68 3651 if (!setup_script || !strcmp(setup_script, "no"))
7c9d8e07
FB
3652 setup_script = "";
3653 if (setup_script[0] != '\0') {
3654 /* try to launch network init script */
3655 pid = fork();
3656 if (pid >= 0) {
3657 if (pid == 0) {
50d3eeae
TS
3658 int open_max = sysconf (_SC_OPEN_MAX), i;
3659 for (i = 0; i < open_max; i++)
3660 if (i != STDIN_FILENO &&
3661 i != STDOUT_FILENO &&
3662 i != STDERR_FILENO &&
3663 i != fd)
3664 close(i);
3665
7c9d8e07
FB
3666 parg = args;
3667 *parg++ = (char *)setup_script;
3668 *parg++ = ifname;
3669 *parg++ = NULL;
3670 execv(setup_script, args);
4a38940d 3671 _exit(1);
7c9d8e07
FB
3672 }
3673 while (waitpid(pid, &status, 0) != pid);
3674 if (!WIFEXITED(status) ||
3675 WEXITSTATUS(status) != 0) {
3676 fprintf(stderr, "%s: could not launch network script\n",
3677 setup_script);
3678 return -1;
3679 }
3680 }
3681 }
3682 s = net_tap_fd_init(vlan, fd);
3683 if (!s)
3684 return -1;
3685 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3686 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3687 return 0;
3688}
3689
fd1dff4b
FB
3690#endif /* !_WIN32 */
3691
7c9d8e07
FB
3692/* network connection */
3693typedef struct NetSocketState {
3694 VLANClientState *vc;
3695 int fd;
3696 int state; /* 0 = getting length, 1 = getting data */
3697 int index;
3698 int packet_len;
3699 uint8_t buf[4096];
3d830459 3700 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
7c9d8e07
FB
3701} NetSocketState;
3702
3703typedef struct NetSocketListenState {
3704 VLANState *vlan;
3705 int fd;
3706} NetSocketListenState;
3707
3708/* XXX: we consider we can send the whole packet without blocking */
3709static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
c20709aa 3710{
7c9d8e07
FB
3711 NetSocketState *s = opaque;
3712 uint32_t len;
3713 len = htonl(size);
3714
fd1dff4b
FB
3715 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3716 send_all(s->fd, buf, size);
c20709aa
FB
3717}
3718
3d830459
FB
3719static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3720{
3721 NetSocketState *s = opaque;
3722 sendto(s->fd, buf, size, 0,
3723 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3724}
3725
7c9d8e07 3726static void net_socket_send(void *opaque)
c4b1fcc0 3727{
7c9d8e07 3728 NetSocketState *s = opaque;
fd1dff4b 3729 int l, size, err;
7c9d8e07
FB
3730 uint8_t buf1[4096];
3731 const uint8_t *buf;
3732
fd1dff4b
FB
3733 size = recv(s->fd, buf1, sizeof(buf1), 0);
3734 if (size < 0) {
3735 err = socket_error();
3736 if (err != EWOULDBLOCK)
3737 goto eoc;
3738 } else if (size == 0) {
7c9d8e07 3739 /* end of connection */
fd1dff4b 3740 eoc:
7c9d8e07 3741 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
fd1dff4b 3742 closesocket(s->fd);
7c9d8e07
FB
3743 return;
3744 }
3745 buf = buf1;
3746 while (size > 0) {
3747 /* reassemble a packet from the network */
3748 switch(s->state) {
3749 case 0:
3750 l = 4 - s->index;
3751 if (l > size)
3752 l = size;
3753 memcpy(s->buf + s->index, buf, l);
3754 buf += l;
3755 size -= l;
3756 s->index += l;
3757 if (s->index == 4) {
3758 /* got length */
3759 s->packet_len = ntohl(*(uint32_t *)s->buf);
3760 s->index = 0;
3761 s->state = 1;
3762 }
3763 break;
3764 case 1:
3765 l = s->packet_len - s->index;
3766 if (l > size)
3767 l = size;
3768 memcpy(s->buf + s->index, buf, l);
3769 s->index += l;
3770 buf += l;
3771 size -= l;
3772 if (s->index >= s->packet_len) {
3773 qemu_send_packet(s->vc, s->buf, s->packet_len);
3774 s->index = 0;
3775 s->state = 0;
3776 }
3777 break;
3778 }
3779 }
c20709aa
FB
3780}
3781
3d830459
FB
3782static void net_socket_send_dgram(void *opaque)
3783{
3784 NetSocketState *s = opaque;
3785 int size;
3786
3787 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3788 if (size < 0)
3789 return;
3790 if (size == 0) {
3791 /* end of connection */
3792 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3793 return;
3794 }
3795 qemu_send_packet(s->vc, s->buf, size);
3796}
3797
3798static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3799{
3800 struct ip_mreq imr;
3801 int fd;
3802 int val, ret;
3803 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3804 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
fd1dff4b
FB
3805 inet_ntoa(mcastaddr->sin_addr),
3806 (int)ntohl(mcastaddr->sin_addr.s_addr));
3d830459
FB
3807 return -1;
3808
3809 }
3810 fd = socket(PF_INET, SOCK_DGRAM, 0);
3811 if (fd < 0) {
3812 perror("socket(PF_INET, SOCK_DGRAM)");
3813 return -1;
3814 }
3815
fd1dff4b
FB
3816 val = 1;
3817 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3818 (const char *)&val, sizeof(val));
3819 if (ret < 0) {
3820 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3821 goto fail;
3822 }
3823
3824 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3825 if (ret < 0) {
3826 perror("bind");
3827 goto fail;
3828 }
3829
3d830459
FB
3830 /* Add host to multicast group */
3831 imr.imr_multiaddr = mcastaddr->sin_addr;
3832 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3833
fd1dff4b
FB
3834 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3835 (const char *)&imr, sizeof(struct ip_mreq));
3d830459
FB
3836 if (ret < 0) {
3837 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3838 goto fail;
3839 }
3840
3841 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3842 val = 1;
fd1dff4b
FB
3843 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3844 (const char *)&val, sizeof(val));
3d830459
FB
3845 if (ret < 0) {
3846 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3847 goto fail;
3848 }
3849
fd1dff4b 3850 socket_set_nonblock(fd);
3d830459
FB
3851 return fd;
3852fail:
0bab00f3
FB
3853 if (fd >= 0)
3854 closesocket(fd);
3d830459
FB
3855 return -1;
3856}
3857
3858static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3859 int is_connected)
3860{
3861 struct sockaddr_in saddr;
3862 int newfd;
3863 socklen_t saddr_len;
3864 NetSocketState *s;
3865
3866 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3867 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3868 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3869 */
3870
3871 if (is_connected) {
3872 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3873 /* must be bound */
3874 if (saddr.sin_addr.s_addr==0) {
3875 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3876 fd);
3877 return NULL;
3878 }
3879 /* clone dgram socket */
3880 newfd = net_socket_mcast_create(&saddr);
3881 if (newfd < 0) {
3882 /* error already reported by net_socket_mcast_create() */
3883 close(fd);
3884 return NULL;
3885 }
3886 /* clone newfd to fd, close newfd */
3887 dup2(newfd, fd);
3888 close(newfd);
3889
3890 } else {
3891 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3892 fd, strerror(errno));
3893 return NULL;
3894 }
3895 }
3896
3897 s = qemu_mallocz(sizeof(NetSocketState));
3898 if (!s)
3899 return NULL;
3900 s->fd = fd;
3901
d861b05e 3902 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3d830459
FB
3903 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3904
3905 /* mcast: save bound address as dst */
3906 if (is_connected) s->dgram_dst=saddr;
3907
3908 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3909 "socket: fd=%d (%s mcast=%s:%d)",
3910 fd, is_connected? "cloned" : "",
3911 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3912 return s;
3913}
3914
7c9d8e07 3915static void net_socket_connect(void *opaque)
c20709aa 3916{
7c9d8e07
FB
3917 NetSocketState *s = opaque;
3918 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3919}
c4b1fcc0 3920
3d830459 3921static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
7c9d8e07
FB
3922 int is_connected)
3923{
3924 NetSocketState *s;
3925 s = qemu_mallocz(sizeof(NetSocketState));
3926 if (!s)
3927 return NULL;
3928 s->fd = fd;
3929 s->vc = qemu_new_vlan_client(vlan,
d861b05e 3930 net_socket_receive, NULL, s);
7c9d8e07
FB
3931 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3932 "socket: fd=%d", fd);
3933 if (is_connected) {
3934 net_socket_connect(s);
3935 } else {
3936 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3937 }
3938 return s;
3939}
c4b1fcc0 3940
3d830459
FB
3941static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3942 int is_connected)
3943{
3944 int so_type=-1, optlen=sizeof(so_type);
3945
fd1dff4b 3946 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
931f03ee 3947 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3d830459
FB
3948 return NULL;
3949 }
3950 switch(so_type) {
3951 case SOCK_DGRAM:
3952 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3953 case SOCK_STREAM:
3954 return net_socket_fd_init_stream(vlan, fd, is_connected);
3955 default:
3956 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3957 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3958 return net_socket_fd_init_stream(vlan, fd, is_connected);
3959 }
3960 return NULL;
3961}
3962
7c9d8e07
FB
3963static void net_socket_accept(void *opaque)
3964{
3965 NetSocketListenState *s = opaque;
3966 NetSocketState *s1;
3967 struct sockaddr_in saddr;
3968 socklen_t len;
3969 int fd;
3970
3971 for(;;) {
3972 len = sizeof(saddr);
3973 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3974 if (fd < 0 && errno != EINTR) {
3975 return;
3976 } else if (fd >= 0) {
3977 break;
80cabfad 3978 }
330d0414 3979 }
7c9d8e07
FB
3980 s1 = net_socket_fd_init(s->vlan, fd, 1);
3981 if (!s1) {
0bab00f3 3982 closesocket(fd);
7c9d8e07
FB
3983 } else {
3984 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3985 "socket: connection from %s:%d",
3986 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3987 }
3988}
3989
3990static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3991{
3992 NetSocketListenState *s;
3993 int fd, val, ret;
3994 struct sockaddr_in saddr;
3995
3996 if (parse_host_port(&saddr, host_str) < 0)
3997 return -1;
3998
3999 s = qemu_mallocz(sizeof(NetSocketListenState));
4000 if (!s)
4001 return -1;
4002
4003 fd = socket(PF_INET, SOCK_STREAM, 0);
4004 if (fd < 0) {
4005 perror("socket");
4006 return -1;
4007 }
fd1dff4b 4008 socket_set_nonblock(fd);
7c9d8e07
FB
4009
4010 /* allow fast reuse */
4011 val = 1;
fd1dff4b 4012 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
7c9d8e07
FB
4013
4014 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4015 if (ret < 0) {
4016 perror("bind");
4017 return -1;
4018 }
4019 ret = listen(fd, 0);
4020 if (ret < 0) {
4021 perror("listen");
4022 return -1;
4023 }
4024 s->vlan = vlan;
4025 s->fd = fd;
4026 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
80cabfad 4027 return 0;
330d0414
FB
4028}
4029
7c9d8e07 4030static int net_socket_connect_init(VLANState *vlan, const char *host_str)
330d0414 4031{
7c9d8e07 4032 NetSocketState *s;
fd1dff4b 4033 int fd, connected, ret, err;
7c9d8e07
FB
4034 struct sockaddr_in saddr;
4035
4036 if (parse_host_port(&saddr, host_str) < 0)
4037 return -1;
4038
4039 fd = socket(PF_INET, SOCK_STREAM, 0);
4040 if (fd < 0) {
4041 perror("socket");
4042 return -1;
4043 }
fd1dff4b 4044 socket_set_nonblock(fd);
7c9d8e07
FB
4045
4046 connected = 0;
4047 for(;;) {
4048 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4049 if (ret < 0) {
fd1dff4b
FB
4050 err = socket_error();
4051 if (err == EINTR || err == EWOULDBLOCK) {
4052 } else if (err == EINPROGRESS) {
7c9d8e07 4053 break;
f5b12268
TS
4054#ifdef _WIN32
4055 } else if (err == WSAEALREADY) {
4056 break;
4057#endif
7c9d8e07
FB
4058 } else {
4059 perror("connect");
fd1dff4b 4060 closesocket(fd);
7c9d8e07
FB
4061 return -1;
4062 }
4063 } else {
4064 connected = 1;
4065 break;
4066 }
4067 }
4068 s = net_socket_fd_init(vlan, fd, connected);
4069 if (!s)
4070 return -1;
4071 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4072 "socket: connect to %s:%d",
4073 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
c20709aa 4074 return 0;
80cabfad 4075}
330d0414 4076
3d830459
FB
4077static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4078{
4079 NetSocketState *s;
4080 int fd;
4081 struct sockaddr_in saddr;
4082
4083 if (parse_host_port(&saddr, host_str) < 0)
4084 return -1;
4085
4086
4087 fd = net_socket_mcast_create(&saddr);
4088 if (fd < 0)
4089 return -1;
4090
4091 s = net_socket_fd_init(vlan, fd, 0);
4092 if (!s)
4093 return -1;
4094
4095 s->dgram_dst = saddr;
4096
4097 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4098 "socket: mcast=%s:%d",
4099 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4100 return 0;
4101
4102}
4103
7c9d8e07
FB
4104static int get_param_value(char *buf, int buf_size,
4105 const char *tag, const char *str)
4106{
4107 const char *p;
4108 char *q;
4109 char option[128];
4110
4111 p = str;
4112 for(;;) {
4113 q = option;
4114 while (*p != '\0' && *p != '=') {
4115 if ((q - option) < sizeof(option) - 1)
4116 *q++ = *p;
4117 p++;
4118 }
4119 *q = '\0';
4120 if (*p != '=')
4121 break;
4122 p++;
4123 if (!strcmp(tag, option)) {
4124 q = buf;
4125 while (*p != '\0' && *p != ',') {
4126 if ((q - buf) < buf_size - 1)
4127 *q++ = *p;
4128 p++;
4129 }
4130 *q = '\0';
4131 return q - buf;
4132 } else {
4133 while (*p != '\0' && *p != ',') {
4134 p++;
4135 }
4136 }
4137 if (*p != ',')
4138 break;
4139 p++;
4140 }
4141 return 0;
4142}
4143
52f61fde 4144static int net_client_init(const char *str)
7c9d8e07
FB
4145{
4146 const char *p;
4147 char *q;
4148 char device[64];
4149 char buf[1024];
4150 int vlan_id, ret;
4151 VLANState *vlan;
4152
4153 p = str;
4154 q = device;
4155 while (*p != '\0' && *p != ',') {
4156 if ((q - device) < sizeof(device) - 1)
4157 *q++ = *p;
4158 p++;
4159 }
4160 *q = '\0';
4161 if (*p == ',')
4162 p++;
4163 vlan_id = 0;
4164 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4165 vlan_id = strtol(buf, NULL, 0);
4166 }
4167 vlan = qemu_find_vlan(vlan_id);
4168 if (!vlan) {
4169 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4170 return -1;
4171 }
4172 if (!strcmp(device, "nic")) {
4173 NICInfo *nd;
4174 uint8_t *macaddr;
4175
4176 if (nb_nics >= MAX_NICS) {
4177 fprintf(stderr, "Too Many NICs\n");
4178 return -1;
4179 }
4180 nd = &nd_table[nb_nics];
4181 macaddr = nd->macaddr;
4182 macaddr[0] = 0x52;
4183 macaddr[1] = 0x54;
4184 macaddr[2] = 0x00;
4185 macaddr[3] = 0x12;
4186 macaddr[4] = 0x34;
4187 macaddr[5] = 0x56 + nb_nics;
4188
4189 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4190 if (parse_macaddr(macaddr, buf) < 0) {
4191 fprintf(stderr, "invalid syntax for ethernet address\n");
4192 return -1;
4193 }
4194 }
a41b2ff2
PB
4195 if (get_param_value(buf, sizeof(buf), "model", p)) {
4196 nd->model = strdup(buf);
4197 }
7c9d8e07
FB
4198 nd->vlan = vlan;
4199 nb_nics++;
833c7174 4200 vlan->nb_guest_devs++;
7c9d8e07
FB
4201 ret = 0;
4202 } else
4203 if (!strcmp(device, "none")) {
4204 /* does nothing. It is needed to signal that no network cards
4205 are wanted */
4206 ret = 0;
4207 } else
4208#ifdef CONFIG_SLIRP
4209 if (!strcmp(device, "user")) {
115defd1 4210 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3f423c9c 4211 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
115defd1 4212 }
833c7174 4213 vlan->nb_host_devs++;
7c9d8e07
FB
4214 ret = net_slirp_init(vlan);
4215 } else
4216#endif
7fb843f8
FB
4217#ifdef _WIN32
4218 if (!strcmp(device, "tap")) {
4219 char ifname[64];
4220 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4221 fprintf(stderr, "tap: no interface name\n");
4222 return -1;
4223 }
833c7174 4224 vlan->nb_host_devs++;
7fb843f8
FB
4225 ret = tap_win32_init(vlan, ifname);
4226 } else
4227#else
7c9d8e07
FB
4228 if (!strcmp(device, "tap")) {
4229 char ifname[64];
4230 char setup_script[1024];
4231 int fd;
4f01035f 4232 vlan->nb_host_devs++;
7c9d8e07
FB
4233 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4234 fd = strtol(buf, NULL, 0);
4235 ret = -1;
4236 if (net_tap_fd_init(vlan, fd))
4237 ret = 0;
4238 } else {
bf8c5342
FB
4239 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4240 ifname[0] = '\0';
4241 }
7c9d8e07
FB
4242 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4243 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4244 }
4245 ret = net_tap_init(vlan, ifname, setup_script);
4246 }
4247 } else
fd1dff4b 4248#endif
7c9d8e07
FB
4249 if (!strcmp(device, "socket")) {
4250 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4251 int fd;
4252 fd = strtol(buf, NULL, 0);
4253 ret = -1;
4254 if (net_socket_fd_init(vlan, fd, 1))
4255 ret = 0;
4256 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4257 ret = net_socket_listen_init(vlan, buf);
4258 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4259 ret = net_socket_connect_init(vlan, buf);
3d830459
FB
4260 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4261 ret = net_socket_mcast_init(vlan, buf);
7c9d8e07
FB
4262 } else {
4263 fprintf(stderr, "Unknown socket options: %s\n", p);
4264 return -1;
4265 }
833c7174 4266 vlan->nb_host_devs++;
7c9d8e07 4267 } else
7c9d8e07
FB
4268 {
4269 fprintf(stderr, "Unknown network device: %s\n", device);
4270 return -1;
4271 }
4272 if (ret < 0) {
4273 fprintf(stderr, "Could not initialize device '%s'\n", device);
4274 }
4275
4276 return ret;
4277}
4278
4279void do_info_network(void)
4280{
4281 VLANState *vlan;
4282 VLANClientState *vc;
4283
4284 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4285 term_printf("VLAN %d devices:\n", vlan->id);
4286 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4287 term_printf(" %s\n", vc->info_str);
4288 }
4289}
42550fde 4290
a594cfbf
FB
4291/***********************************************************/
4292/* USB devices */
4293
0d92ed30
PB
4294static USBPort *used_usb_ports;
4295static USBPort *free_usb_ports;
4296
4297/* ??? Maybe change this to register a hub to keep track of the topology. */
4298void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4299 usb_attachfn attach)
4300{
4301 port->opaque = opaque;
4302 port->index = index;
4303 port->attach = attach;
4304 port->next = free_usb_ports;
4305 free_usb_ports = port;
4306}
4307
a594cfbf
FB
4308static int usb_device_add(const char *devname)
4309{
4310 const char *p;
4311 USBDevice *dev;
0d92ed30 4312 USBPort *port;
a594cfbf 4313
0d92ed30 4314 if (!free_usb_ports)
a594cfbf
FB
4315 return -1;
4316
4317 if (strstart(devname, "host:", &p)) {
4318 dev = usb_host_device_open(p);
a594cfbf
FB
4319 } else if (!strcmp(devname, "mouse")) {
4320 dev = usb_mouse_init();
09b26c5e
FB
4321 } else if (!strcmp(devname, "tablet")) {
4322 dev = usb_tablet_init();
2e5d83bb
PB
4323 } else if (strstart(devname, "disk:", &p)) {
4324 dev = usb_msd_init(p);
f6d2a316
AZ
4325 } else if (!strcmp(devname, "wacom-tablet")) {
4326 dev = usb_wacom_init();
a594cfbf
FB
4327 } else {
4328 return -1;
4329 }
0d92ed30
PB
4330 if (!dev)
4331 return -1;
4332
4333 /* Find a USB port to add the device to. */
4334 port = free_usb_ports;
4335 if (!port->next) {
4336 USBDevice *hub;
4337
4338 /* Create a new hub and chain it on. */
4339 free_usb_ports = NULL;
4340 port->next = used_usb_ports;
4341 used_usb_ports = port;
4342
4343 hub = usb_hub_init(VM_USB_HUB_SIZE);
4344 usb_attach(port, hub);
4345 port = free_usb_ports;
4346 }
4347
4348 free_usb_ports = port->next;
4349 port->next = used_usb_ports;
4350 used_usb_ports = port;
4351 usb_attach(port, dev);
a594cfbf
FB
4352 return 0;
4353}
4354
4355static int usb_device_del(const char *devname)
4356{
0d92ed30
PB
4357 USBPort *port;
4358 USBPort **lastp;
059809e4 4359 USBDevice *dev;
0d92ed30 4360 int bus_num, addr;
a594cfbf
FB
4361 const char *p;
4362
0d92ed30 4363 if (!used_usb_ports)
a594cfbf
FB
4364 return -1;
4365
4366 p = strchr(devname, '.');
4367 if (!p)
4368 return -1;
4369 bus_num = strtoul(devname, NULL, 0);
4370 addr = strtoul(p + 1, NULL, 0);
4371 if (bus_num != 0)
4372 return -1;
0d92ed30
PB
4373
4374 lastp = &used_usb_ports;
4375 port = used_usb_ports;
4376 while (port && port->dev->addr != addr) {
4377 lastp = &port->next;
4378 port = port->next;
a594cfbf 4379 }
0d92ed30
PB
4380
4381 if (!port)
a594cfbf 4382 return -1;
0d92ed30 4383
059809e4 4384 dev = port->dev;
0d92ed30
PB
4385 *lastp = port->next;
4386 usb_attach(port, NULL);
059809e4 4387 dev->handle_destroy(dev);
0d92ed30
PB
4388 port->next = free_usb_ports;
4389 free_usb_ports = port;
a594cfbf
FB
4390 return 0;
4391}
4392
4393void do_usb_add(const char *devname)
4394{
4395 int ret;
4396 ret = usb_device_add(devname);
4397 if (ret < 0)
4398 term_printf("Could not add USB device '%s'\n", devname);
4399}
4400
4401void do_usb_del(const char *devname)
4402{
4403 int ret;
4404 ret = usb_device_del(devname);
4405 if (ret < 0)
4406 term_printf("Could not remove USB device '%s'\n", devname);
4407}
4408
4409void usb_info(void)
4410{
4411 USBDevice *dev;
0d92ed30 4412 USBPort *port;
a594cfbf
FB
4413 const char *speed_str;
4414
0d92ed30 4415 if (!usb_enabled) {
a594cfbf
FB
4416 term_printf("USB support not enabled\n");
4417 return;
4418 }
4419
0d92ed30
PB
4420 for (port = used_usb_ports; port; port = port->next) {
4421 dev = port->dev;
4422 if (!dev)
4423 continue;
4424 switch(dev->speed) {
4425 case USB_SPEED_LOW:
4426 speed_str = "1.5";
4427 break;
4428 case USB_SPEED_FULL:
4429 speed_str = "12";
4430 break;
4431 case USB_SPEED_HIGH:
4432 speed_str = "480";
4433 break;
4434 default:
4435 speed_str = "?";
4436 break;
a594cfbf 4437 }
1f6e24e7
FB
4438 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4439 0, dev->addr, speed_str, dev->devname);
a594cfbf
FB
4440 }
4441}
4442
201a51fc
AZ
4443/***********************************************************/
4444/* PCMCIA/Cardbus */
4445
4446static struct pcmcia_socket_entry_s {
4447 struct pcmcia_socket_s *socket;
4448 struct pcmcia_socket_entry_s *next;
4449} *pcmcia_sockets = 0;
4450
4451void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4452{
4453 struct pcmcia_socket_entry_s *entry;
4454
4455 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4456 entry->socket = socket;
4457 entry->next = pcmcia_sockets;
4458 pcmcia_sockets = entry;
4459}
4460
4461void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4462{
4463 struct pcmcia_socket_entry_s *entry, **ptr;
4464
4465 ptr = &pcmcia_sockets;
4466 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4467 if (entry->socket == socket) {
4468 *ptr = entry->next;
4469 qemu_free(entry);
4470 }
4471}
4472
4473void pcmcia_info(void)
4474{
4475 struct pcmcia_socket_entry_s *iter;
4476 if (!pcmcia_sockets)
4477 term_printf("No PCMCIA sockets\n");
4478
4479 for (iter = pcmcia_sockets; iter; iter = iter->next)
4480 term_printf("%s: %s\n", iter->socket->slot_string,
4481 iter->socket->attached ? iter->socket->card_string :
4482 "Empty");
4483}
4484
8a7ddc38
FB
4485/***********************************************************/
4486/* I/O handling */
0824d6fc 4487
c4b1fcc0
FB
4488#define MAX_IO_HANDLERS 64
4489
4490typedef struct IOHandlerRecord {
4491 int fd;
7c9d8e07
FB
4492 IOCanRWHandler *fd_read_poll;
4493 IOHandler *fd_read;
4494 IOHandler *fd_write;
cafffd40 4495 int deleted;
c4b1fcc0
FB
4496 void *opaque;
4497 /* temporary data */
4498 struct pollfd *ufd;
8a7ddc38 4499 struct IOHandlerRecord *next;
c4b1fcc0
FB
4500} IOHandlerRecord;
4501
8a7ddc38 4502static IOHandlerRecord *first_io_handler;
c4b1fcc0 4503
7c9d8e07
FB
4504/* XXX: fd_read_poll should be suppressed, but an API change is
4505 necessary in the character devices to suppress fd_can_read(). */
4506int qemu_set_fd_handler2(int fd,
4507 IOCanRWHandler *fd_read_poll,
4508 IOHandler *fd_read,
4509 IOHandler *fd_write,
4510 void *opaque)
c4b1fcc0 4511{
7c9d8e07 4512 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 4513
7c9d8e07
FB
4514 if (!fd_read && !fd_write) {
4515 pioh = &first_io_handler;
4516 for(;;) {
4517 ioh = *pioh;
4518 if (ioh == NULL)
4519 break;
4520 if (ioh->fd == fd) {
cafffd40 4521 ioh->deleted = 1;
7c9d8e07
FB
4522 break;
4523 }
4524 pioh = &ioh->next;
4525 }
4526 } else {
4527 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4528 if (ioh->fd == fd)
4529 goto found;
4530 }
4531 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4532 if (!ioh)
4533 return -1;
4534 ioh->next = first_io_handler;
4535 first_io_handler = ioh;
4536 found:
4537 ioh->fd = fd;
4538 ioh->fd_read_poll = fd_read_poll;
4539 ioh->fd_read = fd_read;
4540 ioh->fd_write = fd_write;
4541 ioh->opaque = opaque;
cafffd40 4542 ioh->deleted = 0;
7c9d8e07 4543 }
c4b1fcc0
FB
4544 return 0;
4545}
4546
7c9d8e07
FB
4547int qemu_set_fd_handler(int fd,
4548 IOHandler *fd_read,
4549 IOHandler *fd_write,
4550 void *opaque)
8a7ddc38 4551{
7c9d8e07 4552 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
4553}
4554
f331110f
FB
4555/***********************************************************/
4556/* Polling handling */
4557
4558typedef struct PollingEntry {
4559 PollingFunc *func;
4560 void *opaque;
4561 struct PollingEntry *next;
4562} PollingEntry;
4563
4564static PollingEntry *first_polling_entry;
4565
4566int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4567{
4568 PollingEntry **ppe, *pe;
4569 pe = qemu_mallocz(sizeof(PollingEntry));
4570 if (!pe)
4571 return -1;
4572 pe->func = func;
4573 pe->opaque = opaque;
4574 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4575 *ppe = pe;
4576 return 0;
4577}
4578
4579void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4580{
4581 PollingEntry **ppe, *pe;
4582 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4583 pe = *ppe;
4584 if (pe->func == func && pe->opaque == opaque) {
4585 *ppe = pe->next;
4586 qemu_free(pe);
4587 break;
4588 }
4589 }
4590}
4591
a18e524a
FB
4592#ifdef _WIN32
4593/***********************************************************/
4594/* Wait objects support */
4595typedef struct WaitObjects {
4596 int num;
4597 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4598 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4599 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4600} WaitObjects;
4601
4602static WaitObjects wait_objects = {0};
4603
4604int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4605{
4606 WaitObjects *w = &wait_objects;
4607
4608 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4609 return -1;
4610 w->events[w->num] = handle;
4611 w->func[w->num] = func;
4612 w->opaque[w->num] = opaque;
4613 w->num++;
4614 return 0;
4615}
4616
4617void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4618{
4619 int i, found;
4620 WaitObjects *w = &wait_objects;
4621
4622 found = 0;
4623 for (i = 0; i < w->num; i++) {
4624 if (w->events[i] == handle)
4625 found = 1;
4626 if (found) {
4627 w->events[i] = w->events[i + 1];
4628 w->func[i] = w->func[i + 1];
4629 w->opaque[i] = w->opaque[i + 1];
4630 }
4631 }
4632 if (found)
4633 w->num--;
4634}
4635#endif
4636
8a7ddc38
FB
4637/***********************************************************/
4638/* savevm/loadvm support */
4639
faea38e7
FB
4640#define IO_BUF_SIZE 32768
4641
4642struct QEMUFile {
4643 FILE *outfile;
4644 BlockDriverState *bs;
4645 int is_file;
4646 int is_writable;
4647 int64_t base_offset;
4648 int64_t buf_offset; /* start of buffer when writing, end of buffer
4649 when reading */
4650 int buf_index;
4651 int buf_size; /* 0 when writing */
4652 uint8_t buf[IO_BUF_SIZE];
4653};
4654
4655QEMUFile *qemu_fopen(const char *filename, const char *mode)
4656{
4657 QEMUFile *f;
4658
4659 f = qemu_mallocz(sizeof(QEMUFile));
4660 if (!f)
4661 return NULL;
4662 if (!strcmp(mode, "wb")) {
4663 f->is_writable = 1;
4664 } else if (!strcmp(mode, "rb")) {
4665 f->is_writable = 0;
4666 } else {
4667 goto fail;
4668 }
4669 f->outfile = fopen(filename, mode);
4670 if (!f->outfile)
4671 goto fail;
4672 f->is_file = 1;
4673 return f;
4674 fail:
4675 if (f->outfile)
4676 fclose(f->outfile);
4677 qemu_free(f);
4678 return NULL;
4679}
4680
4681QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4682{
4683 QEMUFile *f;
4684
4685 f = qemu_mallocz(sizeof(QEMUFile));
4686 if (!f)
4687 return NULL;
4688 f->is_file = 0;
4689 f->bs = bs;
4690 f->is_writable = is_writable;
4691 f->base_offset = offset;
4692 return f;
4693}
4694
4695void qemu_fflush(QEMUFile *f)
4696{
4697 if (!f->is_writable)
4698 return;
4699 if (f->buf_index > 0) {
4700 if (f->is_file) {
4701 fseek(f->outfile, f->buf_offset, SEEK_SET);
4702 fwrite(f->buf, 1, f->buf_index, f->outfile);
4703 } else {
4704 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4705 f->buf, f->buf_index);
4706 }
4707 f->buf_offset += f->buf_index;
4708 f->buf_index = 0;
4709 }
4710}
4711
4712static void qemu_fill_buffer(QEMUFile *f)
4713{
4714 int len;
4715
4716 if (f->is_writable)
4717 return;
4718 if (f->is_file) {
4719 fseek(f->outfile, f->buf_offset, SEEK_SET);
4720 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4721 if (len < 0)
4722 len = 0;
4723 } else {
4724 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4725 f->buf, IO_BUF_SIZE);
4726 if (len < 0)
4727 len = 0;
4728 }
4729 f->buf_index = 0;
4730 f->buf_size = len;
4731 f->buf_offset += len;
4732}
4733
4734void qemu_fclose(QEMUFile *f)
4735{
4736 if (f->is_writable)
4737 qemu_fflush(f);
4738 if (f->is_file) {
4739 fclose(f->outfile);
4740 }
4741 qemu_free(f);
4742}
4743
8a7ddc38 4744void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
b4608c04 4745{
faea38e7
FB
4746 int l;
4747 while (size > 0) {
4748 l = IO_BUF_SIZE - f->buf_index;
4749 if (l > size)
4750 l = size;
4751 memcpy(f->buf + f->buf_index, buf, l);
4752 f->buf_index += l;
4753 buf += l;
4754 size -= l;
4755 if (f->buf_index >= IO_BUF_SIZE)
4756 qemu_fflush(f);
4757 }
b4608c04
FB
4758}
4759
8a7ddc38 4760void qemu_put_byte(QEMUFile *f, int v)
b4608c04 4761{
faea38e7
FB
4762 f->buf[f->buf_index++] = v;
4763 if (f->buf_index >= IO_BUF_SIZE)
4764 qemu_fflush(f);
4765}
4766
4767int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4768{
4769 int size, l;
4770
4771 size = size1;
4772 while (size > 0) {
4773 l = f->buf_size - f->buf_index;
4774 if (l == 0) {
4775 qemu_fill_buffer(f);
4776 l = f->buf_size - f->buf_index;
4777 if (l == 0)
4778 break;
4779 }
4780 if (l > size)
4781 l = size;
4782 memcpy(buf, f->buf + f->buf_index, l);
4783 f->buf_index += l;
4784 buf += l;
4785 size -= l;
4786 }
4787 return size1 - size;
4788}
4789
4790int qemu_get_byte(QEMUFile *f)
4791{
4792 if (f->buf_index >= f->buf_size) {
4793 qemu_fill_buffer(f);
4794 if (f->buf_index >= f->buf_size)
4795 return 0;
4796 }
4797 return f->buf[f->buf_index++];
4798}
4799
4800int64_t qemu_ftell(QEMUFile *f)
4801{
4802 return f->buf_offset - f->buf_size + f->buf_index;
4803}
4804
4805int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4806{
4807 if (whence == SEEK_SET) {
4808 /* nothing to do */
4809 } else if (whence == SEEK_CUR) {
4810 pos += qemu_ftell(f);
4811 } else {
4812 /* SEEK_END not supported */
4813 return -1;
4814 }
4815 if (f->is_writable) {
4816 qemu_fflush(f);
4817 f->buf_offset = pos;
4818 } else {
4819 f->buf_offset = pos;
4820 f->buf_index = 0;
4821 f->buf_size = 0;
4822 }
4823 return pos;
8a7ddc38
FB
4824}
4825
4826void qemu_put_be16(QEMUFile *f, unsigned int v)
4827{
4828 qemu_put_byte(f, v >> 8);
4829 qemu_put_byte(f, v);
4830}
4831
4832void qemu_put_be32(QEMUFile *f, unsigned int v)
4833{
4834 qemu_put_byte(f, v >> 24);
4835 qemu_put_byte(f, v >> 16);
4836 qemu_put_byte(f, v >> 8);
4837 qemu_put_byte(f, v);
4838}
4839
4840void qemu_put_be64(QEMUFile *f, uint64_t v)
4841{
4842 qemu_put_be32(f, v >> 32);
4843 qemu_put_be32(f, v);
4844}
4845
8a7ddc38
FB
4846unsigned int qemu_get_be16(QEMUFile *f)
4847{
4848 unsigned int v;
4849 v = qemu_get_byte(f) << 8;
4850 v |= qemu_get_byte(f);
4851 return v;
4852}
4853
4854unsigned int qemu_get_be32(QEMUFile *f)
4855{
4856 unsigned int v;
4857 v = qemu_get_byte(f) << 24;
4858 v |= qemu_get_byte(f) << 16;
4859 v |= qemu_get_byte(f) << 8;
4860 v |= qemu_get_byte(f);
4861 return v;
4862}
4863
4864uint64_t qemu_get_be64(QEMUFile *f)
4865{
4866 uint64_t v;
4867 v = (uint64_t)qemu_get_be32(f) << 32;
4868 v |= qemu_get_be32(f);
4869 return v;
4870}
4871
8a7ddc38
FB
4872typedef struct SaveStateEntry {
4873 char idstr[256];
4874 int instance_id;
4875 int version_id;
4876 SaveStateHandler *save_state;
4877 LoadStateHandler *load_state;
4878 void *opaque;
4879 struct SaveStateEntry *next;
4880} SaveStateEntry;
b4608c04 4881
8a7ddc38
FB
4882static SaveStateEntry *first_se;
4883
4884int register_savevm(const char *idstr,
4885 int instance_id,
4886 int version_id,
4887 SaveStateHandler *save_state,
4888 LoadStateHandler *load_state,
4889 void *opaque)
4890{
4891 SaveStateEntry *se, **pse;
4892
4893 se = qemu_malloc(sizeof(SaveStateEntry));
4894 if (!se)
4895 return -1;
4896 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4897 se->instance_id = instance_id;
4898 se->version_id = version_id;
4899 se->save_state = save_state;
4900 se->load_state = load_state;
4901 se->opaque = opaque;
4902 se->next = NULL;
4903
4904 /* add at the end of list */
4905 pse = &first_se;
4906 while (*pse != NULL)
4907 pse = &(*pse)->next;
4908 *pse = se;
4909 return 0;
4910}
4911
4912#define QEMU_VM_FILE_MAGIC 0x5145564d
faea38e7 4913#define QEMU_VM_FILE_VERSION 0x00000002
8a7ddc38 4914
faea38e7 4915int qemu_savevm_state(QEMUFile *f)
8a7ddc38
FB
4916{
4917 SaveStateEntry *se;
faea38e7
FB
4918 int len, ret;
4919 int64_t cur_pos, len_pos, total_len_pos;
313aa567 4920
8a7ddc38
FB
4921 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4922 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
faea38e7
FB
4923 total_len_pos = qemu_ftell(f);
4924 qemu_put_be64(f, 0); /* total size */
8a7ddc38
FB
4925
4926 for(se = first_se; se != NULL; se = se->next) {
4927 /* ID string */
4928 len = strlen(se->idstr);
4929 qemu_put_byte(f, len);
4930 qemu_put_buffer(f, se->idstr, len);
4931
4932 qemu_put_be32(f, se->instance_id);
4933 qemu_put_be32(f, se->version_id);
4934
4935 /* record size: filled later */
faea38e7 4936 len_pos = qemu_ftell(f);
8a7ddc38
FB
4937 qemu_put_be32(f, 0);
4938
4939 se->save_state(f, se->opaque);
4940
4941 /* fill record size */
faea38e7
FB
4942 cur_pos = qemu_ftell(f);
4943 len = cur_pos - len_pos - 4;
4944 qemu_fseek(f, len_pos, SEEK_SET);
8a7ddc38 4945 qemu_put_be32(f, len);
faea38e7 4946 qemu_fseek(f, cur_pos, SEEK_SET);
8a7ddc38 4947 }
faea38e7
FB
4948 cur_pos = qemu_ftell(f);
4949 qemu_fseek(f, total_len_pos, SEEK_SET);
4950 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4951 qemu_fseek(f, cur_pos, SEEK_SET);
8a7ddc38 4952
8a7ddc38 4953 ret = 0;
8a7ddc38
FB
4954 return ret;
4955}
4956
4957static SaveStateEntry *find_se(const char *idstr, int instance_id)
4958{
4959 SaveStateEntry *se;
4960
4961 for(se = first_se; se != NULL; se = se->next) {
4962 if (!strcmp(se->idstr, idstr) &&
4963 instance_id == se->instance_id)
4964 return se;
4965 }
4966 return NULL;
4967}
4968
faea38e7 4969int qemu_loadvm_state(QEMUFile *f)
8a7ddc38
FB
4970{
4971 SaveStateEntry *se;
faea38e7
FB
4972 int len, ret, instance_id, record_len, version_id;
4973 int64_t total_len, end_pos, cur_pos;
8a7ddc38
FB
4974 unsigned int v;
4975 char idstr[256];
4976
8a7ddc38
FB
4977 v = qemu_get_be32(f);
4978 if (v != QEMU_VM_FILE_MAGIC)
4979 goto fail;
4980 v = qemu_get_be32(f);
4981 if (v != QEMU_VM_FILE_VERSION) {
4982 fail:
8a7ddc38
FB
4983 ret = -1;
4984 goto the_end;
4985 }
faea38e7
FB
4986 total_len = qemu_get_be64(f);
4987 end_pos = total_len + qemu_ftell(f);
b4608c04 4988 for(;;) {
faea38e7 4989 if (qemu_ftell(f) >= end_pos)
cd4c3e88 4990 break;
faea38e7 4991 len = qemu_get_byte(f);
8a7ddc38
FB
4992 qemu_get_buffer(f, idstr, len);
4993 idstr[len] = '\0';
4994 instance_id = qemu_get_be32(f);
4995 version_id = qemu_get_be32(f);
4996 record_len = qemu_get_be32(f);
4997#if 0
4998 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4999 idstr, instance_id, version_id, record_len);
5000#endif
faea38e7 5001 cur_pos = qemu_ftell(f);
8a7ddc38
FB
5002 se = find_se(idstr, instance_id);
5003 if (!se) {
5004 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5005 instance_id, idstr);
5006 } else {
5007 ret = se->load_state(f, se->opaque, version_id);
5008 if (ret < 0) {
5009 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5010 instance_id, idstr);
5011 }
34865134 5012 }
8a7ddc38
FB
5013 /* always seek to exact end of record */
5014 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5015 }
8a7ddc38 5016 ret = 0;
faea38e7
FB
5017 the_end:
5018 return ret;
5019}
5020
5021/* device can contain snapshots */
5022static int bdrv_can_snapshot(BlockDriverState *bs)
5023{
5024 return (bs &&
5025 !bdrv_is_removable(bs) &&
5026 !bdrv_is_read_only(bs));
5027}
5028
5029/* device must be snapshots in order to have a reliable snapshot */
5030static int bdrv_has_snapshot(BlockDriverState *bs)
5031{
5032 return (bs &&
5033 !bdrv_is_removable(bs) &&
5034 !bdrv_is_read_only(bs));
5035}
5036
5037static BlockDriverState *get_bs_snapshots(void)
5038{
5039 BlockDriverState *bs;
5040 int i;
5041
5042 if (bs_snapshots)
5043 return bs_snapshots;
5044 for(i = 0; i <= MAX_DISKS; i++) {
5045 bs = bs_table[i];
5046 if (bdrv_can_snapshot(bs))
5047 goto ok;
5048 }
5049 return NULL;
5050 ok:
5051 bs_snapshots = bs;
5052 return bs;
5053}
5054
5055static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5056 const char *name)
5057{
5058 QEMUSnapshotInfo *sn_tab, *sn;
5059 int nb_sns, i, ret;
5060
5061 ret = -ENOENT;
5062 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5063 if (nb_sns < 0)
5064 return ret;
5065 for(i = 0; i < nb_sns; i++) {
5066 sn = &sn_tab[i];
5067 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5068 *sn_info = *sn;
5069 ret = 0;
5070 break;
5071 }
5072 }
5073 qemu_free(sn_tab);
5074 return ret;
5075}
5076
5077void do_savevm(const char *name)
5078{
5079 BlockDriverState *bs, *bs1;
5080 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5081 int must_delete, ret, i;
5082 BlockDriverInfo bdi1, *bdi = &bdi1;
5083 QEMUFile *f;
5084 int saved_vm_running;
4c279bdf
FB
5085#ifdef _WIN32
5086 struct _timeb tb;
5087#else
faea38e7 5088 struct timeval tv;
4c279bdf 5089#endif
faea38e7
FB
5090
5091 bs = get_bs_snapshots();
5092 if (!bs) {
5093 term_printf("No block device can accept snapshots\n");
5094 return;
5095 }
5096
6192bc37
PB
5097 /* ??? Should this occur after vm_stop? */
5098 qemu_aio_flush();
5099
faea38e7
FB
5100 saved_vm_running = vm_running;
5101 vm_stop(0);
5102
5103 must_delete = 0;
5104 if (name) {
5105 ret = bdrv_snapshot_find(bs, old_sn, name);
5106 if (ret >= 0) {
5107 must_delete = 1;
5108 }
5109 }
5110 memset(sn, 0, sizeof(*sn));
5111 if (must_delete) {
5112 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5113 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5114 } else {
5115 if (name)
5116 pstrcpy(sn->name, sizeof(sn->name), name);
5117 }
5118
5119 /* fill auxiliary fields */
4c279bdf
FB
5120#ifdef _WIN32
5121 _ftime(&tb);
5122 sn->date_sec = tb.time;
5123 sn->date_nsec = tb.millitm * 1000000;
5124#else
faea38e7
FB
5125 gettimeofday(&tv, NULL);
5126 sn->date_sec = tv.tv_sec;
5127 sn->date_nsec = tv.tv_usec * 1000;
4c279bdf 5128#endif
faea38e7
FB
5129 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5130
5131 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5132 term_printf("Device %s does not support VM state snapshots\n",
5133 bdrv_get_device_name(bs));
5134 goto the_end;
5135 }
5136
5137 /* save the VM state */
5138 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5139 if (!f) {
5140 term_printf("Could not open VM state file\n");
5141 goto the_end;
5142 }
5143 ret = qemu_savevm_state(f);
5144 sn->vm_state_size = qemu_ftell(f);
5145 qemu_fclose(f);
5146 if (ret < 0) {
5147 term_printf("Error %d while writing VM\n", ret);
5148 goto the_end;
5149 }
5150
5151 /* create the snapshots */
5152
5153 for(i = 0; i < MAX_DISKS; i++) {
5154 bs1 = bs_table[i];
5155 if (bdrv_has_snapshot(bs1)) {
5156 if (must_delete) {
5157 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5158 if (ret < 0) {
5159 term_printf("Error while deleting snapshot on '%s'\n",
5160 bdrv_get_device_name(bs1));
5161 }
5162 }
5163 ret = bdrv_snapshot_create(bs1, sn);
5164 if (ret < 0) {
5165 term_printf("Error while creating snapshot on '%s'\n",
5166 bdrv_get_device_name(bs1));
5167 }
5168 }
5169 }
5170
8a7ddc38
FB
5171 the_end:
5172 if (saved_vm_running)
5173 vm_start();
faea38e7
FB
5174}
5175
5176void do_loadvm(const char *name)
5177{
5178 BlockDriverState *bs, *bs1;
5179 BlockDriverInfo bdi1, *bdi = &bdi1;
5180 QEMUFile *f;
5181 int i, ret;
5182 int saved_vm_running;
5183
5184 bs = get_bs_snapshots();
5185 if (!bs) {
5186 term_printf("No block device supports snapshots\n");
5187 return;
5188 }
5189
6192bc37
PB
5190 /* Flush all IO requests so they don't interfere with the new state. */
5191 qemu_aio_flush();
5192
faea38e7
FB
5193 saved_vm_running = vm_running;
5194 vm_stop(0);
5195
5196 for(i = 0; i <= MAX_DISKS; i++) {
5197 bs1 = bs_table[i];
5198 if (bdrv_has_snapshot(bs1)) {
5199 ret = bdrv_snapshot_goto(bs1, name);
5200 if (ret < 0) {
5201 if (bs != bs1)
5202 term_printf("Warning: ");
5203 switch(ret) {
5204 case -ENOTSUP:
5205 term_printf("Snapshots not supported on device '%s'\n",
5206 bdrv_get_device_name(bs1));
5207 break;
5208 case -ENOENT:
5209 term_printf("Could not find snapshot '%s' on device '%s'\n",
5210 name, bdrv_get_device_name(bs1));
5211 break;
5212 default:
5213 term_printf("Error %d while activating snapshot on '%s'\n",
5214 ret, bdrv_get_device_name(bs1));
5215 break;
5216 }
5217 /* fatal on snapshot block device */
5218 if (bs == bs1)
5219 goto the_end;
5220 }
5221 }
5222 }
5223
5224 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5225 term_printf("Device %s does not support VM state snapshots\n",
5226 bdrv_get_device_name(bs));
5227 return;
5228 }
5229
5230 /* restore the VM state */
5231 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5232 if (!f) {
5233 term_printf("Could not open VM state file\n");
5234 goto the_end;
5235 }
5236 ret = qemu_loadvm_state(f);
5237 qemu_fclose(f);
5238 if (ret < 0) {
5239 term_printf("Error %d while loading VM state\n", ret);
5240 }
5241 the_end:
5242 if (saved_vm_running)
5243 vm_start();
5244}
5245
5246void do_delvm(const char *name)
5247{
5248 BlockDriverState *bs, *bs1;
5249 int i, ret;
5250
5251 bs = get_bs_snapshots();
5252 if (!bs) {
5253 term_printf("No block device supports snapshots\n");
5254 return;
5255 }
5256
5257 for(i = 0; i <= MAX_DISKS; i++) {
5258 bs1 = bs_table[i];
5259 if (bdrv_has_snapshot(bs1)) {
5260 ret = bdrv_snapshot_delete(bs1, name);
5261 if (ret < 0) {
5262 if (ret == -ENOTSUP)
5263 term_printf("Snapshots not supported on device '%s'\n",
5264 bdrv_get_device_name(bs1));
5265 else
5266 term_printf("Error %d while deleting snapshot on '%s'\n",
5267 ret, bdrv_get_device_name(bs1));
5268 }
5269 }
5270 }
5271}
5272
5273void do_info_snapshots(void)
5274{
5275 BlockDriverState *bs, *bs1;
5276 QEMUSnapshotInfo *sn_tab, *sn;
5277 int nb_sns, i;
5278 char buf[256];
5279
5280 bs = get_bs_snapshots();
5281 if (!bs) {
5282 term_printf("No available block device supports snapshots\n");
5283 return;
5284 }
5285 term_printf("Snapshot devices:");
5286 for(i = 0; i <= MAX_DISKS; i++) {
5287 bs1 = bs_table[i];
5288 if (bdrv_has_snapshot(bs1)) {
5289 if (bs == bs1)
5290 term_printf(" %s", bdrv_get_device_name(bs1));
5291 }
5292 }
5293 term_printf("\n");
5294
5295 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5296 if (nb_sns < 0) {
5297 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5298 return;
5299 }
5300 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5301 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5302 for(i = 0; i < nb_sns; i++) {
5303 sn = &sn_tab[i];
5304 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5305 }
5306 qemu_free(sn_tab);
8a7ddc38
FB
5307}
5308
5309/***********************************************************/
5310/* cpu save/restore */
5311
5312#if defined(TARGET_I386)
5313
5314static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5315{
02ba45c5 5316 qemu_put_be32(f, dt->selector);
20f32282 5317 qemu_put_betl(f, dt->base);
8a7ddc38
FB
5318 qemu_put_be32(f, dt->limit);
5319 qemu_put_be32(f, dt->flags);
5320}
5321
5322static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5323{
02ba45c5 5324 dt->selector = qemu_get_be32(f);
20f32282 5325 dt->base = qemu_get_betl(f);
8a7ddc38
FB
5326 dt->limit = qemu_get_be32(f);
5327 dt->flags = qemu_get_be32(f);
5328}
5329
5330void cpu_save(QEMUFile *f, void *opaque)
5331{
5332 CPUState *env = opaque;
664e0f19 5333 uint16_t fptag, fpus, fpuc, fpregs_format;
8a7ddc38
FB
5334 uint32_t hflags;
5335 int i;
664e0f19 5336
20f32282
FB
5337 for(i = 0; i < CPU_NB_REGS; i++)
5338 qemu_put_betls(f, &env->regs[i]);
5339 qemu_put_betls(f, &env->eip);
5340 qemu_put_betls(f, &env->eflags);
8a7ddc38
FB
5341 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5342 qemu_put_be32s(f, &hflags);
5343
5344 /* FPU */
5345 fpuc = env->fpuc;
5346 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5347 fptag = 0;
664e0f19
FB
5348 for(i = 0; i < 8; i++) {
5349 fptag |= ((!env->fptags[i]) << i);
8a7ddc38
FB
5350 }
5351
5352 qemu_put_be16s(f, &fpuc);
5353 qemu_put_be16s(f, &fpus);
5354 qemu_put_be16s(f, &fptag);
5355
664e0f19
FB
5356#ifdef USE_X86LDOUBLE
5357 fpregs_format = 0;
5358#else
5359 fpregs_format = 1;
5360#endif
5361 qemu_put_be16s(f, &fpregs_format);
5362
8a7ddc38 5363 for(i = 0; i < 8; i++) {
664e0f19 5364#ifdef USE_X86LDOUBLE
8636b5d8
FB
5365 {
5366 uint64_t mant;
5367 uint16_t exp;
5368 /* we save the real CPU data (in case of MMX usage only 'mant'
5369 contains the MMX register */
5370 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5371 qemu_put_be64(f, mant);
5372 qemu_put_be16(f, exp);
5373 }
664e0f19
FB
5374#else
5375 /* if we use doubles for float emulation, we save the doubles to
5376 avoid losing information in case of MMX usage. It can give
5377 problems if the image is restored on a CPU where long
5378 doubles are used instead. */
8636b5d8 5379 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
664e0f19 5380#endif
8a7ddc38
FB
5381 }
5382
5383 for(i = 0; i < 6; i++)
5384 cpu_put_seg(f, &env->segs[i]);
5385 cpu_put_seg(f, &env->ldt);
5386 cpu_put_seg(f, &env->tr);
5387 cpu_put_seg(f, &env->gdt);
5388 cpu_put_seg(f, &env->idt);
5389
5390 qemu_put_be32s(f, &env->sysenter_cs);
5391 qemu_put_be32s(f, &env->sysenter_esp);
5392 qemu_put_be32s(f, &env->sysenter_eip);
5393
20f32282
FB
5394 qemu_put_betls(f, &env->cr[0]);
5395 qemu_put_betls(f, &env->cr[2]);
5396 qemu_put_betls(f, &env->cr[3]);
5397 qemu_put_betls(f, &env->cr[4]);
8a7ddc38
FB
5398
5399 for(i = 0; i < 8; i++)
20f32282 5400 qemu_put_betls(f, &env->dr[i]);
8a7ddc38
FB
5401
5402 /* MMU */
5403 qemu_put_be32s(f, &env->a20_mask);
02536f8b 5404
664e0f19
FB
5405 /* XMM */
5406 qemu_put_be32s(f, &env->mxcsr);
02536f8b
FB
5407 for(i = 0; i < CPU_NB_REGS; i++) {
5408 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5409 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5410 }
5411
664e0f19 5412#ifdef TARGET_X86_64
02536f8b
FB
5413 qemu_put_be64s(f, &env->efer);
5414 qemu_put_be64s(f, &env->star);
5415 qemu_put_be64s(f, &env->lstar);
5416 qemu_put_be64s(f, &env->cstar);
5417 qemu_put_be64s(f, &env->fmask);
5418 qemu_put_be64s(f, &env->kernelgsbase);
5419#endif
3b21e03e 5420 qemu_put_be32s(f, &env->smbase);
8a7ddc38
FB
5421}
5422
8636b5d8 5423#ifdef USE_X86LDOUBLE
664e0f19
FB
5424/* XXX: add that in a FPU generic layer */
5425union x86_longdouble {
5426 uint64_t mant;
5427 uint16_t exp;
5428};
5429
5430#define MANTD1(fp) (fp & ((1LL << 52) - 1))
5431#define EXPBIAS1 1023
5432#define EXPD1(fp) ((fp >> 52) & 0x7FF)
5433#define SIGND1(fp) ((fp >> 32) & 0x80000000)
5434
5435static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5436{
5437 int e;
5438 /* mantissa */
5439 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5440 /* exponent + sign */
5441 e = EXPD1(temp) - EXPBIAS1 + 16383;
5442 e |= SIGND1(temp) >> 16;
5443 p->exp = e;
5444}
8636b5d8 5445#endif
664e0f19 5446
8a7ddc38
FB
5447int cpu_load(QEMUFile *f, void *opaque, int version_id)
5448{
5449 CPUState *env = opaque;
664e0f19 5450 int i, guess_mmx;
8a7ddc38 5451 uint32_t hflags;
664e0f19 5452 uint16_t fpus, fpuc, fptag, fpregs_format;
8a7ddc38 5453
3b21e03e 5454 if (version_id != 3 && version_id != 4)
8a7ddc38 5455 return -EINVAL;
20f32282
FB
5456 for(i = 0; i < CPU_NB_REGS; i++)
5457 qemu_get_betls(f, &env->regs[i]);
5458 qemu_get_betls(f, &env->eip);
5459 qemu_get_betls(f, &env->eflags);
8a7ddc38
FB
5460 qemu_get_be32s(f, &hflags);
5461
5462 qemu_get_be16s(f, &fpuc);
5463 qemu_get_be16s(f, &fpus);
5464 qemu_get_be16s(f, &fptag);
664e0f19
FB
5465 qemu_get_be16s(f, &fpregs_format);
5466
5467 /* NOTE: we cannot always restore the FPU state if the image come
5468 from a host with a different 'USE_X86LDOUBLE' define. We guess
5469 if we are in an MMX state to restore correctly in that case. */
5470 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
8a7ddc38
FB
5471 for(i = 0; i < 8; i++) {
5472 uint64_t mant;
5473 uint16_t exp;
664e0f19
FB
5474
5475 switch(fpregs_format) {
5476 case 0:
5477 mant = qemu_get_be64(f);
5478 exp = qemu_get_be16(f);
5479#ifdef USE_X86LDOUBLE
5480 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5481#else
5482 /* difficult case */
5483 if (guess_mmx)
8636b5d8 5484 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
5485 else
5486 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5487#endif
5488 break;
5489 case 1:
5490 mant = qemu_get_be64(f);
5491#ifdef USE_X86LDOUBLE
8636b5d8
FB
5492 {
5493 union x86_longdouble *p;
5494 /* difficult case */
5495 p = (void *)&env->fpregs[i];
5496 if (guess_mmx) {
5497 p->mant = mant;
5498 p->exp = 0xffff;
5499 } else {
5500 fp64_to_fp80(p, mant);
5501 }
664e0f19
FB
5502 }
5503#else
8636b5d8 5504 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
5505#endif
5506 break;
5507 default:
5508 return -EINVAL;
5509 }
8a7ddc38
FB
5510 }
5511
5512 env->fpuc = fpuc;
7a0e1f41 5513 /* XXX: restore FPU round state */
8a7ddc38
FB
5514 env->fpstt = (fpus >> 11) & 7;
5515 env->fpus = fpus & ~0x3800;
664e0f19 5516 fptag ^= 0xff;
8a7ddc38 5517 for(i = 0; i < 8; i++) {
664e0f19 5518 env->fptags[i] = (fptag >> i) & 1;
8a7ddc38
FB
5519 }
5520
5521 for(i = 0; i < 6; i++)
5522 cpu_get_seg(f, &env->segs[i]);
5523 cpu_get_seg(f, &env->ldt);
5524 cpu_get_seg(f, &env->tr);
5525 cpu_get_seg(f, &env->gdt);
5526 cpu_get_seg(f, &env->idt);
5527
5528 qemu_get_be32s(f, &env->sysenter_cs);
5529 qemu_get_be32s(f, &env->sysenter_esp);
5530 qemu_get_be32s(f, &env->sysenter_eip);
5531
20f32282
FB
5532 qemu_get_betls(f, &env->cr[0]);
5533 qemu_get_betls(f, &env->cr[2]);
5534 qemu_get_betls(f, &env->cr[3]);
5535 qemu_get_betls(f, &env->cr[4]);
8a7ddc38
FB
5536
5537 for(i = 0; i < 8; i++)
20f32282 5538 qemu_get_betls(f, &env->dr[i]);
8a7ddc38
FB
5539
5540 /* MMU */
5541 qemu_get_be32s(f, &env->a20_mask);
5542
664e0f19 5543 qemu_get_be32s(f, &env->mxcsr);
02536f8b
FB
5544 for(i = 0; i < CPU_NB_REGS; i++) {
5545 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5546 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5547 }
5548
664e0f19 5549#ifdef TARGET_X86_64
02536f8b
FB
5550 qemu_get_be64s(f, &env->efer);
5551 qemu_get_be64s(f, &env->star);
5552 qemu_get_be64s(f, &env->lstar);
5553 qemu_get_be64s(f, &env->cstar);
5554 qemu_get_be64s(f, &env->fmask);
5555 qemu_get_be64s(f, &env->kernelgsbase);
5556#endif
3b21e03e
FB
5557 if (version_id >= 4)
5558 qemu_get_be32s(f, &env->smbase);
02536f8b 5559
8a7ddc38
FB
5560 /* XXX: compute hflags from scratch, except for CPL and IIF */
5561 env->hflags = hflags;
5562 tlb_flush(env, 1);
5563 return 0;
5564}
5565
a541f297
FB
5566#elif defined(TARGET_PPC)
5567void cpu_save(QEMUFile *f, void *opaque)
5568{
5569}
5570
e95c8d51
FB
5571int cpu_load(QEMUFile *f, void *opaque, int version_id)
5572{
5573 return 0;
5574}
6af0bf9c
FB
5575
5576#elif defined(TARGET_MIPS)
5577void cpu_save(QEMUFile *f, void *opaque)
5578{
5579}
5580
5581int cpu_load(QEMUFile *f, void *opaque, int version_id)
5582{
5583 return 0;
5584}
5585
e95c8d51
FB
5586#elif defined(TARGET_SPARC)
5587void cpu_save(QEMUFile *f, void *opaque)
5588{
e80cfcfc
FB
5589 CPUState *env = opaque;
5590 int i;
5591 uint32_t tmp;
5592
4fa5d772
FB
5593 for(i = 0; i < 8; i++)
5594 qemu_put_betls(f, &env->gregs[i]);
5595 for(i = 0; i < NWINDOWS * 16; i++)
5596 qemu_put_betls(f, &env->regbase[i]);
e80cfcfc
FB
5597
5598 /* FPU */
4fa5d772
FB
5599 for(i = 0; i < TARGET_FPREGS; i++) {
5600 union {
1bdb68ea
FB
5601 float32 f;
5602 uint32_t i;
4fa5d772
FB
5603 } u;
5604 u.f = env->fpr[i];
1bdb68ea 5605 qemu_put_be32(f, u.i);
4fa5d772
FB
5606 }
5607
5608 qemu_put_betls(f, &env->pc);
5609 qemu_put_betls(f, &env->npc);
5610 qemu_put_betls(f, &env->y);
e80cfcfc 5611 tmp = GET_PSR(env);
4fa5d772 5612 qemu_put_be32(f, tmp);
3475187d
FB
5613 qemu_put_betls(f, &env->fsr);
5614 qemu_put_betls(f, &env->tbr);
5615#ifndef TARGET_SPARC64
e80cfcfc 5616 qemu_put_be32s(f, &env->wim);
e80cfcfc
FB
5617 /* MMU */
5618 for(i = 0; i < 16; i++)
5619 qemu_put_be32s(f, &env->mmuregs[i]);
3475187d 5620#endif
e95c8d51
FB
5621}
5622
a541f297
FB
5623int cpu_load(QEMUFile *f, void *opaque, int version_id)
5624{
e80cfcfc
FB
5625 CPUState *env = opaque;
5626 int i;
5627 uint32_t tmp;
5628
4fa5d772
FB
5629 for(i = 0; i < 8; i++)
5630 qemu_get_betls(f, &env->gregs[i]);
5631 for(i = 0; i < NWINDOWS * 16; i++)
5632 qemu_get_betls(f, &env->regbase[i]);
e80cfcfc
FB
5633
5634 /* FPU */
4fa5d772
FB
5635 for(i = 0; i < TARGET_FPREGS; i++) {
5636 union {
1bdb68ea
FB
5637 float32 f;
5638 uint32_t i;
4fa5d772 5639 } u;
1bdb68ea 5640 u.i = qemu_get_be32(f);
4fa5d772
FB
5641 env->fpr[i] = u.f;
5642 }
5643
5644 qemu_get_betls(f, &env->pc);
5645 qemu_get_betls(f, &env->npc);
5646 qemu_get_betls(f, &env->y);
5647 tmp = qemu_get_be32(f);
5648 env->cwp = 0; /* needed to ensure that the wrapping registers are
5649 correctly updated */
e80cfcfc 5650 PUT_PSR(env, tmp);
3475187d
FB
5651 qemu_get_betls(f, &env->fsr);
5652 qemu_get_betls(f, &env->tbr);
5653#ifndef TARGET_SPARC64
e80cfcfc 5654 qemu_get_be32s(f, &env->wim);
e80cfcfc
FB
5655 /* MMU */
5656 for(i = 0; i < 16; i++)
5657 qemu_get_be32s(f, &env->mmuregs[i]);
3475187d 5658#endif
e80cfcfc 5659 tlb_flush(env, 1);
a541f297
FB
5660 return 0;
5661}
b5ff1b31
FB
5662
5663#elif defined(TARGET_ARM)
5664
b5ff1b31
FB
5665void cpu_save(QEMUFile *f, void *opaque)
5666{
aa941b94
AZ
5667 int i;
5668 CPUARMState *env = (CPUARMState *)opaque;
5669
5670 for (i = 0; i < 16; i++) {
5671 qemu_put_be32(f, env->regs[i]);
5672 }
5673 qemu_put_be32(f, cpsr_read(env));
5674 qemu_put_be32(f, env->spsr);
5675 for (i = 0; i < 6; i++) {
5676 qemu_put_be32(f, env->banked_spsr[i]);
5677 qemu_put_be32(f, env->banked_r13[i]);
5678 qemu_put_be32(f, env->banked_r14[i]);
5679 }
5680 for (i = 0; i < 5; i++) {
5681 qemu_put_be32(f, env->usr_regs[i]);
5682 qemu_put_be32(f, env->fiq_regs[i]);
5683 }
5684 qemu_put_be32(f, env->cp15.c0_cpuid);
5685 qemu_put_be32(f, env->cp15.c0_cachetype);
5686 qemu_put_be32(f, env->cp15.c1_sys);
5687 qemu_put_be32(f, env->cp15.c1_coproc);
5688 qemu_put_be32(f, env->cp15.c2_base);
5689 qemu_put_be32(f, env->cp15.c2_data);
5690 qemu_put_be32(f, env->cp15.c2_insn);
5691 qemu_put_be32(f, env->cp15.c3);
5692 qemu_put_be32(f, env->cp15.c5_insn);
5693 qemu_put_be32(f, env->cp15.c5_data);
5694 for (i = 0; i < 8; i++) {
5695 qemu_put_be32(f, env->cp15.c6_region[i]);
5696 }
5697 qemu_put_be32(f, env->cp15.c6_insn);
5698 qemu_put_be32(f, env->cp15.c6_data);
5699 qemu_put_be32(f, env->cp15.c9_insn);
5700 qemu_put_be32(f, env->cp15.c9_data);
5701 qemu_put_be32(f, env->cp15.c13_fcse);
5702 qemu_put_be32(f, env->cp15.c13_context);
5703 qemu_put_be32(f, env->cp15.c15_cpar);
5704
5705 qemu_put_be32(f, env->features);
5706
5707 if (arm_feature(env, ARM_FEATURE_VFP)) {
5708 for (i = 0; i < 16; i++) {
5709 CPU_DoubleU u;
5710 u.d = env->vfp.regs[i];
5711 qemu_put_be32(f, u.l.upper);
5712 qemu_put_be32(f, u.l.lower);
5713 }
5714 for (i = 0; i < 16; i++) {
5715 qemu_put_be32(f, env->vfp.xregs[i]);
5716 }
5717
5718 /* TODO: Should use proper FPSCR access functions. */
5719 qemu_put_be32(f, env->vfp.vec_len);
5720 qemu_put_be32(f, env->vfp.vec_stride);
5721 }
5722
5723 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5724 for (i = 0; i < 16; i++) {
5725 qemu_put_be64(f, env->iwmmxt.regs[i]);
5726 }
5727 for (i = 0; i < 16; i++) {
5728 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5729 }
5730 }
b5ff1b31
FB
5731}
5732
5733int cpu_load(QEMUFile *f, void *opaque, int version_id)
5734{
aa941b94
AZ
5735 CPUARMState *env = (CPUARMState *)opaque;
5736 int i;
5737
5738 if (version_id != 0)
5739 return -EINVAL;
5740
5741 for (i = 0; i < 16; i++) {
5742 env->regs[i] = qemu_get_be32(f);
5743 }
5744 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5745 env->spsr = qemu_get_be32(f);
5746 for (i = 0; i < 6; i++) {
5747 env->banked_spsr[i] = qemu_get_be32(f);
5748 env->banked_r13[i] = qemu_get_be32(f);
5749 env->banked_r14[i] = qemu_get_be32(f);
5750 }
5751 for (i = 0; i < 5; i++) {
5752 env->usr_regs[i] = qemu_get_be32(f);
5753 env->fiq_regs[i] = qemu_get_be32(f);
5754 }
5755 env->cp15.c0_cpuid = qemu_get_be32(f);
5756 env->cp15.c0_cachetype = qemu_get_be32(f);
5757 env->cp15.c1_sys = qemu_get_be32(f);
5758 env->cp15.c1_coproc = qemu_get_be32(f);
5759 env->cp15.c2_base = qemu_get_be32(f);
5760 env->cp15.c2_data = qemu_get_be32(f);
5761 env->cp15.c2_insn = qemu_get_be32(f);
5762 env->cp15.c3 = qemu_get_be32(f);
5763 env->cp15.c5_insn = qemu_get_be32(f);
5764 env->cp15.c5_data = qemu_get_be32(f);
5765 for (i = 0; i < 8; i++) {
5766 env->cp15.c6_region[i] = qemu_get_be32(f);
5767 }
5768 env->cp15.c6_insn = qemu_get_be32(f);
5769 env->cp15.c6_data = qemu_get_be32(f);
5770 env->cp15.c9_insn = qemu_get_be32(f);
5771 env->cp15.c9_data = qemu_get_be32(f);
5772 env->cp15.c13_fcse = qemu_get_be32(f);
5773 env->cp15.c13_context = qemu_get_be32(f);
5774 env->cp15.c15_cpar = qemu_get_be32(f);
5775
5776 env->features = qemu_get_be32(f);
5777
5778 if (arm_feature(env, ARM_FEATURE_VFP)) {
5779 for (i = 0; i < 16; i++) {
5780 CPU_DoubleU u;
5781 u.l.upper = qemu_get_be32(f);
5782 u.l.lower = qemu_get_be32(f);
5783 env->vfp.regs[i] = u.d;
5784 }
5785 for (i = 0; i < 16; i++) {
5786 env->vfp.xregs[i] = qemu_get_be32(f);
5787 }
5788
5789 /* TODO: Should use proper FPSCR access functions. */
5790 env->vfp.vec_len = qemu_get_be32(f);
5791 env->vfp.vec_stride = qemu_get_be32(f);
5792 }
5793
5794 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5795 for (i = 0; i < 16; i++) {
5796 env->iwmmxt.regs[i] = qemu_get_be64(f);
5797 }
5798 for (i = 0; i < 16; i++) {
5799 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5800 }
5801 }
5802
b5ff1b31
FB
5803 return 0;
5804}
5805
8a7ddc38
FB
5806#else
5807
5808#warning No CPU save/restore functions
5809
5810#endif
5811
5812/***********************************************************/
5813/* ram save/restore */
5814
8a7ddc38
FB
5815static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5816{
5817 int v;
5818
5819 v = qemu_get_byte(f);
5820 switch(v) {
5821 case 0:
5822 if (qemu_get_buffer(f, buf, len) != len)
5823 return -EIO;
5824 break;
5825 case 1:
5826 v = qemu_get_byte(f);
5827 memset(buf, v, len);
5828 break;
5829 default:
5830 return -EINVAL;
5831 }
5832 return 0;
5833}
5834
c88676f8
FB
5835static int ram_load_v1(QEMUFile *f, void *opaque)
5836{
5837 int i, ret;
5838
5839 if (qemu_get_be32(f) != phys_ram_size)
5840 return -EINVAL;
5841 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5842 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5843 if (ret)
5844 return ret;
5845 }
5846 return 0;
5847}
5848
5849#define BDRV_HASH_BLOCK_SIZE 1024
5850#define IOBUF_SIZE 4096
5851#define RAM_CBLOCK_MAGIC 0xfabe
5852
5853typedef struct RamCompressState {
5854 z_stream zstream;
5855 QEMUFile *f;
5856 uint8_t buf[IOBUF_SIZE];
5857} RamCompressState;
5858
5859static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5860{
5861 int ret;
5862 memset(s, 0, sizeof(*s));
5863 s->f = f;
5864 ret = deflateInit2(&s->zstream, 1,
5865 Z_DEFLATED, 15,
5866 9, Z_DEFAULT_STRATEGY);
5867 if (ret != Z_OK)
5868 return -1;
5869 s->zstream.avail_out = IOBUF_SIZE;
5870 s->zstream.next_out = s->buf;
5871 return 0;
5872}
5873
5874static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5875{
5876 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5877 qemu_put_be16(s->f, len);
5878 qemu_put_buffer(s->f, buf, len);
5879}
5880
5881static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5882{
5883 int ret;
5884
5885 s->zstream.avail_in = len;
5886 s->zstream.next_in = (uint8_t *)buf;
5887 while (s->zstream.avail_in > 0) {
5888 ret = deflate(&s->zstream, Z_NO_FLUSH);
5889 if (ret != Z_OK)
5890 return -1;
5891 if (s->zstream.avail_out == 0) {
5892 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5893 s->zstream.avail_out = IOBUF_SIZE;
5894 s->zstream.next_out = s->buf;
5895 }
5896 }
5897 return 0;
5898}
5899
5900static void ram_compress_close(RamCompressState *s)
5901{
5902 int len, ret;
5903
5904 /* compress last bytes */
5905 for(;;) {
5906 ret = deflate(&s->zstream, Z_FINISH);
5907 if (ret == Z_OK || ret == Z_STREAM_END) {
5908 len = IOBUF_SIZE - s->zstream.avail_out;
5909 if (len > 0) {
5910 ram_put_cblock(s, s->buf, len);
5911 }
5912 s->zstream.avail_out = IOBUF_SIZE;
5913 s->zstream.next_out = s->buf;
5914 if (ret == Z_STREAM_END)
5915 break;
5916 } else {
5917 goto fail;
5918 }
5919 }
5920fail:
5921 deflateEnd(&s->zstream);
5922}
5923
5924typedef struct RamDecompressState {
5925 z_stream zstream;
5926 QEMUFile *f;
5927 uint8_t buf[IOBUF_SIZE];
5928} RamDecompressState;
5929
5930static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5931{
5932 int ret;
5933 memset(s, 0, sizeof(*s));
5934 s->f = f;
5935 ret = inflateInit(&s->zstream);
5936 if (ret != Z_OK)
5937 return -1;
5938 return 0;
5939}
5940
5941static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5942{
5943 int ret, clen;
5944
5945 s->zstream.avail_out = len;
5946 s->zstream.next_out = buf;
5947 while (s->zstream.avail_out > 0) {
5948 if (s->zstream.avail_in == 0) {
5949 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5950 return -1;
5951 clen = qemu_get_be16(s->f);
5952 if (clen > IOBUF_SIZE)
5953 return -1;
5954 qemu_get_buffer(s->f, s->buf, clen);
5955 s->zstream.avail_in = clen;
5956 s->zstream.next_in = s->buf;
5957 }
5958 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5959 if (ret != Z_OK && ret != Z_STREAM_END) {
5960 return -1;
5961 }
5962 }
5963 return 0;
5964}
5965
5966static void ram_decompress_close(RamDecompressState *s)
5967{
5968 inflateEnd(&s->zstream);
5969}
5970
8a7ddc38
FB
5971static void ram_save(QEMUFile *f, void *opaque)
5972{
5973 int i;
c88676f8
FB
5974 RamCompressState s1, *s = &s1;
5975 uint8_t buf[10];
5976
8a7ddc38 5977 qemu_put_be32(f, phys_ram_size);
c88676f8
FB
5978 if (ram_compress_open(s, f) < 0)
5979 return;
5980 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5981#if 0
5982 if (tight_savevm_enabled) {
5983 int64_t sector_num;
5984 int j;
5985
5986 /* find if the memory block is available on a virtual
5987 block device */
5988 sector_num = -1;
5989 for(j = 0; j < MAX_DISKS; j++) {
5990 if (bs_table[j]) {
5991 sector_num = bdrv_hash_find(bs_table[j],
5992 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5993 if (sector_num >= 0)
5994 break;
5995 }
5996 }
5997 if (j == MAX_DISKS)
5998 goto normal_compress;
5999 buf[0] = 1;
6000 buf[1] = j;
6001 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6002 ram_compress_buf(s, buf, 10);
6003 } else
6004#endif
6005 {
6006 // normal_compress:
6007 buf[0] = 0;
6008 ram_compress_buf(s, buf, 1);
6009 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6010 }
8a7ddc38 6011 }
c88676f8 6012 ram_compress_close(s);
8a7ddc38
FB
6013}
6014
6015static int ram_load(QEMUFile *f, void *opaque, int version_id)
6016{
c88676f8
FB
6017 RamDecompressState s1, *s = &s1;
6018 uint8_t buf[10];
6019 int i;
8a7ddc38 6020
c88676f8
FB
6021 if (version_id == 1)
6022 return ram_load_v1(f, opaque);
6023 if (version_id != 2)
8a7ddc38
FB
6024 return -EINVAL;
6025 if (qemu_get_be32(f) != phys_ram_size)
6026 return -EINVAL;
c88676f8
FB
6027 if (ram_decompress_open(s, f) < 0)
6028 return -EINVAL;
6029 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6030 if (ram_decompress_buf(s, buf, 1) < 0) {
6031 fprintf(stderr, "Error while reading ram block header\n");
6032 goto error;
6033 }
6034 if (buf[0] == 0) {
6035 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6036 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6037 goto error;
6038 }
6039 } else
6040#if 0
6041 if (buf[0] == 1) {
6042 int bs_index;
6043 int64_t sector_num;
6044
6045 ram_decompress_buf(s, buf + 1, 9);
6046 bs_index = buf[1];
6047 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6048 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6049 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6050 goto error;
6051 }
6052 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6053 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6054 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6055 bs_index, sector_num);
6056 goto error;
6057 }
6058 } else
6059#endif
6060 {
6061 error:
6062 printf("Error block header\n");
6063 return -EINVAL;
6064 }
8a7ddc38 6065 }
c88676f8 6066 ram_decompress_close(s);
8a7ddc38
FB
6067 return 0;
6068}
6069
83f64091
FB
6070/***********************************************************/
6071/* bottom halves (can be seen as timers which expire ASAP) */
6072
6073struct QEMUBH {
6074 QEMUBHFunc *cb;
6075 void *opaque;
6076 int scheduled;
6077 QEMUBH *next;
6078};
6079
6080static QEMUBH *first_bh = NULL;
6081
6082QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6083{
6084 QEMUBH *bh;
6085 bh = qemu_mallocz(sizeof(QEMUBH));
6086 if (!bh)
6087 return NULL;
6088 bh->cb = cb;
6089 bh->opaque = opaque;
6090 return bh;
6091}
6092
6eb5733a 6093int qemu_bh_poll(void)
83f64091
FB
6094{
6095 QEMUBH *bh, **pbh;
6eb5733a 6096 int ret;
83f64091 6097
6eb5733a 6098 ret = 0;
83f64091
FB
6099 for(;;) {
6100 pbh = &first_bh;
6101 bh = *pbh;
6102 if (!bh)
6103 break;
6eb5733a 6104 ret = 1;
83f64091
FB
6105 *pbh = bh->next;
6106 bh->scheduled = 0;
6107 bh->cb(bh->opaque);
6108 }
6eb5733a 6109 return ret;
83f64091
FB
6110}
6111
6112void qemu_bh_schedule(QEMUBH *bh)
6113{
6114 CPUState *env = cpu_single_env;
6115 if (bh->scheduled)
6116 return;
6117 bh->scheduled = 1;
6118 bh->next = first_bh;
6119 first_bh = bh;
6120
6121 /* stop the currently executing CPU to execute the BH ASAP */
6122 if (env) {
6123 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6124 }
6125}
6126
6127void qemu_bh_cancel(QEMUBH *bh)
6128{
6129 QEMUBH **pbh;
6130 if (bh->scheduled) {
6131 pbh = &first_bh;
6132 while (*pbh != bh)
6133 pbh = &(*pbh)->next;
6134 *pbh = bh->next;
6135 bh->scheduled = 0;
6136 }
6137}
6138
6139void qemu_bh_delete(QEMUBH *bh)
6140{
6141 qemu_bh_cancel(bh);
6142 qemu_free(bh);
6143}
6144
cc1daa40
FB
6145/***********************************************************/
6146/* machine registration */
6147
6148QEMUMachine *first_machine = NULL;
6149
6150int qemu_register_machine(QEMUMachine *m)
6151{
6152 QEMUMachine **pm;
6153 pm = &first_machine;
6154 while (*pm != NULL)
6155 pm = &(*pm)->next;
6156 m->next = NULL;
6157 *pm = m;
6158 return 0;
6159}
6160
6161QEMUMachine *find_machine(const char *name)
6162{
6163 QEMUMachine *m;
6164
6165 for(m = first_machine; m != NULL; m = m->next) {
6166 if (!strcmp(m->name, name))
6167 return m;
6168 }
6169 return NULL;
6170}
6171
8a7ddc38
FB
6172/***********************************************************/
6173/* main execution loop */
6174
6175void gui_update(void *opaque)
6176{
740733bb
TS
6177 DisplayState *ds = opaque;
6178 ds->dpy_refresh(ds);
6179 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
8a7ddc38
FB
6180}
6181
0bd48850
FB
6182struct vm_change_state_entry {
6183 VMChangeStateHandler *cb;
6184 void *opaque;
6185 LIST_ENTRY (vm_change_state_entry) entries;
6186};
6187
6188static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6189
6190VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6191 void *opaque)
6192{
6193 VMChangeStateEntry *e;
6194
6195 e = qemu_mallocz(sizeof (*e));
6196 if (!e)
6197 return NULL;
6198
6199 e->cb = cb;
6200 e->opaque = opaque;
6201 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6202 return e;
6203}
6204
6205void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6206{
6207 LIST_REMOVE (e, entries);
6208 qemu_free (e);
6209}
6210
6211static void vm_state_notify(int running)
6212{
6213 VMChangeStateEntry *e;
6214
6215 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6216 e->cb(e->opaque, running);
6217 }
6218}
6219
8a7ddc38 6220/* XXX: support several handlers */
0bd48850
FB
6221static VMStopHandler *vm_stop_cb;
6222static void *vm_stop_opaque;
8a7ddc38
FB
6223
6224int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6225{
6226 vm_stop_cb = cb;
6227 vm_stop_opaque = opaque;
6228 return 0;
6229}
6230
6231void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6232{
6233 vm_stop_cb = NULL;
6234}
6235
6236void vm_start(void)
6237{
6238 if (!vm_running) {
6239 cpu_enable_ticks();
6240 vm_running = 1;
0bd48850 6241 vm_state_notify(1);
8a7ddc38
FB
6242 }
6243}
6244
6245void vm_stop(int reason)
6246{
6247 if (vm_running) {
6248 cpu_disable_ticks();
6249 vm_running = 0;
6250 if (reason != 0) {
6251 if (vm_stop_cb) {
6252 vm_stop_cb(vm_stop_opaque, reason);
6253 }
34865134 6254 }
0bd48850 6255 vm_state_notify(0);
8a7ddc38
FB
6256 }
6257}
6258
bb0c6722
FB
6259/* reset/shutdown handler */
6260
6261typedef struct QEMUResetEntry {
6262 QEMUResetHandler *func;
6263 void *opaque;
6264 struct QEMUResetEntry *next;
6265} QEMUResetEntry;
6266
6267static QEMUResetEntry *first_reset_entry;
6268static int reset_requested;
6269static int shutdown_requested;
3475187d 6270static int powerdown_requested;
bb0c6722
FB
6271
6272void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6273{
6274 QEMUResetEntry **pre, *re;
6275
6276 pre = &first_reset_entry;
6277 while (*pre != NULL)
6278 pre = &(*pre)->next;
6279 re = qemu_mallocz(sizeof(QEMUResetEntry));
6280 re->func = func;
6281 re->opaque = opaque;
6282 re->next = NULL;
6283 *pre = re;
6284}
6285
52f61fde 6286static void qemu_system_reset(void)
bb0c6722
FB
6287{
6288 QEMUResetEntry *re;
6289
6290 /* reset all devices */
6291 for(re = first_reset_entry; re != NULL; re = re->next) {
6292 re->func(re->opaque);
6293 }
6294}
6295
6296void qemu_system_reset_request(void)
6297{
d1beab82
FB
6298 if (no_reboot) {
6299 shutdown_requested = 1;
6300 } else {
6301 reset_requested = 1;
6302 }
6a00d601
FB
6303 if (cpu_single_env)
6304 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6305}
6306
6307void qemu_system_shutdown_request(void)
6308{
6309 shutdown_requested = 1;
6a00d601
FB
6310 if (cpu_single_env)
6311 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6312}
6313
3475187d
FB
6314void qemu_system_powerdown_request(void)
6315{
6316 powerdown_requested = 1;
6a00d601
FB
6317 if (cpu_single_env)
6318 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6319}
6320
5905b2e5 6321void main_loop_wait(int timeout)
8a7ddc38 6322{
cafffd40 6323 IOHandlerRecord *ioh;
e035649e 6324 fd_set rfds, wfds, xfds;
877cf882
TS
6325 int ret, nfds;
6326#ifdef _WIN32
6327 int ret2, i;
6328#endif
fd1dff4b 6329 struct timeval tv;
f331110f
FB
6330 PollingEntry *pe;
6331
c4b1fcc0 6332
f331110f
FB
6333 /* XXX: need to suppress polling by better using win32 events */
6334 ret = 0;
6335 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6336 ret |= pe->func(pe->opaque);
6337 }
38e205a2 6338#ifdef _WIN32
e6b1e558 6339 if (ret == 0) {
a18e524a
FB
6340 int err;
6341 WaitObjects *w = &wait_objects;
6342
6343 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6344 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6345 if (w->func[ret - WAIT_OBJECT_0])
6346 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
e6b1e558
TS
6347
6348 /* Check for additional signaled events */
6349 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6350
6351 /* Check if event is signaled */
6352 ret2 = WaitForSingleObject(w->events[i], 0);
6353 if(ret2 == WAIT_OBJECT_0) {
6354 if (w->func[i])
6355 w->func[i](w->opaque[i]);
6356 } else if (ret2 == WAIT_TIMEOUT) {
6357 } else {
6358 err = GetLastError();
6359 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6360 }
6361 }
a18e524a
FB
6362 } else if (ret == WAIT_TIMEOUT) {
6363 } else {
6364 err = GetLastError();
e6b1e558 6365 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 6366 }
f331110f 6367 }
fd1dff4b
FB
6368#endif
6369 /* poll any events */
6370 /* XXX: separate device handlers from system ones */
6371 nfds = -1;
6372 FD_ZERO(&rfds);
6373 FD_ZERO(&wfds);
e035649e 6374 FD_ZERO(&xfds);
fd1dff4b 6375 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
6376 if (ioh->deleted)
6377 continue;
fd1dff4b
FB
6378 if (ioh->fd_read &&
6379 (!ioh->fd_read_poll ||
6380 ioh->fd_read_poll(ioh->opaque) != 0)) {
6381 FD_SET(ioh->fd, &rfds);
6382 if (ioh->fd > nfds)
6383 nfds = ioh->fd;
6384 }
6385 if (ioh->fd_write) {
6386 FD_SET(ioh->fd, &wfds);
6387 if (ioh->fd > nfds)
6388 nfds = ioh->fd;
6389 }
6390 }
6391
6392 tv.tv_sec = 0;
6393#ifdef _WIN32
6394 tv.tv_usec = 0;
38e205a2 6395#else
fd1dff4b
FB
6396 tv.tv_usec = timeout * 1000;
6397#endif
e035649e
FB
6398#if defined(CONFIG_SLIRP)
6399 if (slirp_inited) {
6400 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6401 }
6402#endif
6403 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
fd1dff4b 6404 if (ret > 0) {
cafffd40
TS
6405 IOHandlerRecord **pioh;
6406
6407 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6408 if (ioh->deleted)
6409 continue;
fd1dff4b
FB
6410 if (FD_ISSET(ioh->fd, &rfds)) {
6411 ioh->fd_read(ioh->opaque);
7c9d8e07 6412 }
fd1dff4b
FB
6413 if (FD_ISSET(ioh->fd, &wfds)) {
6414 ioh->fd_write(ioh->opaque);
c4b1fcc0 6415 }
b4608c04 6416 }
cafffd40
TS
6417
6418 /* remove deleted IO handlers */
6419 pioh = &first_io_handler;
6420 while (*pioh) {
6421 ioh = *pioh;
6422 if (ioh->deleted) {
6423 *pioh = ioh->next;
6424 qemu_free(ioh);
6425 } else
6426 pioh = &ioh->next;
6427 }
fd1dff4b 6428 }
c20709aa 6429#if defined(CONFIG_SLIRP)
fd1dff4b 6430 if (slirp_inited) {
e035649e
FB
6431 if (ret < 0) {
6432 FD_ZERO(&rfds);
6433 FD_ZERO(&wfds);
6434 FD_ZERO(&xfds);
c20709aa 6435 }
e035649e 6436 slirp_select_poll(&rfds, &wfds, &xfds);
fd1dff4b 6437 }
e035649e 6438#endif
83f64091 6439 qemu_aio_poll();
b4608c04 6440
fd1dff4b
FB
6441 if (vm_running) {
6442 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6443 qemu_get_clock(vm_clock));
6444 /* run dma transfers, if any */
6445 DMA_run();
6446 }
423f0742 6447
fd1dff4b
FB
6448 /* real time timers */
6449 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6450 qemu_get_clock(rt_clock));
423f0742
PB
6451
6452 /* Check bottom-halves last in case any of the earlier events triggered
6453 them. */
6454 qemu_bh_poll();
6455
5905b2e5
FB
6456}
6457
6a00d601
FB
6458static CPUState *cur_cpu;
6459
5905b2e5
FB
6460int main_loop(void)
6461{
6462 int ret, timeout;
89bfc105
FB
6463#ifdef CONFIG_PROFILER
6464 int64_t ti;
6465#endif
6a00d601 6466 CPUState *env;
5905b2e5 6467
6a00d601 6468 cur_cpu = first_cpu;
5905b2e5
FB
6469 for(;;) {
6470 if (vm_running) {
15a76449
FB
6471
6472 env = cur_cpu;
6473 for(;;) {
6474 /* get next cpu */
6475 env = env->next_cpu;
6476 if (!env)
6477 env = first_cpu;
89bfc105
FB
6478#ifdef CONFIG_PROFILER
6479 ti = profile_getclock();
6480#endif
6a00d601 6481 ret = cpu_exec(env);
89bfc105
FB
6482#ifdef CONFIG_PROFILER
6483 qemu_time += profile_getclock() - ti;
6484#endif
bd967e05
PB
6485 if (ret == EXCP_HLT) {
6486 /* Give the next CPU a chance to run. */
6487 cur_cpu = env;
6488 continue;
6489 }
15a76449
FB
6490 if (ret != EXCP_HALTED)
6491 break;
6492 /* all CPUs are halted ? */
bd967e05 6493 if (env == cur_cpu)
15a76449 6494 break;
15a76449
FB
6495 }
6496 cur_cpu = env;
6497
5905b2e5 6498 if (shutdown_requested) {
3475187d 6499 ret = EXCP_INTERRUPT;
5905b2e5
FB
6500 break;
6501 }
6502 if (reset_requested) {
6503 reset_requested = 0;
6504 qemu_system_reset();
3475187d
FB
6505 ret = EXCP_INTERRUPT;
6506 }
6507 if (powerdown_requested) {
6508 powerdown_requested = 0;
6509 qemu_system_powerdown();
6510 ret = EXCP_INTERRUPT;
5905b2e5
FB
6511 }
6512 if (ret == EXCP_DEBUG) {
6513 vm_stop(EXCP_DEBUG);
6514 }
bd967e05 6515 /* If all cpus are halted then wait until the next IRQ */
5905b2e5 6516 /* XXX: use timeout computed from timers */
bd967e05 6517 if (ret == EXCP_HALTED)
5905b2e5
FB
6518 timeout = 10;
6519 else
6520 timeout = 0;
6521 } else {
6522 timeout = 10;
6523 }
89bfc105
FB
6524#ifdef CONFIG_PROFILER
6525 ti = profile_getclock();
6526#endif
5905b2e5 6527 main_loop_wait(timeout);
89bfc105
FB
6528#ifdef CONFIG_PROFILER
6529 dev_time += profile_getclock() - ti;
6530#endif
b4608c04 6531 }
34865134
FB
6532 cpu_disable_ticks();
6533 return ret;
b4608c04
FB
6534}
6535
0824d6fc
FB
6536void help(void)
6537{
84f2e8ef 6538 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
0db63474 6539 "usage: %s [options] [disk_image]\n"
0824d6fc 6540 "\n"
a20dd508 6541 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 6542 "\n"
a20dd508 6543 "Standard options:\n"
cc1daa40 6544 "-M machine select emulated machine (-M ? for list)\n"
5adb4839 6545 "-cpu cpu select CPU (-cpu ? for list)\n"
c45886db 6546 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
36b486bb
FB
6547 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6548 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
c4b1fcc0 6549 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3e3d5815 6550 "-mtdblock file use 'file' as on-board Flash memory image\n"
a1bb27b1 6551 "-sd file use 'file' as SecureDigital card image\n"
86f55663 6552 "-pflash file use 'file' as a parallel flash image\n"
eec85c2a 6553 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
667accab
TS
6554 "-snapshot write to temporary files instead of disk image files\n"
6555#ifdef CONFIG_SDL
43523e93 6556 "-no-frame open SDL window without a frame and window decorations\n"
3780e197 6557 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
667accab
TS
6558 "-no-quit disable SDL window close capability\n"
6559#endif
52ca8d6a
FB
6560#ifdef TARGET_I386
6561 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6562#endif
a00bad7e 6563 "-m megs set virtual RAM size to megs MB [default=%d]\n"
91fc2119 6564 "-smp n set the number of CPUs to 'n' [default=1]\n"
c4b1fcc0 6565 "-nographic disable graphical output and redirect serial I/Os to console\n"
a171fe39 6566 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4ca0074c 6567#ifndef _WIN32
667accab 6568 "-k language use keyboard layout (for example \"fr\" for French)\n"
4ca0074c 6569#endif
1d14ffa9 6570#ifdef HAS_AUDIO
1d14ffa9 6571 "-audio-help print list of audio drivers and their options\n"
c0fe3827
FB
6572 "-soundhw c1,... enable audio support\n"
6573 " and only specified sound cards (comma separated list)\n"
6574 " use -soundhw ? to get the list of supported cards\n"
6a36d84e 6575 " use -soundhw all to enable all of them\n"
1d14ffa9 6576#endif
89980284 6577 "-localtime set the real time clock to local time [default=utc]\n"
d63d307f 6578 "-full-screen start in full screen\n"
a09db21f
FB
6579#ifdef TARGET_I386
6580 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6581#endif
b389dbfb
FB
6582 "-usb enable the USB driver (will be the default soon)\n"
6583 "-usbdevice name add the host or guest USB device 'name'\n"
6f7e9aec
FB
6584#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6585 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
bb0c6722 6586#endif
c35734b2 6587 "-name string set the name of the guest\n"
c4b1fcc0
FB
6588 "\n"
6589 "Network options:\n"
a41b2ff2 6590 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7c9d8e07 6591 " create a new Network Interface Card and connect it to VLAN 'n'\n"
c20709aa 6592#ifdef CONFIG_SLIRP
115defd1
PB
6593 "-net user[,vlan=n][,hostname=host]\n"
6594 " connect the user mode network stack to VLAN 'n' and send\n"
6595 " hostname 'host' to DHCP clients\n"
7c9d8e07 6596#endif
7fb843f8
FB
6597#ifdef _WIN32
6598 "-net tap[,vlan=n],ifname=name\n"
6599 " connect the host TAP network interface to VLAN 'n'\n"
6600#else
7c9d8e07
FB
6601 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6602 " connect the host TAP network interface to VLAN 'n' and use\n"
6603 " the network script 'file' (default=%s);\n"
6a1cbf68 6604 " use 'script=no' to disable script execution;\n"
7c9d8e07 6605 " use 'fd=h' to connect to an already opened TAP interface\n"
7fb843f8 6606#endif
6a00d601 6607 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7c9d8e07 6608 " connect the vlan 'n' to another VLAN using a socket connection\n"
3d830459
FB
6609 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6610 " connect the vlan 'n' to multicast maddr and port\n"
7c9d8e07
FB
6611 "-net none use it alone to have zero network devices; if no -net option\n"
6612 " is provided, the default is '-net nic -net user'\n"
6613 "\n"
6614#ifdef CONFIG_SLIRP
0db1137d 6615 "-tftp dir allow tftp access to files in dir [-net user]\n"
47d5d01a 6616 "-bootp file advertise file in BOOTP replies\n"
7c9d8e07
FB
6617#ifndef _WIN32
6618 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
c94c8d64 6619#endif
9bf05444 6620 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7c9d8e07 6621 " redirect TCP or UDP connections from host to guest [-net user]\n"
c20709aa 6622#endif
a20dd508 6623 "\n"
c4b1fcc0 6624 "Linux boot specific:\n"
a20dd508
FB
6625 "-kernel bzImage use 'bzImage' as kernel image\n"
6626 "-append cmdline use 'cmdline' as kernel command line\n"
6627 "-initrd file use 'file' as initial ram disk\n"
fc01f7e7 6628 "\n"
330d0414 6629 "Debug/Expert options:\n"
82c643ff
FB
6630 "-monitor dev redirect the monitor to char device 'dev'\n"
6631 "-serial dev redirect the serial port to char device 'dev'\n"
6508fe59 6632 "-parallel dev redirect the parallel port to char device 'dev'\n"
f7cce898 6633 "-pidfile file Write PID to 'file'\n"
cd6f1169 6634 "-S freeze CPU at startup (use 'c' to start execution)\n"
cfc3475a
PB
6635 "-s wait gdb connection to port\n"
6636 "-p port set gdb connection port [default=%s]\n"
f193c797 6637 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
46d4767d
FB
6638 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6639 " translation (t=none or lba) (usually qemu can guess them)\n"
87b47350 6640 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
d993e026 6641#ifdef USE_KQEMU
6515b203 6642 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
d993e026
FB
6643 "-no-kqemu disable KQEMU kernel module usage\n"
6644#endif
77fef8c1
FB
6645#ifdef USE_CODE_COPY
6646 "-no-code-copy disable code copy acceleration\n"
6647#endif
bb0c6722 6648#ifdef TARGET_I386
1bfe856e
FB
6649 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6650 " (default is CL-GD5446 PCI VGA)\n"
6515b203 6651 "-no-acpi disable ACPI\n"
bb0c6722 6652#endif
d1beab82 6653 "-no-reboot exit instead of rebooting\n"
d63d307f 6654 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
24236869 6655 "-vnc display start a VNC server on display\n"
71e3ceb8
TS
6656#ifndef _WIN32
6657 "-daemonize daemonize QEMU after initializing\n"
6658#endif
9ae02555 6659 "-option-rom rom load a file, rom, into the option ROM space\n"
66508601
BS
6660#ifdef TARGET_SPARC
6661 "-prom-env variable=value set OpenBIOS nvram variables\n"
6662#endif
0824d6fc 6663 "\n"
82c643ff 6664 "During emulation, the following keys are useful:\n"
032a8c9e
FB
6665 "ctrl-alt-f toggle full screen\n"
6666 "ctrl-alt-n switch to virtual console 'n'\n"
6667 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
6668 "\n"
6669 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6670 ,
0db63474 6671 "qemu",
a00bad7e 6672 DEFAULT_RAM_SIZE,
7c9d8e07 6673#ifndef _WIN32
a00bad7e 6674 DEFAULT_NETWORK_SCRIPT,
7c9d8e07 6675#endif
6e44ba7f
FB
6676 DEFAULT_GDBSTUB_PORT,
6677 "/tmp/qemu.log");
0824d6fc
FB
6678 exit(1);
6679}
6680
cd6f1169
FB
6681#define HAS_ARG 0x0001
6682
6683enum {
6684 QEMU_OPTION_h,
6685
cc1daa40 6686 QEMU_OPTION_M,
94fc95cd 6687 QEMU_OPTION_cpu,
cd6f1169
FB
6688 QEMU_OPTION_fda,
6689 QEMU_OPTION_fdb,
6690 QEMU_OPTION_hda,
6691 QEMU_OPTION_hdb,
6692 QEMU_OPTION_hdc,
6693 QEMU_OPTION_hdd,
6694 QEMU_OPTION_cdrom,
3e3d5815 6695 QEMU_OPTION_mtdblock,
a1bb27b1 6696 QEMU_OPTION_sd,
86f55663 6697 QEMU_OPTION_pflash,
cd6f1169
FB
6698 QEMU_OPTION_boot,
6699 QEMU_OPTION_snapshot,
52ca8d6a
FB
6700#ifdef TARGET_I386
6701 QEMU_OPTION_no_fd_bootchk,
6702#endif
cd6f1169
FB
6703 QEMU_OPTION_m,
6704 QEMU_OPTION_nographic,
a171fe39 6705 QEMU_OPTION_portrait,
1d14ffa9 6706#ifdef HAS_AUDIO
1d14ffa9
FB
6707 QEMU_OPTION_audio_help,
6708 QEMU_OPTION_soundhw,
6709#endif
cd6f1169 6710
7c9d8e07 6711 QEMU_OPTION_net,
c7f74643 6712 QEMU_OPTION_tftp,
47d5d01a 6713 QEMU_OPTION_bootp,
9d728e8c 6714 QEMU_OPTION_smb,
9bf05444 6715 QEMU_OPTION_redir,
cd6f1169
FB
6716
6717 QEMU_OPTION_kernel,
6718 QEMU_OPTION_append,
6719 QEMU_OPTION_initrd,
6720
6721 QEMU_OPTION_S,
6722 QEMU_OPTION_s,
6723 QEMU_OPTION_p,
6724 QEMU_OPTION_d,
6725 QEMU_OPTION_hdachs,
6726 QEMU_OPTION_L,
6727 QEMU_OPTION_no_code_copy,
3d11d0eb 6728 QEMU_OPTION_k,
ee22c2f7 6729 QEMU_OPTION_localtime,
1f04275e 6730 QEMU_OPTION_cirrusvga,
d34cab9f 6731 QEMU_OPTION_vmsvga,
e9b137c2 6732 QEMU_OPTION_g,
1bfe856e 6733 QEMU_OPTION_std_vga,
20d8a3ed 6734 QEMU_OPTION_echr,
82c643ff
FB
6735 QEMU_OPTION_monitor,
6736 QEMU_OPTION_serial,
6508fe59 6737 QEMU_OPTION_parallel,
d63d307f
FB
6738 QEMU_OPTION_loadvm,
6739 QEMU_OPTION_full_screen,
43523e93 6740 QEMU_OPTION_no_frame,
3780e197 6741 QEMU_OPTION_alt_grab,
667accab 6742 QEMU_OPTION_no_quit,
f7cce898 6743 QEMU_OPTION_pidfile,
d993e026 6744 QEMU_OPTION_no_kqemu,
89bfc105 6745 QEMU_OPTION_kernel_kqemu,
a09db21f 6746 QEMU_OPTION_win2k_hack,
bb36d470 6747 QEMU_OPTION_usb,
a594cfbf 6748 QEMU_OPTION_usbdevice,
6a00d601 6749 QEMU_OPTION_smp,
24236869 6750 QEMU_OPTION_vnc,
6515b203 6751 QEMU_OPTION_no_acpi,
d1beab82 6752 QEMU_OPTION_no_reboot,
9467cd46 6753 QEMU_OPTION_show_cursor,
71e3ceb8 6754 QEMU_OPTION_daemonize,
9ae02555 6755 QEMU_OPTION_option_rom,
c35734b2
TS
6756 QEMU_OPTION_semihosting,
6757 QEMU_OPTION_name,
66508601 6758 QEMU_OPTION_prom_env,
cd6f1169
FB
6759};
6760
6761typedef struct QEMUOption {
6762 const char *name;
6763 int flags;
6764 int index;
6765} QEMUOption;
6766
6767const QEMUOption qemu_options[] = {
6768 { "h", 0, QEMU_OPTION_h },
64423fb2 6769 { "help", 0, QEMU_OPTION_h },
cd6f1169 6770
cc1daa40 6771 { "M", HAS_ARG, QEMU_OPTION_M },
94fc95cd 6772 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
cd6f1169
FB
6773 { "fda", HAS_ARG, QEMU_OPTION_fda },
6774 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6775 { "hda", HAS_ARG, QEMU_OPTION_hda },
6776 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6777 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6778 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6779 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3e3d5815 6780 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
a1bb27b1 6781 { "sd", HAS_ARG, QEMU_OPTION_sd },
86f55663 6782 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
cd6f1169
FB
6783 { "boot", HAS_ARG, QEMU_OPTION_boot },
6784 { "snapshot", 0, QEMU_OPTION_snapshot },
52ca8d6a
FB
6785#ifdef TARGET_I386
6786 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6787#endif
cd6f1169
FB
6788 { "m", HAS_ARG, QEMU_OPTION_m },
6789 { "nographic", 0, QEMU_OPTION_nographic },
a171fe39 6790 { "portrait", 0, QEMU_OPTION_portrait },
3d11d0eb 6791 { "k", HAS_ARG, QEMU_OPTION_k },
1d14ffa9 6792#ifdef HAS_AUDIO
1d14ffa9
FB
6793 { "audio-help", 0, QEMU_OPTION_audio_help },
6794 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6795#endif
cd6f1169 6796
7c9d8e07 6797 { "net", HAS_ARG, QEMU_OPTION_net},
158156d1 6798#ifdef CONFIG_SLIRP
c7f74643 6799 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
47d5d01a 6800 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
c94c8d64 6801#ifndef _WIN32
9d728e8c 6802 { "smb", HAS_ARG, QEMU_OPTION_smb },
c94c8d64 6803#endif
9bf05444 6804 { "redir", HAS_ARG, QEMU_OPTION_redir },
158156d1 6805#endif
cd6f1169
FB
6806
6807 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6808 { "append", HAS_ARG, QEMU_OPTION_append },
6809 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6810
6811 { "S", 0, QEMU_OPTION_S },
6812 { "s", 0, QEMU_OPTION_s },
6813 { "p", HAS_ARG, QEMU_OPTION_p },
6814 { "d", HAS_ARG, QEMU_OPTION_d },
6815 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6816 { "L", HAS_ARG, QEMU_OPTION_L },
6817 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
d993e026
FB
6818#ifdef USE_KQEMU
6819 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
89bfc105 6820 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
d993e026 6821#endif
6f7e9aec 6822#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2 6823 { "g", 1, QEMU_OPTION_g },
77d4bc34 6824#endif
ee22c2f7 6825 { "localtime", 0, QEMU_OPTION_localtime },
1bfe856e 6826 { "std-vga", 0, QEMU_OPTION_std_vga },
20d8a3ed 6827 { "echr", 1, QEMU_OPTION_echr },
82c643ff
FB
6828 { "monitor", 1, QEMU_OPTION_monitor },
6829 { "serial", 1, QEMU_OPTION_serial },
6508fe59 6830 { "parallel", 1, QEMU_OPTION_parallel },
d63d307f
FB
6831 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6832 { "full-screen", 0, QEMU_OPTION_full_screen },
667accab 6833#ifdef CONFIG_SDL
43523e93 6834 { "no-frame", 0, QEMU_OPTION_no_frame },
3780e197 6835 { "alt-grab", 0, QEMU_OPTION_alt_grab },
667accab
TS
6836 { "no-quit", 0, QEMU_OPTION_no_quit },
6837#endif
f7cce898 6838 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
a09db21f 6839 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
a594cfbf 6840 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6a00d601 6841 { "smp", HAS_ARG, QEMU_OPTION_smp },
24236869 6842 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
96d30e48 6843
1f04275e 6844 /* temporary options */
a594cfbf 6845 { "usb", 0, QEMU_OPTION_usb },
1f04275e 6846 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
d34cab9f 6847 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6515b203 6848 { "no-acpi", 0, QEMU_OPTION_no_acpi },
d1beab82 6849 { "no-reboot", 0, QEMU_OPTION_no_reboot },
9467cd46 6850 { "show-cursor", 0, QEMU_OPTION_show_cursor },
71e3ceb8 6851 { "daemonize", 0, QEMU_OPTION_daemonize },
9ae02555 6852 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
a87295e8 6853#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
6854 { "semihosting", 0, QEMU_OPTION_semihosting },
6855#endif
c35734b2 6856 { "name", HAS_ARG, QEMU_OPTION_name },
66508601
BS
6857#if defined(TARGET_SPARC)
6858 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6859#endif
cd6f1169 6860 { NULL },
fc01f7e7
FB
6861};
6862
77fef8c1
FB
6863#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6864
6865/* this stack is only used during signal handling */
6866#define SIGNAL_STACK_SIZE 32768
6867
6868static uint8_t *signal_stack;
6869
6870#endif
6871
5905b2e5
FB
6872/* password input */
6873
2bac6019
AZ
6874int qemu_key_check(BlockDriverState *bs, const char *name)
6875{
6876 char password[256];
6877 int i;
6878
6879 if (!bdrv_is_encrypted(bs))
6880 return 0;
6881
6882 term_printf("%s is encrypted.\n", name);
6883 for(i = 0; i < 3; i++) {
6884 monitor_readline("Password: ", 1, password, sizeof(password));
6885 if (bdrv_set_key(bs, password) == 0)
6886 return 0;
6887 term_printf("invalid password\n");
6888 }
6889 return -EPERM;
6890}
6891
5905b2e5
FB
6892static BlockDriverState *get_bdrv(int index)
6893{
6894 BlockDriverState *bs;
6895
6896 if (index < 4) {
6897 bs = bs_table[index];
6898 } else if (index < 6) {
6899 bs = fd_table[index - 4];
6900 } else {
6901 bs = NULL;
6902 }
6903 return bs;
6904}
6905
6906static void read_passwords(void)
6907{
6908 BlockDriverState *bs;
2bac6019 6909 int i;
5905b2e5
FB
6910
6911 for(i = 0; i < 6; i++) {
6912 bs = get_bdrv(i);
2bac6019
AZ
6913 if (bs)
6914 qemu_key_check(bs, bdrv_get_device_name(bs));
5905b2e5
FB
6915 }
6916}
6917
cc1daa40
FB
6918/* XXX: currently we cannot use simultaneously different CPUs */
6919void register_machines(void)
6920{
6921#if defined(TARGET_I386)
6922 qemu_register_machine(&pc_machine);
3dbbdc25 6923 qemu_register_machine(&isapc_machine);
cc1daa40
FB
6924#elif defined(TARGET_PPC)
6925 qemu_register_machine(&heathrow_machine);
6926 qemu_register_machine(&core99_machine);
6927 qemu_register_machine(&prep_machine);
1a6c0886
JM
6928 qemu_register_machine(&ref405ep_machine);
6929 qemu_register_machine(&taihu_machine);
6af0bf9c
FB
6930#elif defined(TARGET_MIPS)
6931 qemu_register_machine(&mips_machine);
5856de80 6932 qemu_register_machine(&mips_malta_machine);
ad6fe1d2 6933 qemu_register_machine(&mips_pica61_machine);
cc1daa40 6934#elif defined(TARGET_SPARC)
3475187d
FB
6935#ifdef TARGET_SPARC64
6936 qemu_register_machine(&sun4u_machine);
6937#else
36cd9210 6938 qemu_register_machine(&ss5_machine);
e0353fe2 6939 qemu_register_machine(&ss10_machine);
cc1daa40 6940#endif
b5ff1b31 6941#elif defined(TARGET_ARM)
3371d272 6942 qemu_register_machine(&integratorcp_machine);
cdbdb648 6943 qemu_register_machine(&versatilepb_machine);
16406950 6944 qemu_register_machine(&versatileab_machine);
e69954b9 6945 qemu_register_machine(&realview_machine);
b00052e4
AZ
6946 qemu_register_machine(&akitapda_machine);
6947 qemu_register_machine(&spitzpda_machine);
6948 qemu_register_machine(&borzoipda_machine);
6949 qemu_register_machine(&terrierpda_machine);
27c7ca7e
FB
6950#elif defined(TARGET_SH4)
6951 qemu_register_machine(&shix_machine);
eddf68a6
JM
6952#elif defined(TARGET_ALPHA)
6953 /* XXX: TODO */
0633879f 6954#elif defined(TARGET_M68K)
20dcee94 6955 qemu_register_machine(&mcf5208evb_machine);
0633879f 6956 qemu_register_machine(&an5206_machine);
b5ff1b31
FB
6957#else
6958#error unsupported CPU
3475187d 6959#endif
cc1daa40
FB
6960}
6961
1d14ffa9 6962#ifdef HAS_AUDIO
6a36d84e 6963struct soundhw soundhw[] = {
b00052e4 6964#ifdef HAS_AUDIO_CHOICE
fd06c375
FB
6965#ifdef TARGET_I386
6966 {
6967 "pcspk",
6968 "PC speaker",
6969 0,
6970 1,
6971 { .init_isa = pcspk_audio_init }
6972 },
6973#endif
6a36d84e
FB
6974 {
6975 "sb16",
6976 "Creative Sound Blaster 16",
6977 0,
6978 1,
6979 { .init_isa = SB16_init }
6980 },
6981
1d14ffa9 6982#ifdef CONFIG_ADLIB
6a36d84e
FB
6983 {
6984 "adlib",
1d14ffa9 6985#ifdef HAS_YMF262
6a36d84e 6986 "Yamaha YMF262 (OPL3)",
1d14ffa9 6987#else
6a36d84e 6988 "Yamaha YM3812 (OPL2)",
1d14ffa9 6989#endif
6a36d84e
FB
6990 0,
6991 1,
6992 { .init_isa = Adlib_init }
6993 },
1d14ffa9 6994#endif
6a36d84e 6995
1d14ffa9 6996#ifdef CONFIG_GUS
6a36d84e
FB
6997 {
6998 "gus",
6999 "Gravis Ultrasound GF1",
7000 0,
7001 1,
7002 { .init_isa = GUS_init }
7003 },
1d14ffa9 7004#endif
6a36d84e
FB
7005
7006 {
7007 "es1370",
7008 "ENSONIQ AudioPCI ES1370",
7009 0,
7010 0,
7011 { .init_pci = es1370_init }
7012 },
b00052e4 7013#endif
6a36d84e
FB
7014
7015 { NULL, NULL, 0, 0, { NULL } }
7016};
7017
7018static void select_soundhw (const char *optarg)
7019{
7020 struct soundhw *c;
7021
7022 if (*optarg == '?') {
7023 show_valid_cards:
7024
7025 printf ("Valid sound card names (comma separated):\n");
7026 for (c = soundhw; c->name; ++c) {
7027 printf ("%-11s %s\n", c->name, c->descr);
7028 }
7029 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
7030 exit (*optarg != '?');
7031 }
7032 else {
6a36d84e 7033 size_t l;
1d14ffa9
FB
7034 const char *p;
7035 char *e;
7036 int bad_card = 0;
7037
6a36d84e
FB
7038 if (!strcmp (optarg, "all")) {
7039 for (c = soundhw; c->name; ++c) {
7040 c->enabled = 1;
7041 }
7042 return;
7043 }
1d14ffa9 7044
6a36d84e 7045 p = optarg;
1d14ffa9
FB
7046 while (*p) {
7047 e = strchr (p, ',');
7048 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
7049
7050 for (c = soundhw; c->name; ++c) {
7051 if (!strncmp (c->name, p, l)) {
7052 c->enabled = 1;
1d14ffa9
FB
7053 break;
7054 }
7055 }
6a36d84e
FB
7056
7057 if (!c->name) {
1d14ffa9
FB
7058 if (l > 80) {
7059 fprintf (stderr,
7060 "Unknown sound card name (too big to show)\n");
7061 }
7062 else {
7063 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7064 (int) l, p);
7065 }
7066 bad_card = 1;
7067 }
7068 p += l + (e != NULL);
7069 }
7070
7071 if (bad_card)
7072 goto show_valid_cards;
7073 }
7074}
7075#endif
7076
3587d7e6
FB
7077#ifdef _WIN32
7078static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7079{
7080 exit(STATUS_CONTROL_C_EXIT);
7081 return TRUE;
7082}
7083#endif
7084
7c9d8e07 7085#define MAX_NET_CLIENTS 32
c20709aa 7086
0824d6fc
FB
7087int main(int argc, char **argv)
7088{
67b915a5 7089#ifdef CONFIG_GDBSTUB
cfc3475a
PB
7090 int use_gdbstub;
7091 const char *gdbstub_port;
67b915a5 7092#endif
86f55663 7093 int i, cdrom_index, pflash_index;
1ccde1cb 7094 int snapshot, linux_boot;
7f7f9873 7095 const char *initrd_filename;
96d30e48 7096 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
86f55663 7097 const char *pflash_filename[MAX_PFLASH];
a1bb27b1 7098 const char *sd_filename;
3e3d5815 7099 const char *mtd_filename;
a20dd508 7100 const char *kernel_filename, *kernel_cmdline;
313aa567 7101 DisplayState *ds = &display_state;
46d4767d 7102 int cyls, heads, secs, translation;
7c9d8e07
FB
7103 char net_clients[MAX_NET_CLIENTS][256];
7104 int nb_net_clients;
cd6f1169
FB
7105 int optind;
7106 const char *r, *optarg;
82c643ff
FB
7107 CharDriverState *monitor_hd;
7108 char monitor_device[128];
8d11df9e
FB
7109 char serial_devices[MAX_SERIAL_PORTS][128];
7110 int serial_device_index;
6508fe59
FB
7111 char parallel_devices[MAX_PARALLEL_PORTS][128];
7112 int parallel_device_index;
d63d307f 7113 const char *loadvm = NULL;
cc1daa40 7114 QEMUMachine *machine;
94fc95cd 7115 const char *cpu_model;
0d92ed30 7116 char usb_devices[MAX_USB_CMDLINE][128];
a594cfbf 7117 int usb_devices_index;
71e3ceb8 7118 int fds[2];
93815bc2 7119 const char *pid_file = NULL;
833c7174 7120 VLANState *vlan;
0bd48850
FB
7121
7122 LIST_INIT (&vm_change_state_head);
be995c27
FB
7123#ifndef _WIN32
7124 {
7125 struct sigaction act;
7126 sigfillset(&act.sa_mask);
7127 act.sa_flags = 0;
7128 act.sa_handler = SIG_IGN;
7129 sigaction(SIGPIPE, &act, NULL);
7130 }
3587d7e6
FB
7131#else
7132 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
7133 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7134 QEMU to run on a single CPU */
7135 {
7136 HANDLE h;
7137 DWORD mask, smask;
7138 int i;
7139 h = GetCurrentProcess();
7140 if (GetProcessAffinityMask(h, &mask, &smask)) {
7141 for(i = 0; i < 32; i++) {
7142 if (mask & (1 << i))
7143 break;
7144 }
7145 if (i != 32) {
7146 mask = 1 << i;
7147 SetProcessAffinityMask(h, mask);
7148 }
7149 }
7150 }
67b915a5 7151#endif
be995c27 7152
cc1daa40
FB
7153 register_machines();
7154 machine = first_machine;
94fc95cd 7155 cpu_model = NULL;
fc01f7e7 7156 initrd_filename = NULL;
c45886db
FB
7157 for(i = 0; i < MAX_FD; i++)
7158 fd_filename[i] = NULL;
96d30e48
TS
7159 for(i = 0; i < MAX_DISKS; i++)
7160 hd_filename[i] = NULL;
86f55663
JM
7161 for(i = 0; i < MAX_PFLASH; i++)
7162 pflash_filename[i] = NULL;
7163 pflash_index = 0;
a1bb27b1 7164 sd_filename = NULL;
3e3d5815 7165 mtd_filename = NULL;
a00bad7e 7166 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
313aa567 7167 vga_ram_size = VGA_RAM_SIZE;
67b915a5 7168#ifdef CONFIG_GDBSTUB
b4608c04 7169 use_gdbstub = 0;
c636bb66 7170 gdbstub_port = DEFAULT_GDBSTUB_PORT;
67b915a5 7171#endif
33e3963e 7172 snapshot = 0;
a20dd508
FB
7173 nographic = 0;
7174 kernel_filename = NULL;
7175 kernel_cmdline = "";
cc1daa40
FB
7176#ifdef TARGET_PPC
7177 cdrom_index = 1;
7178#else
7179 cdrom_index = 2;
7180#endif
c4b1fcc0 7181 cyls = heads = secs = 0;
46d4767d 7182 translation = BIOS_ATA_TRANSLATION_AUTO;
82c643ff 7183 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
c4b1fcc0 7184
8d11df9e
FB
7185 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7186 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7187 serial_devices[i][0] = '\0';
7188 serial_device_index = 0;
7189
6508fe59
FB
7190 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7191 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7192 parallel_devices[i][0] = '\0';
7193 parallel_device_index = 0;
7194
a594cfbf
FB
7195 usb_devices_index = 0;
7196
7c9d8e07
FB
7197 nb_net_clients = 0;
7198
7199 nb_nics = 0;
702c651c 7200 /* default mac address of the first network interface */
82c643ff 7201
cd6f1169 7202 optind = 1;
0824d6fc 7203 for(;;) {
cd6f1169 7204 if (optind >= argc)
0824d6fc 7205 break;
cd6f1169
FB
7206 r = argv[optind];
7207 if (r[0] != '-') {
96d30e48 7208 hd_filename[0] = argv[optind++];
cd6f1169
FB
7209 } else {
7210 const QEMUOption *popt;
7211
7212 optind++;
dff5efc8
PB
7213 /* Treat --foo the same as -foo. */
7214 if (r[1] == '-')
7215 r++;
cd6f1169
FB
7216 popt = qemu_options;
7217 for(;;) {
7218 if (!popt->name) {
7219 fprintf(stderr, "%s: invalid option -- '%s'\n",
7220 argv[0], r);
7221 exit(1);
7222 }
7223 if (!strcmp(popt->name, r + 1))
7224 break;
7225 popt++;
7226 }
7227 if (popt->flags & HAS_ARG) {
7228 if (optind >= argc) {
7229 fprintf(stderr, "%s: option '%s' requires an argument\n",
7230 argv[0], r);
7231 exit(1);
7232 }
7233 optarg = argv[optind++];
7234 } else {
7235 optarg = NULL;
7236 }
7237
7238 switch(popt->index) {
cc1daa40
FB
7239 case QEMU_OPTION_M:
7240 machine = find_machine(optarg);
7241 if (!machine) {
7242 QEMUMachine *m;
7243 printf("Supported machines are:\n");
7244 for(m = first_machine; m != NULL; m = m->next) {
7245 printf("%-10s %s%s\n",
7246 m->name, m->desc,
7247 m == first_machine ? " (default)" : "");
7248 }
7249 exit(1);
7250 }
7251 break;
94fc95cd
JM
7252 case QEMU_OPTION_cpu:
7253 /* hw initialization will check this */
7254 if (optarg[0] == '?') {
7255#if defined(TARGET_PPC)
7256 ppc_cpu_list(stdout, &fprintf);
5adb4839
PB
7257#elif defined(TARGET_ARM)
7258 arm_cpu_list();
33d68b5f
TS
7259#elif defined(TARGET_MIPS)
7260 mips_cpu_list(stdout, &fprintf);
62724a37
BS
7261#elif defined(TARGET_SPARC)
7262 sparc_cpu_list(stdout, &fprintf);
94fc95cd
JM
7263#endif
7264 exit(1);
7265 } else {
7266 cpu_model = optarg;
7267 }
7268 break;
cd6f1169 7269 case QEMU_OPTION_initrd:
fc01f7e7
FB
7270 initrd_filename = optarg;
7271 break;
cd6f1169 7272 case QEMU_OPTION_hda:
cd6f1169 7273 case QEMU_OPTION_hdb:
cc1daa40
FB
7274 case QEMU_OPTION_hdc:
7275 case QEMU_OPTION_hdd:
7276 {
7277 int hd_index;
7278 hd_index = popt->index - QEMU_OPTION_hda;
96d30e48
TS
7279 hd_filename[hd_index] = optarg;
7280 if (hd_index == cdrom_index)
7281 cdrom_index = -1;
cc1daa40 7282 }
fc01f7e7 7283 break;
3e3d5815
AZ
7284 case QEMU_OPTION_mtdblock:
7285 mtd_filename = optarg;
7286 break;
a1bb27b1
PB
7287 case QEMU_OPTION_sd:
7288 sd_filename = optarg;
7289 break;
86f55663
JM
7290 case QEMU_OPTION_pflash:
7291 if (pflash_index >= MAX_PFLASH) {
7292 fprintf(stderr, "qemu: too many parallel flash images\n");
7293 exit(1);
7294 }
7295 pflash_filename[pflash_index++] = optarg;
7296 break;
cd6f1169 7297 case QEMU_OPTION_snapshot:
33e3963e
FB
7298 snapshot = 1;
7299 break;
cd6f1169 7300 case QEMU_OPTION_hdachs:
330d0414 7301 {
330d0414
FB
7302 const char *p;
7303 p = optarg;
7304 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
7305 if (cyls < 1 || cyls > 16383)
7306 goto chs_fail;
330d0414
FB
7307 if (*p != ',')
7308 goto chs_fail;
7309 p++;
7310 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
7311 if (heads < 1 || heads > 16)
7312 goto chs_fail;
330d0414
FB
7313 if (*p != ',')
7314 goto chs_fail;
7315 p++;
7316 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
7317 if (secs < 1 || secs > 63)
7318 goto chs_fail;
7319 if (*p == ',') {
7320 p++;
7321 if (!strcmp(p, "none"))
7322 translation = BIOS_ATA_TRANSLATION_NONE;
7323 else if (!strcmp(p, "lba"))
7324 translation = BIOS_ATA_TRANSLATION_LBA;
7325 else if (!strcmp(p, "auto"))
7326 translation = BIOS_ATA_TRANSLATION_AUTO;
7327 else
7328 goto chs_fail;
7329 } else if (*p != '\0') {
c4b1fcc0 7330 chs_fail:
46d4767d
FB
7331 fprintf(stderr, "qemu: invalid physical CHS format\n");
7332 exit(1);
c4b1fcc0 7333 }
330d0414
FB
7334 }
7335 break;
cd6f1169 7336 case QEMU_OPTION_nographic:
8d11df9e 7337 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
a39437aa 7338 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
20d8a3ed 7339 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
a20dd508
FB
7340 nographic = 1;
7341 break;
a171fe39
AZ
7342 case QEMU_OPTION_portrait:
7343 graphic_rotate = 1;
7344 break;
cd6f1169 7345 case QEMU_OPTION_kernel:
a20dd508
FB
7346 kernel_filename = optarg;
7347 break;
cd6f1169 7348 case QEMU_OPTION_append:
a20dd508 7349 kernel_cmdline = optarg;
313aa567 7350 break;
cd6f1169 7351 case QEMU_OPTION_cdrom:
96d30e48
TS
7352 if (cdrom_index >= 0) {
7353 hd_filename[cdrom_index] = optarg;
fa1fb14c 7354 }
36b486bb 7355 break;
cd6f1169 7356 case QEMU_OPTION_boot:
36b486bb 7357 boot_device = optarg[0];
9e89a4be 7358 if (boot_device != 'a' &&
eec85c2a 7359#if defined(TARGET_SPARC) || defined(TARGET_I386)
6f7e9aec
FB
7360 // Network boot
7361 boot_device != 'n' &&
7362#endif
c45886db 7363 boot_device != 'c' && boot_device != 'd') {
36b486bb
FB
7364 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7365 exit(1);
7366 }
7367 break;
cd6f1169 7368 case QEMU_OPTION_fda:
c45886db
FB
7369 fd_filename[0] = optarg;
7370 break;
cd6f1169 7371 case QEMU_OPTION_fdb:
c45886db
FB
7372 fd_filename[1] = optarg;
7373 break;
52ca8d6a
FB
7374#ifdef TARGET_I386
7375 case QEMU_OPTION_no_fd_bootchk:
7376 fd_bootchk = 0;
7377 break;
7378#endif
cd6f1169 7379 case QEMU_OPTION_no_code_copy:
77fef8c1
FB
7380 code_copy_enabled = 0;
7381 break;
7c9d8e07
FB
7382 case QEMU_OPTION_net:
7383 if (nb_net_clients >= MAX_NET_CLIENTS) {
7384 fprintf(stderr, "qemu: too many network clients\n");
c4b1fcc0
FB
7385 exit(1);
7386 }
7c9d8e07
FB
7387 pstrcpy(net_clients[nb_net_clients],
7388 sizeof(net_clients[0]),
7389 optarg);
7390 nb_net_clients++;
702c651c 7391 break;
c7f74643
FB
7392#ifdef CONFIG_SLIRP
7393 case QEMU_OPTION_tftp:
c7f74643 7394 tftp_prefix = optarg;
9bf05444 7395 break;
47d5d01a
TS
7396 case QEMU_OPTION_bootp:
7397 bootp_filename = optarg;
7398 break;
c94c8d64 7399#ifndef _WIN32
9d728e8c
FB
7400 case QEMU_OPTION_smb:
7401 net_slirp_smb(optarg);
7402 break;
c94c8d64 7403#endif
9bf05444
FB
7404 case QEMU_OPTION_redir:
7405 net_slirp_redir(optarg);
7406 break;
c7f74643 7407#endif
1d14ffa9 7408#ifdef HAS_AUDIO
1d14ffa9
FB
7409 case QEMU_OPTION_audio_help:
7410 AUD_help ();
7411 exit (0);
7412 break;
7413 case QEMU_OPTION_soundhw:
7414 select_soundhw (optarg);
7415 break;
7416#endif
cd6f1169 7417 case QEMU_OPTION_h:
0824d6fc 7418 help();
cd6f1169
FB
7419 break;
7420 case QEMU_OPTION_m:
7421 ram_size = atoi(optarg) * 1024 * 1024;
7422 if (ram_size <= 0)
7423 help();
7424 if (ram_size > PHYS_RAM_MAX_SIZE) {
7425 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7426 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7427 exit(1);
7428 }
7429 break;
7430 case QEMU_OPTION_d:
7431 {
7432 int mask;
7433 CPULogItem *item;
7434
7435 mask = cpu_str_to_log_mask(optarg);
7436 if (!mask) {
7437 printf("Log items (comma separated):\n");
f193c797
FB
7438 for(item = cpu_log_items; item->mask != 0; item++) {
7439 printf("%-10s %s\n", item->name, item->help);
7440 }
7441 exit(1);
cd6f1169
FB
7442 }
7443 cpu_set_log(mask);
f193c797 7444 }
cd6f1169 7445 break;
67b915a5 7446#ifdef CONFIG_GDBSTUB
cd6f1169
FB
7447 case QEMU_OPTION_s:
7448 use_gdbstub = 1;
7449 break;
7450 case QEMU_OPTION_p:
cfc3475a 7451 gdbstub_port = optarg;
cd6f1169 7452 break;
67b915a5 7453#endif
cd6f1169
FB
7454 case QEMU_OPTION_L:
7455 bios_dir = optarg;
7456 break;
7457 case QEMU_OPTION_S:
3c07f8e8 7458 autostart = 0;
cd6f1169 7459 break;
3d11d0eb
FB
7460 case QEMU_OPTION_k:
7461 keyboard_layout = optarg;
7462 break;
ee22c2f7
FB
7463 case QEMU_OPTION_localtime:
7464 rtc_utc = 0;
7465 break;
1f04275e
FB
7466 case QEMU_OPTION_cirrusvga:
7467 cirrus_vga_enabled = 1;
d34cab9f
TS
7468 vmsvga_enabled = 0;
7469 break;
7470 case QEMU_OPTION_vmsvga:
7471 cirrus_vga_enabled = 0;
7472 vmsvga_enabled = 1;
1f04275e 7473 break;
1bfe856e
FB
7474 case QEMU_OPTION_std_vga:
7475 cirrus_vga_enabled = 0;
d34cab9f 7476 vmsvga_enabled = 0;
1bfe856e 7477 break;
e9b137c2
FB
7478 case QEMU_OPTION_g:
7479 {
7480 const char *p;
7481 int w, h, depth;
7482 p = optarg;
7483 w = strtol(p, (char **)&p, 10);
7484 if (w <= 0) {
7485 graphic_error:
7486 fprintf(stderr, "qemu: invalid resolution or depth\n");
7487 exit(1);
7488 }
7489 if (*p != 'x')
7490 goto graphic_error;
7491 p++;
7492 h = strtol(p, (char **)&p, 10);
7493 if (h <= 0)
7494 goto graphic_error;
7495 if (*p == 'x') {
7496 p++;
7497 depth = strtol(p, (char **)&p, 10);
7498 if (depth != 8 && depth != 15 && depth != 16 &&
7499 depth != 24 && depth != 32)
7500 goto graphic_error;
7501 } else if (*p == '\0') {
7502 depth = graphic_depth;
7503 } else {
7504 goto graphic_error;
7505 }
7506
7507 graphic_width = w;
7508 graphic_height = h;
7509 graphic_depth = depth;
7510 }
7511 break;
20d8a3ed
TS
7512 case QEMU_OPTION_echr:
7513 {
7514 char *r;
7515 term_escape_char = strtol(optarg, &r, 0);
7516 if (r == optarg)
7517 printf("Bad argument to echr\n");
7518 break;
7519 }
82c643ff
FB
7520 case QEMU_OPTION_monitor:
7521 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7522 break;
7523 case QEMU_OPTION_serial:
8d11df9e
FB
7524 if (serial_device_index >= MAX_SERIAL_PORTS) {
7525 fprintf(stderr, "qemu: too many serial ports\n");
7526 exit(1);
7527 }
7528 pstrcpy(serial_devices[serial_device_index],
7529 sizeof(serial_devices[0]), optarg);
7530 serial_device_index++;
82c643ff 7531 break;
6508fe59
FB
7532 case QEMU_OPTION_parallel:
7533 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7534 fprintf(stderr, "qemu: too many parallel ports\n");
7535 exit(1);
7536 }
7537 pstrcpy(parallel_devices[parallel_device_index],
7538 sizeof(parallel_devices[0]), optarg);
7539 parallel_device_index++;
7540 break;
d63d307f
FB
7541 case QEMU_OPTION_loadvm:
7542 loadvm = optarg;
7543 break;
7544 case QEMU_OPTION_full_screen:
7545 full_screen = 1;
7546 break;
667accab 7547#ifdef CONFIG_SDL
43523e93
TS
7548 case QEMU_OPTION_no_frame:
7549 no_frame = 1;
7550 break;
3780e197
TS
7551 case QEMU_OPTION_alt_grab:
7552 alt_grab = 1;
7553 break;
667accab
TS
7554 case QEMU_OPTION_no_quit:
7555 no_quit = 1;
7556 break;
7557#endif
f7cce898 7558 case QEMU_OPTION_pidfile:
93815bc2 7559 pid_file = optarg;
f7cce898 7560 break;
a09db21f
FB
7561#ifdef TARGET_I386
7562 case QEMU_OPTION_win2k_hack:
7563 win2k_install_hack = 1;
7564 break;
7565#endif
d993e026
FB
7566#ifdef USE_KQEMU
7567 case QEMU_OPTION_no_kqemu:
7568 kqemu_allowed = 0;
7569 break;
89bfc105
FB
7570 case QEMU_OPTION_kernel_kqemu:
7571 kqemu_allowed = 2;
7572 break;
d993e026 7573#endif
bb36d470
FB
7574 case QEMU_OPTION_usb:
7575 usb_enabled = 1;
7576 break;
a594cfbf
FB
7577 case QEMU_OPTION_usbdevice:
7578 usb_enabled = 1;
0d92ed30 7579 if (usb_devices_index >= MAX_USB_CMDLINE) {
a594cfbf
FB
7580 fprintf(stderr, "Too many USB devices\n");
7581 exit(1);
7582 }
7583 pstrcpy(usb_devices[usb_devices_index],
7584 sizeof(usb_devices[usb_devices_index]),
7585 optarg);
7586 usb_devices_index++;
7587 break;
6a00d601
FB
7588 case QEMU_OPTION_smp:
7589 smp_cpus = atoi(optarg);
ba3c64fb 7590 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6a00d601
FB
7591 fprintf(stderr, "Invalid number of CPUs\n");
7592 exit(1);
7593 }
7594 break;
24236869 7595 case QEMU_OPTION_vnc:
73fc9742 7596 vnc_display = optarg;
24236869 7597 break;
6515b203
FB
7598 case QEMU_OPTION_no_acpi:
7599 acpi_enabled = 0;
7600 break;
d1beab82
FB
7601 case QEMU_OPTION_no_reboot:
7602 no_reboot = 1;
7603 break;
9467cd46
AZ
7604 case QEMU_OPTION_show_cursor:
7605 cursor_hide = 0;
7606 break;
71e3ceb8
TS
7607 case QEMU_OPTION_daemonize:
7608 daemonize = 1;
7609 break;
9ae02555
TS
7610 case QEMU_OPTION_option_rom:
7611 if (nb_option_roms >= MAX_OPTION_ROMS) {
7612 fprintf(stderr, "Too many option ROMs\n");
7613 exit(1);
7614 }
7615 option_rom[nb_option_roms] = optarg;
7616 nb_option_roms++;
7617 break;
8e71621f
PB
7618 case QEMU_OPTION_semihosting:
7619 semihosting_enabled = 1;
7620 break;
c35734b2
TS
7621 case QEMU_OPTION_name:
7622 qemu_name = optarg;
7623 break;
66508601
BS
7624#ifdef TARGET_SPARC
7625 case QEMU_OPTION_prom_env:
7626 if (nb_prom_envs >= MAX_PROM_ENVS) {
7627 fprintf(stderr, "Too many prom variables\n");
7628 exit(1);
7629 }
7630 prom_envs[nb_prom_envs] = optarg;
7631 nb_prom_envs++;
7632 break;
7633#endif
cd6f1169 7634 }
0824d6fc
FB
7635 }
7636 }
330d0414 7637
71e3ceb8
TS
7638#ifndef _WIN32
7639 if (daemonize && !nographic && vnc_display == NULL) {
7640 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7641 daemonize = 0;
7642 }
7643
7644 if (daemonize) {
7645 pid_t pid;
7646
7647 if (pipe(fds) == -1)
7648 exit(1);
7649
7650 pid = fork();
7651 if (pid > 0) {
7652 uint8_t status;
7653 ssize_t len;
7654
7655 close(fds[1]);
7656
7657 again:
93815bc2
TS
7658 len = read(fds[0], &status, 1);
7659 if (len == -1 && (errno == EINTR))
7660 goto again;
7661
7662 if (len != 1)
7663 exit(1);
7664 else if (status == 1) {
7665 fprintf(stderr, "Could not acquire pidfile\n");
7666 exit(1);
7667 } else
7668 exit(0);
71e3ceb8 7669 } else if (pid < 0)
93815bc2 7670 exit(1);
71e3ceb8
TS
7671
7672 setsid();
7673
7674 pid = fork();
7675 if (pid > 0)
7676 exit(0);
7677 else if (pid < 0)
7678 exit(1);
7679
7680 umask(027);
7681 chdir("/");
7682
7683 signal(SIGTSTP, SIG_IGN);
7684 signal(SIGTTOU, SIG_IGN);
7685 signal(SIGTTIN, SIG_IGN);
7686 }
7687#endif
7688
aa26bb2d 7689 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
7690 if (daemonize) {
7691 uint8_t status = 1;
7692 write(fds[1], &status, 1);
7693 } else
7694 fprintf(stderr, "Could not acquire pid file\n");
7695 exit(1);
7696 }
7697
ff3fbb30
FB
7698#ifdef USE_KQEMU
7699 if (smp_cpus > 1)
7700 kqemu_allowed = 0;
7701#endif
a20dd508 7702 linux_boot = (kernel_filename != NULL);
42550fde
TS
7703
7704 if (!linux_boot &&
d84fe7ae 7705 boot_device != 'n' &&
96d30e48
TS
7706 hd_filename[0] == '\0' &&
7707 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
c45886db 7708 fd_filename[0] == '\0')
0824d6fc
FB
7709 help();
7710
96d30e48
TS
7711 /* boot to floppy or the default cd if no hard disk defined yet */
7712 if (hd_filename[0] == '\0' && boot_device == 'c') {
7713 if (fd_filename[0] != '\0')
7714 boot_device = 'a';
7715 else
7716 boot_device = 'd';
7717 }
7718
b118d61e 7719 setvbuf(stdout, NULL, _IOLBF, 0);
7c9d8e07 7720
634fce96
PB
7721 init_timers();
7722 init_timer_alarm();
83f64091 7723 qemu_aio_init();
634fce96 7724
fd1dff4b
FB
7725#ifdef _WIN32
7726 socket_init();
7727#endif
7728
7c9d8e07
FB
7729 /* init network clients */
7730 if (nb_net_clients == 0) {
7731 /* if no clients, we use a default config */
7732 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7733 "nic");
7734 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7735 "user");
7736 nb_net_clients = 2;
c20709aa
FB
7737 }
7738
7c9d8e07
FB
7739 for(i = 0;i < nb_net_clients; i++) {
7740 if (net_client_init(net_clients[i]) < 0)
7741 exit(1);
702c651c 7742 }
833c7174
BS
7743 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7744 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7745 continue;
7746 if (vlan->nb_guest_devs == 0) {
7747 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7748 exit(1);
7749 }
7750 if (vlan->nb_host_devs == 0)
7751 fprintf(stderr,
7752 "Warning: vlan %d is not connected to host network\n",
7753 vlan->id);
7754 }
f1510b2c 7755
eec85c2a
TS
7756#ifdef TARGET_I386
7757 if (boot_device == 'n') {
7758 for (i = 0; i < nb_nics; i++) {
7759 const char *model = nd_table[i].model;
7760 char buf[1024];
7761 if (model == NULL)
7762 model = "ne2k_pci";
7763 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7764 if (get_image_size(buf) > 0) {
7765 option_rom[nb_option_roms] = strdup(buf);
7766 nb_option_roms++;
7767 break;
7768 }
7769 }
7770 if (i == nb_nics) {
7771 fprintf(stderr, "No valid PXE rom found for network device\n");
7772 exit(1);
7773 }
7774 boot_device = 'c'; /* to prevent confusion by the BIOS */
7775 }
7776#endif
7777
0824d6fc 7778 /* init the memory */
970ac5a3 7779 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9ae02555 7780
d993e026 7781 phys_ram_base = qemu_vmalloc(phys_ram_size);
7f7f9873
FB
7782 if (!phys_ram_base) {
7783 fprintf(stderr, "Could not allocate physical memory\n");
0824d6fc
FB
7784 exit(1);
7785 }
7786
96d30e48 7787 /* we always create the cdrom drive, even if no disk is there */
5905b2e5 7788 bdrv_init();
96d30e48
TS
7789 if (cdrom_index >= 0) {
7790 bs_table[cdrom_index] = bdrv_new("cdrom");
7791 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
c4b1fcc0
FB
7792 }
7793
96d30e48
TS
7794 /* open the virtual block devices */
7795 for(i = 0; i < MAX_DISKS; i++) {
7796 if (hd_filename[i]) {
7797 if (!bs_table[i]) {
7798 char buf[64];
7799 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7800 bs_table[i] = bdrv_new(buf);
7801 }
7802 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7803 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7804 hd_filename[i]);
7805 exit(1);
7806 }
7807 if (i == 0 && cyls != 0) {
7808 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7809 bdrv_set_translation_hint(bs_table[i], translation);
7810 }
7811 }
c4b1fcc0
FB
7812 }
7813
7814 /* we always create at least one floppy disk */
7815 fd_table[0] = bdrv_new("fda");
7816 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7817
7818 for(i = 0; i < MAX_FD; i++) {
7819 if (fd_filename[i]) {
7820 if (!fd_table[i]) {
7821 char buf[64];
7822 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7823 fd_table[i] = bdrv_new(buf);
7824 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7825 }
a1bb27b1 7826 if (fd_filename[i][0] != '\0') {
83f64091
FB
7827 if (bdrv_open(fd_table[i], fd_filename[i],
7828 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
c20709aa 7829 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
c4b1fcc0
FB
7830 fd_filename[i]);
7831 exit(1);
7832 }
7833 }
33e3963e
FB
7834 }
7835 }
7836
2bac6019 7837 /* Open the virtual parallel flash block devices */
86f55663
JM
7838 for(i = 0; i < MAX_PFLASH; i++) {
7839 if (pflash_filename[i]) {
7840 if (!pflash_table[i]) {
7841 char buf[64];
7842 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7843 pflash_table[i] = bdrv_new(buf);
7844 }
7845 if (bdrv_open(pflash_table[i], pflash_filename[i],
7846 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7847 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7848 pflash_filename[i]);
7849 exit(1);
7850 }
7851 }
7852 }
7853
a1bb27b1
PB
7854 sd_bdrv = bdrv_new ("sd");
7855 /* FIXME: This isn't really a floppy, but it's a reasonable
7856 approximation. */
7857 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7858 if (sd_filename) {
7859 if (bdrv_open(sd_bdrv, sd_filename,
7860 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7861 fprintf(stderr, "qemu: could not open SD card image %s\n",
7862 sd_filename);
2bac6019 7863 } else
a171fe39 7864 qemu_key_check(sd_bdrv, sd_filename);
a1bb27b1
PB
7865 }
7866
3e3d5815
AZ
7867 if (mtd_filename) {
7868 mtd_bdrv = bdrv_new ("mtd");
7869 if (bdrv_open(mtd_bdrv, mtd_filename,
7870 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7871 qemu_key_check(mtd_bdrv, mtd_filename)) {
7872 fprintf(stderr, "qemu: could not open Flash image %s\n",
7873 mtd_filename);
7874 bdrv_delete(mtd_bdrv);
7875 mtd_bdrv = 0;
7876 }
7877 }
7878
c88676f8
FB
7879 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7880 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8a7ddc38 7881
330d0414 7882 init_ioports();
0824d6fc 7883
313aa567 7884 /* terminal init */
740733bb 7885 memset(&display_state, 0, sizeof(display_state));
a20dd508 7886 if (nographic) {
740733bb 7887 /* nothing to do */
73fc9742 7888 } else if (vnc_display != NULL) {
740733bb 7889 vnc_display_init(ds, vnc_display);
313aa567 7890 } else {
5b0753e0 7891#if defined(CONFIG_SDL)
43523e93 7892 sdl_display_init(ds, full_screen, no_frame);
5b0753e0
FB
7893#elif defined(CONFIG_COCOA)
7894 cocoa_display_init(ds, full_screen);
313aa567
FB
7895#endif
7896 }
0824d6fc 7897
20d8a3ed
TS
7898 /* Maintain compatibility with multiple stdio monitors */
7899 if (!strcmp(monitor_device,"stdio")) {
7900 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7901 if (!strcmp(serial_devices[i],"mon:stdio")) {
7902 monitor_device[0] = '\0';
7903 break;
7904 } else if (!strcmp(serial_devices[i],"stdio")) {
7905 monitor_device[0] = '\0';
7906 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7907 break;
7908 }
7909 }
7910 }
7911 if (monitor_device[0] != '\0') {
7912 monitor_hd = qemu_chr_open(monitor_device);
7913 if (!monitor_hd) {
7914 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7915 exit(1);
7916 }
7917 monitor_init(monitor_hd, !nographic);
82c643ff 7918 }
82c643ff 7919
8d11df9e 7920 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
c03b0f0f
FB
7921 const char *devname = serial_devices[i];
7922 if (devname[0] != '\0' && strcmp(devname, "none")) {
7923 serial_hds[i] = qemu_chr_open(devname);
8d11df9e
FB
7924 if (!serial_hds[i]) {
7925 fprintf(stderr, "qemu: could not open serial device '%s'\n",
c03b0f0f 7926 devname);
8d11df9e
FB
7927 exit(1);
7928 }
c03b0f0f 7929 if (!strcmp(devname, "vc"))
7ba1260a 7930 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8d11df9e 7931 }
82c643ff 7932 }
82c643ff 7933
6508fe59 7934 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
c03b0f0f
FB
7935 const char *devname = parallel_devices[i];
7936 if (devname[0] != '\0' && strcmp(devname, "none")) {
7937 parallel_hds[i] = qemu_chr_open(devname);
6508fe59
FB
7938 if (!parallel_hds[i]) {
7939 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
c03b0f0f 7940 devname);
6508fe59
FB
7941 exit(1);
7942 }
c03b0f0f 7943 if (!strcmp(devname, "vc"))
7ba1260a 7944 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6508fe59
FB
7945 }
7946 }
7947
cc1daa40
FB
7948 machine->init(ram_size, vga_ram_size, boot_device,
7949 ds, fd_filename, snapshot,
94fc95cd 7950 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
73332e5c 7951
0d92ed30
PB
7952 /* init USB devices */
7953 if (usb_enabled) {
7954 for(i = 0; i < usb_devices_index; i++) {
7955 if (usb_device_add(usb_devices[i]) < 0) {
7956 fprintf(stderr, "Warning: could not add USB device %s\n",
7957 usb_devices[i]);
7958 }
7959 }
7960 }
7961
740733bb
TS
7962 if (display_state.dpy_refresh) {
7963 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
7964 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
7965 }
7f7f9873 7966
67b915a5 7967#ifdef CONFIG_GDBSTUB
b4608c04 7968 if (use_gdbstub) {
c636bb66
FB
7969 /* XXX: use standard host:port notation and modify options
7970 accordingly. */
cfc3475a
PB
7971 if (gdbserver_start(gdbstub_port) < 0) {
7972 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
c636bb66 7973 gdbstub_port);
8a7ddc38 7974 exit(1);
8a7ddc38 7975 }
67b915a5
FB
7976 } else
7977#endif
d63d307f 7978 if (loadvm)
faea38e7 7979 do_loadvm(loadvm);
d63d307f 7980
67b915a5 7981 {
5905b2e5
FB
7982 /* XXX: simplify init */
7983 read_passwords();
3c07f8e8 7984 if (autostart) {
5905b2e5
FB
7985 vm_start();
7986 }
0824d6fc 7987 }
ffd843bc 7988
71e3ceb8
TS
7989 if (daemonize) {
7990 uint8_t status = 0;
7991 ssize_t len;
7992 int fd;
7993
7994 again1:
7995 len = write(fds[1], &status, 1);
7996 if (len == -1 && (errno == EINTR))
7997 goto again1;
7998
7999 if (len != 1)
8000 exit(1);
8001
8002 fd = open("/dev/null", O_RDWR);
8003 if (fd == -1)
8004 exit(1);
8005
8006 dup2(fd, 0);
8007 dup2(fd, 1);
8008 dup2(fd, 2);
8009
8010 close(fd);
8011 }
8012
8a7ddc38 8013 main_loop();
40c3bac3 8014 quit_timers();
0824d6fc
FB
8015 return 0;
8016}