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