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