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