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